babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets an array of textures on the engine to be used in the shader.
  861. * @param channel Name of the variable.
  862. * @param textures Textures to set.
  863. */
  864. Effect.prototype.setTextureArray = function (channel, textures) {
  865. if (this._samplers.indexOf(channel + "Ex") === -1) {
  866. var initialPos = this._samplers.indexOf(channel);
  867. for (var index = 1; index < textures.length; index++) {
  868. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  869. }
  870. }
  871. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  872. };
  873. /**
  874. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  875. * @param channel Name of the sampler variable.
  876. * @param postProcess Post process to get the input texture from.
  877. */
  878. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  879. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  880. };
  881. /** @ignore */
  882. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  883. var cache = this._valueCache[uniformName];
  884. var flag = matrix.updateFlag;
  885. if (cache !== undefined && cache === flag) {
  886. return false;
  887. }
  888. this._valueCache[uniformName] = flag;
  889. return true;
  890. };
  891. /** @ignore */
  892. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  893. var cache = this._valueCache[uniformName];
  894. if (!cache) {
  895. cache = [x, y];
  896. this._valueCache[uniformName] = cache;
  897. return true;
  898. }
  899. var changed = false;
  900. if (cache[0] !== x) {
  901. cache[0] = x;
  902. changed = true;
  903. }
  904. if (cache[1] !== y) {
  905. cache[1] = y;
  906. changed = true;
  907. }
  908. return changed;
  909. };
  910. /** @ignore */
  911. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  912. var cache = this._valueCache[uniformName];
  913. if (!cache) {
  914. cache = [x, y, z];
  915. this._valueCache[uniformName] = cache;
  916. return true;
  917. }
  918. var changed = false;
  919. if (cache[0] !== x) {
  920. cache[0] = x;
  921. changed = true;
  922. }
  923. if (cache[1] !== y) {
  924. cache[1] = y;
  925. changed = true;
  926. }
  927. if (cache[2] !== z) {
  928. cache[2] = z;
  929. changed = true;
  930. }
  931. return changed;
  932. };
  933. /** @ignore */
  934. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  935. var cache = this._valueCache[uniformName];
  936. if (!cache) {
  937. cache = [x, y, z, w];
  938. this._valueCache[uniformName] = cache;
  939. return true;
  940. }
  941. var changed = false;
  942. if (cache[0] !== x) {
  943. cache[0] = x;
  944. changed = true;
  945. }
  946. if (cache[1] !== y) {
  947. cache[1] = y;
  948. changed = true;
  949. }
  950. if (cache[2] !== z) {
  951. cache[2] = z;
  952. changed = true;
  953. }
  954. if (cache[3] !== w) {
  955. cache[3] = w;
  956. changed = true;
  957. }
  958. return changed;
  959. };
  960. /**
  961. * Binds a buffer to a uniform.
  962. * @param buffer Buffer to bind.
  963. * @param name Name of the uniform variable to bind to.
  964. */
  965. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  966. var bufferName = this._uniformBuffersNames[name];
  967. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  968. return;
  969. }
  970. Effect._baseCache[bufferName] = buffer;
  971. this._engine.bindUniformBufferBase(buffer, bufferName);
  972. };
  973. /**
  974. * Binds block to a uniform.
  975. * @param blockName Name of the block to bind.
  976. * @param index Index to bind.
  977. */
  978. Effect.prototype.bindUniformBlock = function (blockName, index) {
  979. this._engine.bindUniformBlock(this._program, blockName, index);
  980. };
  981. /**
  982. * Sets an interger value on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param value Value to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setInt = function (uniformName, value) {
  988. var cache = this._valueCache[uniformName];
  989. if (cache !== undefined && cache === value)
  990. return this;
  991. this._valueCache[uniformName] = value;
  992. this._engine.setInt(this.getUniform(uniformName), value);
  993. return this;
  994. };
  995. /**
  996. * Sets an int array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setIntArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setIntArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets an float array on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param array array to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setFloatArray = function (uniformName, array) {
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1052. * @param uniformName Name of the variable.
  1053. * @param array array to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1063. * @param uniformName Name of the variable.
  1064. * @param array array to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1074. * @param uniformName Name of the variable.
  1075. * @param array array to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1079. this._valueCache[uniformName] = null;
  1080. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1081. return this;
  1082. };
  1083. /**
  1084. * Sets an array on a uniform variable.
  1085. * @param uniformName Name of the variable.
  1086. * @param array array to be set.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setArray = function (uniformName, array) {
  1090. this._valueCache[uniformName] = null;
  1091. this._engine.setArray(this.getUniform(uniformName), array);
  1092. return this;
  1093. };
  1094. /**
  1095. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1096. * @param uniformName Name of the variable.
  1097. * @param array array to be set.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setArray2 = function (uniformName, array) {
  1101. this._valueCache[uniformName] = null;
  1102. this._engine.setArray2(this.getUniform(uniformName), array);
  1103. return this;
  1104. };
  1105. /**
  1106. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1107. * @param uniformName Name of the variable.
  1108. * @param array array to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setArray3 = function (uniformName, array) {
  1112. this._valueCache[uniformName] = null;
  1113. this._engine.setArray3(this.getUniform(uniformName), array);
  1114. return this;
  1115. };
  1116. /**
  1117. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1118. * @param uniformName Name of the variable.
  1119. * @param array array to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setArray4 = function (uniformName, array) {
  1123. this._valueCache[uniformName] = null;
  1124. this._engine.setArray4(this.getUniform(uniformName), array);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets matrices on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param matrices matrices to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1134. if (!matrices) {
  1135. return this;
  1136. }
  1137. this._valueCache[uniformName] = null;
  1138. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets matrix on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param matrix matrix to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1148. if (this._cacheMatrix(uniformName, matrix)) {
  1149. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1155. * @param uniformName Name of the variable.
  1156. * @param matrix matrix to be set.
  1157. * @returns this effect.
  1158. */
  1159. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1160. this._valueCache[uniformName] = null;
  1161. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1166. * @param uniformName Name of the variable.
  1167. * @param matrix matrix to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1171. this._valueCache[uniformName] = null;
  1172. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param value value to be set.
  1179. * @returns this effect.
  1180. */
  1181. Effect.prototype.setFloat = function (uniformName, value) {
  1182. var cache = this._valueCache[uniformName];
  1183. if (cache !== undefined && cache === value)
  1184. return this;
  1185. this._valueCache[uniformName] = value;
  1186. this._engine.setFloat(this.getUniform(uniformName), value);
  1187. return this;
  1188. };
  1189. /**
  1190. * Sets a boolean on a uniform variable.
  1191. * @param uniformName Name of the variable.
  1192. * @param bool value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setBool = function (uniformName, bool) {
  1196. var cache = this._valueCache[uniformName];
  1197. if (cache !== undefined && cache === bool)
  1198. return this;
  1199. this._valueCache[uniformName] = bool;
  1200. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Vector2 on a uniform variable.
  1205. * @param uniformName Name of the variable.
  1206. * @param vector2 vector2 to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1210. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1211. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a float2 on a uniform variable.
  1217. * @param uniformName Name of the variable.
  1218. * @param x First float in float2.
  1219. * @param y Second float in float2.
  1220. * @returns this effect.
  1221. */
  1222. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1223. if (this._cacheFloat2(uniformName, x, y)) {
  1224. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1225. }
  1226. return this;
  1227. };
  1228. /**
  1229. * Sets a Vector3 on a uniform variable.
  1230. * @param uniformName Name of the variable.
  1231. * @param vector3 Value to be set.
  1232. * @returns this effect.
  1233. */
  1234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1235. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1236. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1237. }
  1238. return this;
  1239. };
  1240. /**
  1241. * Sets a float3 on a uniform variable.
  1242. * @param uniformName Name of the variable.
  1243. * @param x First float in float3.
  1244. * @param y Second float in float3.
  1245. * @param z Third float in float3.
  1246. * @returns this effect.
  1247. */
  1248. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1249. if (this._cacheFloat3(uniformName, x, y, z)) {
  1250. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1251. }
  1252. return this;
  1253. };
  1254. /**
  1255. * Sets a Vector4 on a uniform variable.
  1256. * @param uniformName Name of the variable.
  1257. * @param vector4 Value to be set.
  1258. * @returns this effect.
  1259. */
  1260. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1261. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1262. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1263. }
  1264. return this;
  1265. };
  1266. /**
  1267. * Sets a float4 on a uniform variable.
  1268. * @param uniformName Name of the variable.
  1269. * @param x First float in float4.
  1270. * @param y Second float in float4.
  1271. * @param z Third float in float4.
  1272. * @param w Fourth float in float4.
  1273. * @returns this effect.
  1274. */
  1275. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1276. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1277. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1278. }
  1279. return this;
  1280. };
  1281. /**
  1282. * Sets a Color3 on a uniform variable.
  1283. * @param uniformName Name of the variable.
  1284. * @param color3 Value to be set.
  1285. * @returns this effect.
  1286. */
  1287. Effect.prototype.setColor3 = function (uniformName, color3) {
  1288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1289. this._engine.setColor3(this.getUniform(uniformName), color3);
  1290. }
  1291. return this;
  1292. };
  1293. /**
  1294. * Sets a Color4 on a uniform variable.
  1295. * @param uniformName Name of the variable.
  1296. * @param color3 Value to be set.
  1297. * @param alpha Alpha value to be set.
  1298. * @returns this effect.
  1299. */
  1300. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1301. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1302. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1303. }
  1304. return this;
  1305. };
  1306. /**
  1307. * Sets a Color4 on a uniform variable
  1308. * @param uniformName defines the name of the variable
  1309. * @param color4 defines the value to be set
  1310. * @returns this effect.
  1311. */
  1312. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1313. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1314. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1315. }
  1316. return this;
  1317. };
  1318. /**
  1319. * Resets the cache of effects.
  1320. */
  1321. Effect.ResetCache = function () {
  1322. Effect._baseCache = {};
  1323. };
  1324. Effect._uniqueIdSeed = 0;
  1325. Effect._baseCache = {};
  1326. Effect._sourceCache = {};
  1327. // Statics
  1328. /**
  1329. * Store of each shader (The can be looked up using effect.key)
  1330. */
  1331. Effect.ShadersStore = {};
  1332. /**
  1333. * Store of each included file for a shader (The can be looked up using effect.key)
  1334. */
  1335. Effect.IncludesShadersStore = {};
  1336. return Effect;
  1337. }());
  1338. BABYLON.Effect = Effect;
  1339. })(BABYLON || (BABYLON = {}));
  1340. //# sourceMappingURL=babylon.effect.js.map
  1341. //# sourceMappingURL=babylon.types.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. var KeyboardEventTypes = /** @class */ (function () {
  1345. function KeyboardEventTypes() {
  1346. }
  1347. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1348. get: function () {
  1349. return KeyboardEventTypes._KEYDOWN;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1355. get: function () {
  1356. return KeyboardEventTypes._KEYUP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. KeyboardEventTypes._KEYDOWN = 0x01;
  1362. KeyboardEventTypes._KEYUP = 0x02;
  1363. return KeyboardEventTypes;
  1364. }());
  1365. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1366. var KeyboardInfo = /** @class */ (function () {
  1367. function KeyboardInfo(type, event) {
  1368. this.type = type;
  1369. this.event = event;
  1370. }
  1371. return KeyboardInfo;
  1372. }());
  1373. BABYLON.KeyboardInfo = KeyboardInfo;
  1374. /**
  1375. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1376. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1377. */
  1378. var KeyboardInfoPre = /** @class */ (function (_super) {
  1379. __extends(KeyboardInfoPre, _super);
  1380. function KeyboardInfoPre(type, event) {
  1381. var _this = _super.call(this, type, event) || this;
  1382. _this.skipOnPointerObservable = false;
  1383. return _this;
  1384. }
  1385. return KeyboardInfoPre;
  1386. }(KeyboardInfo));
  1387. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1388. })(BABYLON || (BABYLON = {}));
  1389. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1390. var BABYLON;
  1391. (function (BABYLON) {
  1392. var PointerEventTypes = /** @class */ (function () {
  1393. function PointerEventTypes() {
  1394. }
  1395. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1396. get: function () {
  1397. return PointerEventTypes._POINTERDOWN;
  1398. },
  1399. enumerable: true,
  1400. configurable: true
  1401. });
  1402. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1403. get: function () {
  1404. return PointerEventTypes._POINTERUP;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1410. get: function () {
  1411. return PointerEventTypes._POINTERMOVE;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERWHEEL;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERPICK;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERTAP;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERDOUBLETAP;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. PointerEventTypes._POINTERDOWN = 0x01;
  1445. PointerEventTypes._POINTERUP = 0x02;
  1446. PointerEventTypes._POINTERMOVE = 0x04;
  1447. PointerEventTypes._POINTERWHEEL = 0x08;
  1448. PointerEventTypes._POINTERPICK = 0x10;
  1449. PointerEventTypes._POINTERTAP = 0x20;
  1450. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1451. return PointerEventTypes;
  1452. }());
  1453. BABYLON.PointerEventTypes = PointerEventTypes;
  1454. var PointerInfoBase = /** @class */ (function () {
  1455. function PointerInfoBase(type, event) {
  1456. this.type = type;
  1457. this.event = event;
  1458. }
  1459. return PointerInfoBase;
  1460. }());
  1461. BABYLON.PointerInfoBase = PointerInfoBase;
  1462. /**
  1463. * This class is used to store pointer related info for the onPrePointerObservable event.
  1464. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1465. */
  1466. var PointerInfoPre = /** @class */ (function (_super) {
  1467. __extends(PointerInfoPre, _super);
  1468. function PointerInfoPre(type, event, localX, localY) {
  1469. var _this = _super.call(this, type, event) || this;
  1470. _this.skipOnPointerObservable = false;
  1471. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1472. return _this;
  1473. }
  1474. return PointerInfoPre;
  1475. }(PointerInfoBase));
  1476. BABYLON.PointerInfoPre = PointerInfoPre;
  1477. /**
  1478. * This type contains all the data related to a pointer event in Babylon.js.
  1479. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1480. */
  1481. var PointerInfo = /** @class */ (function (_super) {
  1482. __extends(PointerInfo, _super);
  1483. function PointerInfo(type, event, pickInfo) {
  1484. var _this = _super.call(this, type, event) || this;
  1485. _this.pickInfo = pickInfo;
  1486. return _this;
  1487. }
  1488. return PointerInfo;
  1489. }(PointerInfoBase));
  1490. BABYLON.PointerInfo = PointerInfo;
  1491. })(BABYLON || (BABYLON = {}));
  1492. //# sourceMappingURL=babylon.pointerEvents.js.map
  1493. var BABYLON;
  1494. (function (BABYLON) {
  1495. BABYLON.ToGammaSpace = 1 / 2.2;
  1496. BABYLON.ToLinearSpace = 2.2;
  1497. BABYLON.Epsilon = 0.001;
  1498. /**
  1499. * Class used to hold a RBG color
  1500. */
  1501. var Color3 = /** @class */ (function () {
  1502. /**
  1503. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1504. * @param r defines the red component (between 0 and 1, default is 0)
  1505. * @param g defines the green component (between 0 and 1, default is 0)
  1506. * @param b defines the blue component (between 0 and 1, default is 0)
  1507. */
  1508. function Color3(
  1509. /**
  1510. * Defines the red component (between 0 and 1, default is 0)
  1511. */
  1512. r,
  1513. /**
  1514. * Defines the green component (between 0 and 1, default is 0)
  1515. */
  1516. g,
  1517. /**
  1518. * Defines the blue component (between 0 and 1, default is 0)
  1519. */
  1520. b) {
  1521. if (r === void 0) { r = 0; }
  1522. if (g === void 0) { g = 0; }
  1523. if (b === void 0) { b = 0; }
  1524. this.r = r;
  1525. this.g = g;
  1526. this.b = b;
  1527. }
  1528. /**
  1529. * Creates a string with the Color3 current values
  1530. * @returns the string representation of the Color3 object
  1531. */
  1532. Color3.prototype.toString = function () {
  1533. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1534. };
  1535. /**
  1536. * Returns the string "Color3"
  1537. * @returns "Color3"
  1538. */
  1539. Color3.prototype.getClassName = function () {
  1540. return "Color3";
  1541. };
  1542. /**
  1543. * Compute the Color3 hash code
  1544. * @returns an unique number that can be used to hash Color3 objects
  1545. */
  1546. Color3.prototype.getHashCode = function () {
  1547. var hash = this.r || 0;
  1548. hash = (hash * 397) ^ (this.g || 0);
  1549. hash = (hash * 397) ^ (this.b || 0);
  1550. return hash;
  1551. };
  1552. // Operators
  1553. /**
  1554. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1555. * @param array defines the array where to store the r,g,b components
  1556. * @param index defines an optional index in the target array to define where to start storing values
  1557. * @returns the current Color3 object
  1558. */
  1559. Color3.prototype.toArray = function (array, index) {
  1560. if (index === undefined) {
  1561. index = 0;
  1562. }
  1563. array[index] = this.r;
  1564. array[index + 1] = this.g;
  1565. array[index + 2] = this.b;
  1566. return this;
  1567. };
  1568. /**
  1569. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1570. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1571. * @returns a new {BABYLON.Color4} object
  1572. */
  1573. Color3.prototype.toColor4 = function (alpha) {
  1574. if (alpha === void 0) { alpha = 1; }
  1575. return new Color4(this.r, this.g, this.b, alpha);
  1576. };
  1577. /**
  1578. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1579. * @returns the new array
  1580. */
  1581. Color3.prototype.asArray = function () {
  1582. var result = new Array();
  1583. this.toArray(result, 0);
  1584. return result;
  1585. };
  1586. /**
  1587. * Returns the luminance value
  1588. * @returns a float value
  1589. */
  1590. Color3.prototype.toLuminance = function () {
  1591. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1592. };
  1593. /**
  1594. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3 object
  1597. */
  1598. Color3.prototype.multiply = function (otherColor) {
  1599. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1600. };
  1601. /**
  1602. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines the Color3 object where to store the result
  1605. * @returns the current Color3
  1606. */
  1607. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1608. result.r = this.r * otherColor.r;
  1609. result.g = this.g * otherColor.g;
  1610. result.b = this.b * otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Determines equality between Color3 objects
  1615. * @param otherColor defines the second operand
  1616. * @returns true if the rgb values are equal to the passed ones
  1617. */
  1618. Color3.prototype.equals = function (otherColor) {
  1619. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1620. };
  1621. /**
  1622. * Determines equality between the current Color3 object and a set of r,b,g values
  1623. * @param r defines the red component to check
  1624. * @param g defines the green component to check
  1625. * @param b defines the blue component to check
  1626. * @returns true if the rgb values are equal to the passed ones
  1627. */
  1628. Color3.prototype.equalsFloats = function (r, g, b) {
  1629. return this.r === r && this.g === g && this.b === b;
  1630. };
  1631. /**
  1632. * Multiplies in place each rgb value by scale
  1633. * @param scale defines the scaling factor
  1634. * @returns the updated Color3.
  1635. */
  1636. Color3.prototype.scale = function (scale) {
  1637. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1638. };
  1639. /**
  1640. * Multiplies the rgb values by scale and stores the result into "result"
  1641. * @param scale defines the scaling factor
  1642. * @param result defines the Color3 object where to store the result
  1643. * @returns the unmodified current Color3.
  1644. */
  1645. Color3.prototype.scaleToRef = function (scale, result) {
  1646. result.r = this.r * scale;
  1647. result.g = this.g * scale;
  1648. result.b = this.b * scale;
  1649. return this;
  1650. };
  1651. /**
  1652. * Clamps the rgb values by the min and max values and stores the result into "result"
  1653. * @param min defines minimum clamping value (default is 0)
  1654. * @param max defines maximum clamping value (default is 1)
  1655. * @param result defines color to store the result into
  1656. * @returns the original Color3
  1657. */
  1658. Color3.prototype.clampToRef = function (min, max, result) {
  1659. if (min === void 0) { min = 0; }
  1660. if (max === void 0) { max = 1; }
  1661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1664. return this;
  1665. };
  1666. /**
  1667. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1668. * @param otherColor defines the second operand
  1669. * @returns the new Color3
  1670. */
  1671. Color3.prototype.add = function (otherColor) {
  1672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1673. };
  1674. /**
  1675. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1676. * @param otherColor defines the second operand
  1677. * @param result defines Color3 object to store the result into
  1678. * @returns the unmodified current Color3
  1679. */
  1680. Color3.prototype.addToRef = function (otherColor, result) {
  1681. result.r = this.r + otherColor.r;
  1682. result.g = this.g + otherColor.g;
  1683. result.b = this.b + otherColor.b;
  1684. return this;
  1685. };
  1686. /**
  1687. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1688. * @param otherColor defines the second operand
  1689. * @returns the new Color3
  1690. */
  1691. Color3.prototype.subtract = function (otherColor) {
  1692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1693. };
  1694. /**
  1695. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1696. * @param otherColor defines the second operand
  1697. * @param result defines Color3 object to store the result into
  1698. * @returns the unmodified current Color3
  1699. */
  1700. Color3.prototype.subtractToRef = function (otherColor, result) {
  1701. result.r = this.r - otherColor.r;
  1702. result.g = this.g - otherColor.g;
  1703. result.b = this.b - otherColor.b;
  1704. return this;
  1705. };
  1706. /**
  1707. * Copy the current object
  1708. * @returns a new Color3 copied the current one
  1709. */
  1710. Color3.prototype.clone = function () {
  1711. return new Color3(this.r, this.g, this.b);
  1712. };
  1713. /**
  1714. * Copies the rgb values from the source in the current Color3
  1715. * @param source defines the source Color3 object
  1716. * @returns the updated Color3 object
  1717. */
  1718. Color3.prototype.copyFrom = function (source) {
  1719. this.r = source.r;
  1720. this.g = source.g;
  1721. this.b = source.b;
  1722. return this;
  1723. };
  1724. /**
  1725. * Updates the Color3 rgb values from the passed floats
  1726. * @param r defines the red component to read from
  1727. * @param g defines the green component to read from
  1728. * @param b defines the blue component to read from
  1729. * @returns the current Color3 object
  1730. */
  1731. Color3.prototype.copyFromFloats = function (r, g, b) {
  1732. this.r = r;
  1733. this.g = g;
  1734. this.b = b;
  1735. return this;
  1736. };
  1737. /**
  1738. * Updates the Color3 rgb values from the passed floats
  1739. * @param r defines the red component to read from
  1740. * @param g defines the green component to read from
  1741. * @param b defines the blue component to read from
  1742. * @returns the current Color3 object
  1743. */
  1744. Color3.prototype.set = function (r, g, b) {
  1745. return this.copyFromFloats(r, g, b);
  1746. };
  1747. /**
  1748. * Compute the Color3 hexadecimal code as a string
  1749. * @returns a string containing the hexadecimal representation of the Color3 object
  1750. */
  1751. Color3.prototype.toHexString = function () {
  1752. var intR = (this.r * 255) | 0;
  1753. var intG = (this.g * 255) | 0;
  1754. var intB = (this.b * 255) | 0;
  1755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1756. };
  1757. /**
  1758. * Computes a new Color3 converted from the current one to linear space
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.prototype.toLinearSpace = function () {
  1762. var convertedColor = new Color3();
  1763. this.toLinearSpaceToRef(convertedColor);
  1764. return convertedColor;
  1765. };
  1766. /**
  1767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1768. * @param convertedColor defines the Color3 object where to store the linear space version
  1769. * @returns the unmodified Color3
  1770. */
  1771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1775. return this;
  1776. };
  1777. /**
  1778. * Computes a new Color3 converted from the current one to gamma space
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.prototype.toGammaSpace = function () {
  1782. var convertedColor = new Color3();
  1783. this.toGammaSpaceToRef(convertedColor);
  1784. return convertedColor;
  1785. };
  1786. /**
  1787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1788. * @param convertedColor defines the Color3 object where to store the gamma space version
  1789. * @returns the unmodified Color3
  1790. */
  1791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1795. return this;
  1796. };
  1797. // Statics
  1798. /**
  1799. * Creates a new Color3 from the string containing valid hexadecimal values
  1800. * @param hex defines a string containing valid hexadecimal values
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.FromHexString = function (hex) {
  1804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1805. return new Color3(0, 0, 0);
  1806. }
  1807. var r = parseInt(hex.substring(1, 3), 16);
  1808. var g = parseInt(hex.substring(3, 5), 16);
  1809. var b = parseInt(hex.substring(5, 7), 16);
  1810. return Color3.FromInts(r, g, b);
  1811. };
  1812. /**
  1813. * Creates a new Vector3 from the starting index of the passed array
  1814. * @param array defines the source array
  1815. * @param offset defines an offset in the source array
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromArray = function (array, offset) {
  1819. if (offset === void 0) { offset = 0; }
  1820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1821. };
  1822. /**
  1823. * Creates a new Color3 from integer values (< 256)
  1824. * @param r defines the red component to read from (value between 0 and 255)
  1825. * @param g defines the green component to read from (value between 0 and 255)
  1826. * @param b defines the blue component to read from (value between 0 and 255)
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.FromInts = function (r, g, b) {
  1830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param start defines the start Color3 value
  1835. * @param end defines the end Color3 value
  1836. * @param amount defines the gradient value between start and end
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Lerp = function (start, end, amount) {
  1840. var r = start.r + ((end.r - start.r) * amount);
  1841. var g = start.g + ((end.g - start.g) * amount);
  1842. var b = start.b + ((end.b - start.b) * amount);
  1843. return new Color3(r, g, b);
  1844. };
  1845. /**
  1846. * Returns a Color3 value containing a red color
  1847. * @returns a new Color3 object
  1848. */
  1849. Color3.Red = function () { return new Color3(1, 0, 0); };
  1850. /**
  1851. * Returns a Color3 value containing a green color
  1852. * @returns a new Color3 object
  1853. */
  1854. Color3.Green = function () { return new Color3(0, 1, 0); };
  1855. /**
  1856. * Returns a Color3 value containing a blue color
  1857. * @returns a new Color3 object
  1858. */
  1859. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1860. /**
  1861. * Returns a Color3 value containing a black color
  1862. * @returns a new Color3 object
  1863. */
  1864. Color3.Black = function () { return new Color3(0, 0, 0); };
  1865. /**
  1866. * Returns a Color3 value containing a white color
  1867. * @returns a new Color3 object
  1868. */
  1869. Color3.White = function () { return new Color3(1, 1, 1); };
  1870. /**
  1871. * Returns a Color3 value containing a purple color
  1872. * @returns a new Color3 object
  1873. */
  1874. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1875. /**
  1876. * Returns a Color3 value containing a magenta color
  1877. * @returns a new Color3 object
  1878. */
  1879. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1880. /**
  1881. * Returns a Color3 value containing a yellow color
  1882. * @returns a new Color3 object
  1883. */
  1884. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1885. /**
  1886. * Returns a Color3 value containing a gray color
  1887. * @returns a new Color3 object
  1888. */
  1889. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1890. /**
  1891. * Returns a Color3 value containing a teal color
  1892. * @returns a new Color3 object
  1893. */
  1894. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1895. /**
  1896. * Returns a Color3 value containing a random color
  1897. * @returns a new Color3 object
  1898. */
  1899. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1900. return Color3;
  1901. }());
  1902. BABYLON.Color3 = Color3;
  1903. /**
  1904. * Class used to hold a RBGA color
  1905. */
  1906. var Color4 = /** @class */ (function () {
  1907. /**
  1908. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1909. * @param r defines the red component (between 0 and 1, default is 0)
  1910. * @param g defines the green component (between 0 and 1, default is 0)
  1911. * @param b defines the blue component (between 0 and 1, default is 0)
  1912. * @param a defines the alpha component (between 0 and 1, default is 1)
  1913. */
  1914. function Color4(
  1915. /**
  1916. * Defines the red component (between 0 and 1, default is 0)
  1917. */
  1918. r,
  1919. /**
  1920. * Defines the green component (between 0 and 1, default is 0)
  1921. */
  1922. g,
  1923. /**
  1924. * Defines the blue component (between 0 and 1, default is 0)
  1925. */
  1926. b,
  1927. /**
  1928. * Defines the alpha component (between 0 and 1, default is 1)
  1929. */
  1930. a) {
  1931. if (r === void 0) { r = 0; }
  1932. if (g === void 0) { g = 0; }
  1933. if (b === void 0) { b = 0; }
  1934. if (a === void 0) { a = 1; }
  1935. this.r = r;
  1936. this.g = g;
  1937. this.b = b;
  1938. this.a = a;
  1939. }
  1940. // Operators
  1941. /**
  1942. * Adds in place the passed Color4 values to the current Color4 object
  1943. * @param right defines the second operand
  1944. * @returns the current updated Color4 object
  1945. */
  1946. Color4.prototype.addInPlace = function (right) {
  1947. this.r += right.r;
  1948. this.g += right.g;
  1949. this.b += right.b;
  1950. this.a += right.a;
  1951. return this;
  1952. };
  1953. /**
  1954. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1955. * @returns the new array
  1956. */
  1957. Color4.prototype.asArray = function () {
  1958. var result = new Array();
  1959. this.toArray(result, 0);
  1960. return result;
  1961. };
  1962. /**
  1963. * Stores from the starting index in the passed array the Color4 successive values
  1964. * @param array defines the array where to store the r,g,b components
  1965. * @param index defines an optional index in the target array to define where to start storing values
  1966. * @returns the current Color4 object
  1967. */
  1968. Color4.prototype.toArray = function (array, index) {
  1969. if (index === undefined) {
  1970. index = 0;
  1971. }
  1972. array[index] = this.r;
  1973. array[index + 1] = this.g;
  1974. array[index + 2] = this.b;
  1975. array[index + 3] = this.a;
  1976. return this;
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.add = function (right) {
  1984. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1985. };
  1986. /**
  1987. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1988. * @param right defines the second operand
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.subtract = function (right) {
  1992. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1993. };
  1994. /**
  1995. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1996. * @param right defines the second operand
  1997. * @param result defines the Color4 object where to store the result
  1998. * @returns the current Color4 object
  1999. */
  2000. Color4.prototype.subtractToRef = function (right, result) {
  2001. result.r = this.r - right.r;
  2002. result.g = this.g - right.g;
  2003. result.b = this.b - right.b;
  2004. result.a = this.a - right.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Creates a new Color4 with the current Color4 values multiplied by scale
  2009. * @param scale defines the scaling factor to apply
  2010. * @returns a new Color4 object
  2011. */
  2012. Color4.prototype.scale = function (scale) {
  2013. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2014. };
  2015. /**
  2016. * Multiplies the current Color4 values by scale and stores the result in "result"
  2017. * @param scale defines the scaling factor to apply
  2018. * @param result defines the Color4 object where to store the result
  2019. * @returns the current Color4.
  2020. */
  2021. Color4.prototype.scaleToRef = function (scale, result) {
  2022. result.r = this.r * scale;
  2023. result.g = this.g * scale;
  2024. result.b = this.b * scale;
  2025. result.a = this.a * scale;
  2026. return this;
  2027. };
  2028. /**
  2029. * Clamps the rgb values by the min and max values and stores the result into "result"
  2030. * @param min defines minimum clamping value (default is 0)
  2031. * @param max defines maximum clamping value (default is 1)
  2032. * @param result defines color to store the result into.
  2033. * @returns the cuurent Color4
  2034. */
  2035. Color4.prototype.clampToRef = function (min, max, result) {
  2036. if (min === void 0) { min = 0; }
  2037. if (max === void 0) { max = 1; }
  2038. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2039. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2040. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2041. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2042. return this;
  2043. };
  2044. /**
  2045. * Multipy an Color4 value by another and return a new Color4 object
  2046. * @param color defines the Color4 value to multiply by
  2047. * @returns a new Color4 object
  2048. */
  2049. Color4.prototype.multiply = function (color) {
  2050. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2051. };
  2052. /**
  2053. * Multipy a Color4 value by another and push the result in a reference value
  2054. * @param color defines the Color4 value to multiply by
  2055. * @param result defines the Color4 to fill the result in
  2056. * @returns the result Color4
  2057. */
  2058. Color4.prototype.multiplyToRef = function (color, result) {
  2059. result.r = this.r * color.r;
  2060. result.g = this.g * color.g;
  2061. result.b = this.b * color.b;
  2062. result.a = this.a * color.a;
  2063. return result;
  2064. };
  2065. /**
  2066. * Creates a string with the Color4 current values
  2067. * @returns the string representation of the Color4 object
  2068. */
  2069. Color4.prototype.toString = function () {
  2070. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2071. };
  2072. /**
  2073. * Returns the string "Color4"
  2074. * @returns "Color4"
  2075. */
  2076. Color4.prototype.getClassName = function () {
  2077. return "Color4";
  2078. };
  2079. /**
  2080. * Compute the Color4 hash code
  2081. * @returns an unique number that can be used to hash Color4 objects
  2082. */
  2083. Color4.prototype.getHashCode = function () {
  2084. var hash = this.r || 0;
  2085. hash = (hash * 397) ^ (this.g || 0);
  2086. hash = (hash * 397) ^ (this.b || 0);
  2087. hash = (hash * 397) ^ (this.a || 0);
  2088. return hash;
  2089. };
  2090. /**
  2091. * Creates a new Color4 copied from the current one
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.clone = function () {
  2095. return new Color4(this.r, this.g, this.b, this.a);
  2096. };
  2097. /**
  2098. * Copies the passed Color4 values into the current one
  2099. * @param source defines the source Color4 object
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFrom = function (source) {
  2103. this.r = source.r;
  2104. this.g = source.g;
  2105. this.b = source.b;
  2106. this.a = source.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the passed float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2118. this.r = r;
  2119. this.g = g;
  2120. this.b = b;
  2121. this.a = a;
  2122. return this;
  2123. };
  2124. /**
  2125. * Copies the passed float values into the current one
  2126. * @param r defines the red component to read from
  2127. * @param g defines the green component to read from
  2128. * @param b defines the blue component to read from
  2129. * @param a defines the alpha component to read from
  2130. * @returns the current updated Color4 object
  2131. */
  2132. Color4.prototype.set = function (r, g, b, a) {
  2133. return this.copyFromFloats(r, g, b, a);
  2134. };
  2135. /**
  2136. * Compute the Color4 hexadecimal code as a string
  2137. * @returns a string containing the hexadecimal representation of the Color4 object
  2138. */
  2139. Color4.prototype.toHexString = function () {
  2140. var intR = (this.r * 255) | 0;
  2141. var intG = (this.g * 255) | 0;
  2142. var intB = (this.b * 255) | 0;
  2143. var intA = (this.a * 255) | 0;
  2144. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2145. };
  2146. /**
  2147. * Computes a new Color4 converted from the current one to linear space
  2148. * @returns a new Color4 object
  2149. */
  2150. Color4.prototype.toLinearSpace = function () {
  2151. var convertedColor = new Color4();
  2152. this.toLinearSpaceToRef(convertedColor);
  2153. return convertedColor;
  2154. };
  2155. /**
  2156. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2157. * @param convertedColor defines the Color4 object where to store the linear space version
  2158. * @returns the unmodified Color4
  2159. */
  2160. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2164. convertedColor.a = this.a;
  2165. return this;
  2166. };
  2167. /**
  2168. * Computes a new Color4 converted from the current one to gamma space
  2169. * @returns a new Color4 object
  2170. */
  2171. Color4.prototype.toGammaSpace = function () {
  2172. var convertedColor = new Color4();
  2173. this.toGammaSpaceToRef(convertedColor);
  2174. return convertedColor;
  2175. };
  2176. /**
  2177. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2178. * @param convertedColor defines the Color4 object where to store the gamma space version
  2179. * @returns the unmodified Color4
  2180. */
  2181. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2182. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2183. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2184. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2185. convertedColor.a = this.a;
  2186. return this;
  2187. };
  2188. // Statics
  2189. /**
  2190. * Creates a new Color4 from the string containing valid hexadecimal values
  2191. * @param hex defines a string containing valid hexadecimal values
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromHexString = function (hex) {
  2195. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2196. return new Color4(0.0, 0.0, 0.0, 0.0);
  2197. }
  2198. var r = parseInt(hex.substring(1, 3), 16);
  2199. var g = parseInt(hex.substring(3, 5), 16);
  2200. var b = parseInt(hex.substring(5, 7), 16);
  2201. var a = parseInt(hex.substring(7, 9), 16);
  2202. return Color4.FromInts(r, g, b, a);
  2203. };
  2204. /**
  2205. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2206. * @param left defines the start value
  2207. * @param right defines the end value
  2208. * @param amount defines the gradient factor
  2209. * @returns a new Color4 object
  2210. */
  2211. Color4.Lerp = function (left, right, amount) {
  2212. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2213. Color4.LerpToRef(left, right, amount, result);
  2214. return result;
  2215. };
  2216. /**
  2217. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @param result defines the Color4 object where to store data
  2222. */
  2223. Color4.LerpToRef = function (left, right, amount, result) {
  2224. result.r = left.r + (right.r - left.r) * amount;
  2225. result.g = left.g + (right.g - left.g) * amount;
  2226. result.b = left.b + (right.b - left.b) * amount;
  2227. result.a = left.a + (right.a - left.a) * amount;
  2228. };
  2229. /**
  2230. * Creates a new Color4 from the starting index element of the passed array
  2231. * @param array defines the source array to read from
  2232. * @param offset defines the offset in the source array
  2233. * @returns a new Color4 object
  2234. */
  2235. Color4.FromArray = function (array, offset) {
  2236. if (offset === void 0) { offset = 0; }
  2237. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2238. };
  2239. /**
  2240. * Creates a new Color3 from integer values (< 256)
  2241. * @param r defines the red component to read from (value between 0 and 255)
  2242. * @param g defines the green component to read from (value between 0 and 255)
  2243. * @param b defines the blue component to read from (value between 0 and 255)
  2244. * @param a defines the alpha component to read from (value between 0 and 255)
  2245. * @returns a new Color3 object
  2246. */
  2247. Color4.FromInts = function (r, g, b, a) {
  2248. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2249. };
  2250. /**
  2251. * Check the content of a given array and convert it to an array containing RGBA data
  2252. * If the original array was already containing count * 4 values then it is returned directly
  2253. * @param colors defines the array to check
  2254. * @param count defines the number of RGBA data to expect
  2255. * @returns an array containing count * 4 values (RGBA)
  2256. */
  2257. Color4.CheckColors4 = function (colors, count) {
  2258. // Check if color3 was used
  2259. if (colors.length === count * 3) {
  2260. var colors4 = [];
  2261. for (var index = 0; index < colors.length; index += 3) {
  2262. var newIndex = (index / 3) * 4;
  2263. colors4[newIndex] = colors[index];
  2264. colors4[newIndex + 1] = colors[index + 1];
  2265. colors4[newIndex + 2] = colors[index + 2];
  2266. colors4[newIndex + 3] = 1.0;
  2267. }
  2268. return colors4;
  2269. }
  2270. return colors;
  2271. };
  2272. return Color4;
  2273. }());
  2274. BABYLON.Color4 = Color4;
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the passed x and y coordinates.
  2278. */
  2279. function Vector2(x, y) {
  2280. this.x = x;
  2281. this.y = y;
  2282. }
  2283. /**
  2284. * Returns a string with the Vector2 coordinates.
  2285. */
  2286. Vector2.prototype.toString = function () {
  2287. return "{X: " + this.x + " Y:" + this.y + "}";
  2288. };
  2289. /**
  2290. * Returns the string "Vector2"
  2291. */
  2292. Vector2.prototype.getClassName = function () {
  2293. return "Vector2";
  2294. };
  2295. /**
  2296. * Returns the Vector2 hash code as a number.
  2297. */
  2298. Vector2.prototype.getHashCode = function () {
  2299. var hash = this.x || 0;
  2300. hash = (hash * 397) ^ (this.y || 0);
  2301. return hash;
  2302. };
  2303. // Operators
  2304. /**
  2305. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2306. * Returns the Vector2.
  2307. */
  2308. Vector2.prototype.toArray = function (array, index) {
  2309. if (index === void 0) { index = 0; }
  2310. array[index] = this.x;
  2311. array[index + 1] = this.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Returns a new array with 2 elements : the Vector2 coordinates.
  2316. */
  2317. Vector2.prototype.asArray = function () {
  2318. var result = new Array();
  2319. this.toArray(result, 0);
  2320. return result;
  2321. };
  2322. /**
  2323. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2324. * Returns the updated Vector2.
  2325. */
  2326. Vector2.prototype.copyFrom = function (source) {
  2327. this.x = source.x;
  2328. this.y = source.y;
  2329. return this;
  2330. };
  2331. /**
  2332. * Sets the Vector2 coordinates with the passed floats.
  2333. * Returns the updated Vector2.
  2334. */
  2335. Vector2.prototype.copyFromFloats = function (x, y) {
  2336. this.x = x;
  2337. this.y = y;
  2338. return this;
  2339. };
  2340. /**
  2341. * Sets the Vector2 coordinates with the passed floats.
  2342. * Returns the updated Vector2.
  2343. */
  2344. Vector2.prototype.set = function (x, y) {
  2345. return this.copyFromFloats(x, y);
  2346. };
  2347. /**
  2348. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2349. */
  2350. Vector2.prototype.add = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2355. * Returns the Vector2.
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2364. * Returns the updated Vector2.
  2365. */
  2366. Vector2.prototype.addInPlace = function (otherVector) {
  2367. this.x += otherVector.x;
  2368. this.y += otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2373. */
  2374. Vector2.prototype.addVector3 = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2379. */
  2380. Vector2.prototype.subtract = function (otherVector) {
  2381. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2382. };
  2383. /**
  2384. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2388. result.x = this.x - otherVector.x;
  2389. result.y = this.y - otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2394. * Returns the updated Vector2.
  2395. */
  2396. Vector2.prototype.subtractInPlace = function (otherVector) {
  2397. this.x -= otherVector.x;
  2398. this.y -= otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2406. this.x *= otherVector.x;
  2407. this.y *= otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2412. */
  2413. Vector2.prototype.multiply = function (otherVector) {
  2414. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2415. };
  2416. /**
  2417. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2418. * Returns the Vector2.
  2419. */
  2420. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2421. result.x = this.x * otherVector.x;
  2422. result.y = this.y * otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2427. */
  2428. Vector2.prototype.multiplyByFloats = function (x, y) {
  2429. return new Vector2(this.x * x, this.y * y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2433. */
  2434. Vector2.prototype.divide = function (otherVector) {
  2435. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2436. };
  2437. /**
  2438. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2439. * Returns the Vector2.
  2440. */
  2441. Vector2.prototype.divideToRef = function (otherVector, result) {
  2442. result.x = this.x / otherVector.x;
  2443. result.y = this.y / otherVector.y;
  2444. return this;
  2445. };
  2446. /**
  2447. * Divides the current Vector3 coordinates by the passed ones.
  2448. * Returns the updated Vector3.
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 with current Vector2 negated coordinates.
  2455. */
  2456. Vector2.prototype.negate = function () {
  2457. return new Vector2(-this.x, -this.y);
  2458. };
  2459. /**
  2460. * Multiply the Vector2 coordinates by scale.
  2461. * Returns the updated Vector2.
  2462. */
  2463. Vector2.prototype.scaleInPlace = function (scale) {
  2464. this.x *= scale;
  2465. this.y *= scale;
  2466. return this;
  2467. };
  2468. /**
  2469. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2470. */
  2471. Vector2.prototype.scale = function (scale) {
  2472. return new Vector2(this.x * scale, this.y * scale);
  2473. };
  2474. /**
  2475. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2476. */
  2477. Vector2.prototype.equals = function (otherVector) {
  2478. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2479. };
  2480. /**
  2481. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2482. */
  2483. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2484. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2485. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2486. };
  2487. // Properties
  2488. /**
  2489. * Returns the vector length (float).
  2490. */
  2491. Vector2.prototype.length = function () {
  2492. return Math.sqrt(this.x * this.x + this.y * this.y);
  2493. };
  2494. /**
  2495. * Returns the vector squared length (float);
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector.
  2503. * Returns the updated Vector2.
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 copied from the Vector2.
  2516. */
  2517. Vector2.prototype.clone = function () {
  2518. return new Vector2(this.x, this.y);
  2519. };
  2520. // Statics
  2521. /**
  2522. * Returns a new Vector2(0, 0)
  2523. */
  2524. Vector2.Zero = function () {
  2525. return new Vector2(0, 0);
  2526. };
  2527. /**
  2528. * Returns a new Vector2(1, 1)
  2529. */
  2530. Vector2.One = function () {
  2531. return new Vector2(1, 1);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 set from the passed index element of the passed array.
  2535. */
  2536. Vector2.FromArray = function (array, offset) {
  2537. if (offset === void 0) { offset = 0; }
  2538. return new Vector2(array[offset], array[offset + 1]);
  2539. };
  2540. /**
  2541. * Sets "result" from the passed index element of the passed array.
  2542. */
  2543. Vector2.FromArrayToRef = function (array, offset, result) {
  2544. result.x = array[offset];
  2545. result.y = array[offset + 1];
  2546. };
  2547. /**
  2548. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2549. */
  2550. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2551. var squared = amount * amount;
  2552. var cubed = amount * squared;
  2553. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2554. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2555. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2556. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2557. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2558. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2559. return new Vector2(x, y);
  2560. };
  2561. /**
  2562. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2563. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2564. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2565. */
  2566. Vector2.Clamp = function (value, min, max) {
  2567. var x = value.x;
  2568. x = (x > max.x) ? max.x : x;
  2569. x = (x < min.x) ? min.x : x;
  2570. var y = value.y;
  2571. y = (y > max.y) ? max.y : y;
  2572. y = (y < min.y) ? min.y : y;
  2573. return new Vector2(x, y);
  2574. };
  2575. /**
  2576. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2577. */
  2578. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2579. var squared = amount * amount;
  2580. var cubed = amount * squared;
  2581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2583. var part3 = (cubed - (2.0 * squared)) + amount;
  2584. var part4 = cubed - squared;
  2585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2587. return new Vector2(x, y);
  2588. };
  2589. /**
  2590. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2591. */
  2592. Vector2.Lerp = function (start, end, amount) {
  2593. var x = start.x + ((end.x - start.x) * amount);
  2594. var y = start.y + ((end.y - start.y) * amount);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns the dot product (float) of the vector "left" and the vector "right".
  2599. */
  2600. Vector2.Dot = function (left, right) {
  2601. return left.x * right.x + left.y * right.y;
  2602. };
  2603. /**
  2604. * Returns a new Vector2 equal to the normalized passed vector.
  2605. */
  2606. Vector2.Normalize = function (vector) {
  2607. var newVector = vector.clone();
  2608. newVector.normalize();
  2609. return newVector;
  2610. };
  2611. /**
  2612. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2613. */
  2614. Vector2.Minimize = function (left, right) {
  2615. var x = (left.x < right.x) ? left.x : right.x;
  2616. var y = (left.y < right.y) ? left.y : right.y;
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Maximize = function (left, right) {
  2623. var x = (left.x > right.x) ? left.x : right.x;
  2624. var y = (left.y > right.y) ? left.y : right.y;
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2629. */
  2630. Vector2.Transform = function (vector, transformation) {
  2631. var r = Vector2.Zero();
  2632. Vector2.TransformToRef(vector, transformation, r);
  2633. return r;
  2634. };
  2635. /**
  2636. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2637. */
  2638. Vector2.TransformToRef = function (vector, transformation, result) {
  2639. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2640. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2641. result.x = x;
  2642. result.y = y;
  2643. };
  2644. /**
  2645. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2646. */
  2647. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2648. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2649. var sign = a < 0 ? -1 : 1;
  2650. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2651. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2652. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2653. };
  2654. /**
  2655. * Returns the distance (float) between the vectors "value1" and "value2".
  2656. */
  2657. Vector2.Distance = function (value1, value2) {
  2658. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2659. };
  2660. /**
  2661. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2662. */
  2663. Vector2.DistanceSquared = function (value1, value2) {
  2664. var x = value1.x - value2.x;
  2665. var y = value1.y - value2.y;
  2666. return (x * x) + (y * y);
  2667. };
  2668. /**
  2669. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2670. */
  2671. Vector2.Center = function (value1, value2) {
  2672. var center = value1.add(value2);
  2673. center.scaleInPlace(0.5);
  2674. return center;
  2675. };
  2676. /**
  2677. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2678. */
  2679. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2680. var l2 = Vector2.DistanceSquared(segA, segB);
  2681. if (l2 === 0.0) {
  2682. return Vector2.Distance(p, segA);
  2683. }
  2684. var v = segB.subtract(segA);
  2685. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2686. var proj = segA.add(v.multiplyByFloats(t, t));
  2687. return Vector2.Distance(p, proj);
  2688. };
  2689. return Vector2;
  2690. }());
  2691. BABYLON.Vector2 = Vector2;
  2692. /**
  2693. * Classed used to store (x,y,z) vector representation
  2694. * A Vector3 is the main object used in 3D geometry
  2695. * It can represent etiher the coordinates of a point the space, either a direction
  2696. * Reminder: Babylon.js uses a left handed forward facing system
  2697. */
  2698. var Vector3 = /** @class */ (function () {
  2699. /**
  2700. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2701. * @param x defines the first coordinates (on X axis)
  2702. * @param y defines the second coordinates (on Y axis)
  2703. * @param z defines the third coordinates (on Z axis)
  2704. */
  2705. function Vector3(
  2706. /**
  2707. * Defines the first coordinates (on X axis)
  2708. */
  2709. x,
  2710. /**
  2711. * Defines the second coordinates (on Y axis)
  2712. */
  2713. y,
  2714. /**
  2715. * Defines the third coordinates (on Z axis)
  2716. */
  2717. z) {
  2718. this.x = x;
  2719. this.y = y;
  2720. this.z = z;
  2721. }
  2722. /**
  2723. * Creates a string representation of the Vector3
  2724. * @returns a string with the Vector3 coordinates.
  2725. */
  2726. Vector3.prototype.toString = function () {
  2727. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2728. };
  2729. /**
  2730. * Gets the class name
  2731. * @returns the string "Vector3"
  2732. */
  2733. Vector3.prototype.getClassName = function () {
  2734. return "Vector3";
  2735. };
  2736. /**
  2737. * Creates the Vector3 hash code
  2738. * @returns a number which tends to be unique between Vector3 instances
  2739. */
  2740. Vector3.prototype.getHashCode = function () {
  2741. var hash = this.x || 0;
  2742. hash = (hash * 397) ^ (this.y || 0);
  2743. hash = (hash * 397) ^ (this.z || 0);
  2744. return hash;
  2745. };
  2746. // Operators
  2747. /**
  2748. * Creates an array containing three elements : the coordinates of the Vector3
  2749. * @returns a new array of numbers
  2750. */
  2751. Vector3.prototype.asArray = function () {
  2752. var result = [];
  2753. this.toArray(result, 0);
  2754. return result;
  2755. };
  2756. /**
  2757. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2758. * @param array defines the destination array
  2759. * @param index defines the offset in the destination array
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.toArray = function (array, index) {
  2763. if (index === void 0) { index = 0; }
  2764. array[index] = this.x;
  2765. array[index + 1] = this.y;
  2766. array[index + 2] = this.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2771. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2772. */
  2773. Vector3.prototype.toQuaternion = function () {
  2774. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2775. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2776. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2777. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2778. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2779. var cosy = Math.cos(this.y * 0.5);
  2780. var siny = Math.sin(this.y * 0.5);
  2781. result.x = coszMinusx * siny;
  2782. result.y = -sinzMinusx * siny;
  2783. result.z = sinxPlusz * cosy;
  2784. result.w = cosxPlusz * cosy;
  2785. return result;
  2786. };
  2787. /**
  2788. * Adds the passed vector to the current Vector3
  2789. * @param otherVector defines the second operand
  2790. * @returns the current updated Vector3
  2791. */
  2792. Vector3.prototype.addInPlace = function (otherVector) {
  2793. this.x += otherVector.x;
  2794. this.y += otherVector.y;
  2795. this.z += otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2800. * @param otherVector defines the second operand
  2801. * @returns the resulting Vector3
  2802. */
  2803. Vector3.prototype.add = function (otherVector) {
  2804. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2805. };
  2806. /**
  2807. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2808. * @param otherVector defines the second operand
  2809. * @param result defines the Vector3 object where to store the result
  2810. * @returns the current Vector3
  2811. */
  2812. Vector3.prototype.addToRef = function (otherVector, result) {
  2813. result.x = this.x + otherVector.x;
  2814. result.y = this.y + otherVector.y;
  2815. result.z = this.z + otherVector.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Subtract the passed vector from the current Vector3
  2820. * @param otherVector defines the second operand
  2821. * @returns the current updated Vector3
  2822. */
  2823. Vector3.prototype.subtractInPlace = function (otherVector) {
  2824. this.x -= otherVector.x;
  2825. this.y -= otherVector.y;
  2826. this.z -= otherVector.z;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2831. * @param otherVector defines the second operand
  2832. * @returns the resulting Vector3
  2833. */
  2834. Vector3.prototype.subtract = function (otherVector) {
  2835. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2836. };
  2837. /**
  2838. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2839. * @param otherVector defines the second operand
  2840. * @param result defines the Vector3 object where to store the result
  2841. * @returns the current Vector3
  2842. */
  2843. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2844. result.x = this.x - otherVector.x;
  2845. result.y = this.y - otherVector.y;
  2846. result.z = this.z - otherVector.z;
  2847. return this;
  2848. };
  2849. /**
  2850. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2857. return new Vector3(this.x - x, this.y - y, this.z - z);
  2858. };
  2859. /**
  2860. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2861. * @param x defines the x coordinate of the operand
  2862. * @param y defines the y coordinate of the operand
  2863. * @param z defines the z coordinate of the operand
  2864. * @param result defines the Vector3 object where to store the result
  2865. * @returns the current Vector3
  2866. */
  2867. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2868. result.x = this.x - x;
  2869. result.y = this.y - y;
  2870. result.z = this.z - z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2875. * @returns a new Vector3
  2876. */
  2877. Vector3.prototype.negate = function () {
  2878. return new Vector3(-this.x, -this.y, -this.z);
  2879. };
  2880. /**
  2881. * Multiplies the Vector3 coordinates by the float "scale"
  2882. * @param scale defines the multiplier factor
  2883. * @returns the current updated Vector3
  2884. */
  2885. Vector3.prototype.scaleInPlace = function (scale) {
  2886. this.x *= scale;
  2887. this.y *= scale;
  2888. this.z *= scale;
  2889. return this;
  2890. };
  2891. /**
  2892. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2893. * @param scale defines the multiplier factor
  2894. * @returns a new Vector3
  2895. */
  2896. Vector3.prototype.scale = function (scale) {
  2897. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2898. };
  2899. /**
  2900. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2901. * @param scale defines the multiplier factor
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.scaleToRef = function (scale, result) {
  2906. result.x = this.x * scale;
  2907. result.y = this.y * scale;
  2908. result.z = this.z * scale;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2913. * @param otherVector defines the second operand
  2914. * @returns true if both vectors are equals
  2915. */
  2916. Vector3.prototype.equals = function (otherVector) {
  2917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2918. };
  2919. /**
  2920. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2921. * @param otherVector defines the second operand
  2922. * @param epsilon defines the minimal distance to define values as equals
  2923. * @returns true if both vectors are distant less than epsilon
  2924. */
  2925. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2928. };
  2929. /**
  2930. * Returns true if the current Vector3 coordinates equals the passed floats
  2931. * @param x defines the x coordinate of the operand
  2932. * @param y defines the y coordinate of the operand
  2933. * @param z defines the z coordinate of the operand
  2934. * @returns true if both vectors are equals
  2935. */
  2936. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2937. return this.x === x && this.y === y && this.z === z;
  2938. };
  2939. /**
  2940. * Multiplies the current Vector3 coordinates by the passed ones
  2941. * @param otherVector defines the second operand
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2945. this.x *= otherVector.x;
  2946. this.y *= otherVector.y;
  2947. this.z *= otherVector.z;
  2948. return this;
  2949. };
  2950. /**
  2951. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2952. * @param otherVector defines the second operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiply = function (otherVector) {
  2956. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2957. };
  2958. /**
  2959. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2960. * @param otherVector defines the second operand
  2961. * @param result defines the Vector3 object where to store the result
  2962. * @returns the current Vector3
  2963. */
  2964. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2965. result.x = this.x * otherVector.x;
  2966. result.y = this.y * otherVector.y;
  2967. result.z = this.z * otherVector.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the new Vector3
  2976. */
  2977. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2978. return new Vector3(this.x * x, this.y * y, this.z * z);
  2979. };
  2980. /**
  2981. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the new Vector3
  2984. */
  2985. Vector3.prototype.divide = function (otherVector) {
  2986. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2987. };
  2988. /**
  2989. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2990. * @param otherVector defines the second operand
  2991. * @param result defines the Vector3 object where to store the result
  2992. * @returns the current Vector3
  2993. */
  2994. Vector3.prototype.divideToRef = function (otherVector, result) {
  2995. result.x = this.x / otherVector.x;
  2996. result.y = this.y / otherVector.y;
  2997. result.z = this.z / otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Divides the current Vector3 coordinates by the passed ones.
  3002. * @param otherVector defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.divideInPlace = function (otherVector) {
  3006. return this.divideToRef(otherVector, this);
  3007. };
  3008. /**
  3009. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3010. * @param other defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.minimizeInPlace = function (other) {
  3014. if (other.x < this.x)
  3015. this.x = other.x;
  3016. if (other.y < this.y)
  3017. this.y = other.y;
  3018. if (other.z < this.z)
  3019. this.z = other.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3024. * @param other defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.maximizeInPlace = function (other) {
  3028. if (other.x > this.x)
  3029. this.x = other.x;
  3030. if (other.y > this.y)
  3031. this.y = other.y;
  3032. if (other.z > this.z)
  3033. this.z = other.z;
  3034. return this;
  3035. };
  3036. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3037. /**
  3038. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3039. */
  3040. get: function () {
  3041. var absX = Math.abs(this.x);
  3042. var absY = Math.abs(this.y);
  3043. if (absX !== absY) {
  3044. return true;
  3045. }
  3046. var absZ = Math.abs(this.z);
  3047. if (absX !== absZ) {
  3048. return true;
  3049. }
  3050. if (absY !== absZ) {
  3051. return true;
  3052. }
  3053. return false;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. // Properties
  3059. /**
  3060. * Gets the length of the Vector3
  3061. * @returns the length of the Vecto3
  3062. */
  3063. Vector3.prototype.length = function () {
  3064. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3065. };
  3066. /**
  3067. * Gets the squared length of the Vector3
  3068. * @returns squared length of the Vector3
  3069. */
  3070. Vector3.prototype.lengthSquared = function () {
  3071. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3072. };
  3073. /**
  3074. * Normalize the current Vector3.
  3075. * Please note that this is an in place operation.
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.normalize = function () {
  3079. var len = this.length();
  3080. if (len === 0 || len === 1.0)
  3081. return this;
  3082. var num = 1.0 / len;
  3083. this.x *= num;
  3084. this.y *= num;
  3085. this.z *= num;
  3086. return this;
  3087. };
  3088. /**
  3089. * Normalize the current Vector3 to a new vector
  3090. * @returns the new Vector3
  3091. */
  3092. Vector3.prototype.normalizeToNew = function () {
  3093. var normalized = new Vector3(0, 0, 0);
  3094. this.normalizeToRef(normalized);
  3095. return normalized;
  3096. };
  3097. /**
  3098. * Normalize the current Vector3 to the reference
  3099. * @param reference define the Vector3 to update
  3100. * @returns the updated Vector3
  3101. */
  3102. Vector3.prototype.normalizeToRef = function (reference) {
  3103. var len = this.length();
  3104. if (len === 0 || len === 1.0) {
  3105. reference.set(this.x, this.y, this.z);
  3106. return reference;
  3107. }
  3108. var scale = 1.0 / len;
  3109. this.scaleToRef(scale, reference);
  3110. return reference;
  3111. };
  3112. /**
  3113. * Creates a new Vector3 copied from the current Vector3
  3114. * @returns the new Vector3
  3115. */
  3116. Vector3.prototype.clone = function () {
  3117. return new Vector3(this.x, this.y, this.z);
  3118. };
  3119. /**
  3120. * Copies the passed vector coordinates to the current Vector3 ones
  3121. * @param source defines the source Vector3
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.copyFrom = function (source) {
  3125. this.x = source.x;
  3126. this.y = source.y;
  3127. this.z = source.z;
  3128. return this;
  3129. };
  3130. /**
  3131. * Copies the passed floats to the current Vector3 coordinates
  3132. * @param x defines the x coordinate of the operand
  3133. * @param y defines the y coordinate of the operand
  3134. * @param z defines the z coordinate of the operand
  3135. * @returns the current updated Vector3
  3136. */
  3137. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3138. this.x = x;
  3139. this.y = y;
  3140. this.z = z;
  3141. return this;
  3142. };
  3143. /**
  3144. * Copies the passed floats to the current Vector3 coordinates
  3145. * @param x defines the x coordinate of the operand
  3146. * @param y defines the y coordinate of the operand
  3147. * @param z defines the z coordinate of the operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.set = function (x, y, z) {
  3151. return this.copyFromFloats(x, y, z);
  3152. };
  3153. // Statics
  3154. /**
  3155. * Get the clip factor between two vectors
  3156. * @param vector0 defines the first operand
  3157. * @param vector1 defines the second operand
  3158. * @param axis defines the axis to use
  3159. * @param size defines the size along the axis
  3160. * @returns the clip factor
  3161. */
  3162. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3163. var d0 = Vector3.Dot(vector0, axis) - size;
  3164. var d1 = Vector3.Dot(vector1, axis) - size;
  3165. var s = d0 / (d0 - d1);
  3166. return s;
  3167. };
  3168. /**
  3169. * Get angle between two vectors
  3170. * @param vector0 angle between vector0 and vector1
  3171. * @param vector1 angle between vector0 and vector1
  3172. * @param normal direction of the normal
  3173. * @return the angle between vector0 and vector1
  3174. */
  3175. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3176. var v0 = vector0.clone().normalize();
  3177. var v1 = vector1.clone().normalize();
  3178. var dot = Vector3.Dot(v0, v1);
  3179. var n = Vector3.Cross(v0, v1);
  3180. if (Vector3.Dot(n, normal) > 0) {
  3181. return Math.acos(dot);
  3182. }
  3183. return -Math.acos(dot);
  3184. };
  3185. /**
  3186. * Returns a new Vector3 set from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @returns the new Vector3
  3190. */
  3191. Vector3.FromArray = function (array, offset) {
  3192. if (!offset) {
  3193. offset = 0;
  3194. }
  3195. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3199. * This function is deprecated. Use FromArray instead
  3200. * @param array defines the source array
  3201. * @param offset defines the offset in the source array
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.FromFloatArray = function (array, offset) {
  3205. return Vector3.FromArray(array, offset);
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3209. * @param array defines the source array
  3210. * @param offset defines the offset in the source array
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromArrayToRef = function (array, offset, result) {
  3214. result.x = array[offset];
  3215. result.y = array[offset + 1];
  3216. result.z = array[offset + 2];
  3217. };
  3218. /**
  3219. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3220. * This function is deprecated. Use FromArrayToRef instead.
  3221. * @param array defines the source array
  3222. * @param offset defines the offset in the source array
  3223. * @param result defines the Vector3 where to store the result
  3224. */
  3225. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3226. return Vector3.FromArrayToRef(array, offset, result);
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" with the passed floats.
  3230. * @param x defines the x coordinate of the source
  3231. * @param y defines the y coordinate of the source
  3232. * @param z defines the z coordinate of the source
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3236. result.x = x;
  3237. result.y = y;
  3238. result.z = z;
  3239. };
  3240. /**
  3241. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3242. * @returns a new empty Vector3
  3243. */
  3244. Vector3.Zero = function () {
  3245. return new Vector3(0.0, 0.0, 0.0);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3249. * @returns a new unit Vector3
  3250. */
  3251. Vector3.One = function () {
  3252. return new Vector3(1.0, 1.0, 1.0);
  3253. };
  3254. /**
  3255. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3256. * @returns a new up Vector3
  3257. */
  3258. Vector3.Up = function () {
  3259. return new Vector3(0.0, 1.0, 0.0);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3263. * @returns a new forward Vector3
  3264. */
  3265. Vector3.Forward = function () {
  3266. return new Vector3(0.0, 0.0, 1.0);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3270. * @returns a new right Vector3
  3271. */
  3272. Vector3.Right = function () {
  3273. return new Vector3(1.0, 0.0, 0.0);
  3274. };
  3275. /**
  3276. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3277. * @returns a new left Vector3
  3278. */
  3279. Vector3.Left = function () {
  3280. return new Vector3(-1.0, 0.0, 0.0);
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3284. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3285. * @param vector defines the Vector3 to transform
  3286. * @param transformation defines the transformation matrix
  3287. * @returns the transformed Vector3
  3288. */
  3289. Vector3.TransformCoordinates = function (vector, transformation) {
  3290. var result = Vector3.Zero();
  3291. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3296. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3297. * @param vector defines the Vector3 to transform
  3298. * @param transformation defines the transformation matrix
  3299. * @param result defines the Vector3 where to store the result
  3300. */
  3301. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3302. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3303. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3304. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3305. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3306. result.x = x / w;
  3307. result.y = y / w;
  3308. result.z = z / w;
  3309. };
  3310. /**
  3311. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3312. * This method computes tranformed coordinates only, not transformed direction vectors
  3313. * @param x define the x coordinate of the source vector
  3314. * @param y define the y coordinate of the source vector
  3315. * @param z define the z coordinate of the source vector
  3316. * @param transformation defines the transformation matrix
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3320. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3321. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3322. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3323. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3324. result.x = rx / rw;
  3325. result.y = ry / rw;
  3326. result.z = rz / rw;
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3330. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3331. * @param vector defines the Vector3 to transform
  3332. * @param transformation defines the transformation matrix
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.TransformNormal = function (vector, transformation) {
  3336. var result = Vector3.Zero();
  3337. Vector3.TransformNormalToRef(vector, transformation, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3342. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3343. * @param vector defines the Vector3 to transform
  3344. * @param transformation defines the transformation matrix
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3348. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3349. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3350. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3351. result.x = x;
  3352. result.y = y;
  3353. result.z = z;
  3354. };
  3355. /**
  3356. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3357. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3366. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3367. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3371. * @param value1 defines the first control point
  3372. * @param value2 defines the second control point
  3373. * @param value3 defines the third control point
  3374. * @param value4 defines the fourth control point
  3375. * @param amount defines the amount on the spline to use
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3382. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3383. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3384. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3385. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3386. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3387. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3388. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3389. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3390. return new Vector3(x, y, z);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3394. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3395. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3396. * @param value defines the current value
  3397. * @param min defines the lower range value
  3398. * @param max defines the upper range value
  3399. * @returns the new Vector3
  3400. */
  3401. Vector3.Clamp = function (value, min, max) {
  3402. var x = value.x;
  3403. x = (x > max.x) ? max.x : x;
  3404. x = (x < min.x) ? min.x : x;
  3405. var y = value.y;
  3406. y = (y > max.y) ? max.y : y;
  3407. y = (y < min.y) ? min.y : y;
  3408. var z = value.z;
  3409. z = (z > max.z) ? max.z : z;
  3410. z = (z < min.z) ? min.z : z;
  3411. return new Vector3(x, y, z);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3415. * @param value1 defines the first control point
  3416. * @param tangent1 defines the first tangent vector
  3417. * @param value2 defines the second control point
  3418. * @param tangent2 defines the second tangent vector
  3419. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3423. var squared = amount * amount;
  3424. var cubed = amount * squared;
  3425. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3426. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3427. var part3 = (cubed - (2.0 * squared)) + amount;
  3428. var part4 = cubed - squared;
  3429. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3430. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3431. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3436. * @param start defines the start value
  3437. * @param end defines the end value
  3438. * @param amount max defines amount between both (between 0 and 1)
  3439. * @returns the new Vector3
  3440. */
  3441. Vector3.Lerp = function (start, end, amount) {
  3442. var result = new Vector3(0, 0, 0);
  3443. Vector3.LerpToRef(start, end, amount, result);
  3444. return result;
  3445. };
  3446. /**
  3447. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3448. * @param start defines the start value
  3449. * @param end defines the end value
  3450. * @param amount max defines amount between both (between 0 and 1)
  3451. * @param result defines the Vector3 where to store the result
  3452. */
  3453. Vector3.LerpToRef = function (start, end, amount, result) {
  3454. result.x = start.x + ((end.x - start.x) * amount);
  3455. result.y = start.y + ((end.y - start.y) * amount);
  3456. result.z = start.z + ((end.z - start.z) * amount);
  3457. };
  3458. /**
  3459. * Returns the dot product (float) between the vectors "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @returns the dot product
  3463. */
  3464. Vector3.Dot = function (left, right) {
  3465. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3466. };
  3467. /**
  3468. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3469. * The cross product is then orthogonal to both "left" and "right"
  3470. * @param left defines the left operand
  3471. * @param right defines the right operand
  3472. * @returns the cross product
  3473. */
  3474. Vector3.Cross = function (left, right) {
  3475. var result = Vector3.Zero();
  3476. Vector3.CrossToRef(left, right, result);
  3477. return result;
  3478. };
  3479. /**
  3480. * Sets the passed vector "result" with the cross product of "left" and "right"
  3481. * The cross product is then orthogonal to both "left" and "right"
  3482. * @param left defines the left operand
  3483. * @param right defines the right operand
  3484. * @param result defines the Vector3 where to store the result
  3485. */
  3486. Vector3.CrossToRef = function (left, right, result) {
  3487. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3488. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3489. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3490. result.copyFrom(MathTmp.Vector3[0]);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 as the normalization of the passed vector
  3494. * @param vector defines the Vector3 to normalize
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Normalize = function (vector) {
  3498. var result = Vector3.Zero();
  3499. Vector3.NormalizeToRef(vector, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Sets the passed vector "result" with the normalization of the passed first vector
  3504. * @param vector defines the Vector3 to normalize
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.NormalizeToRef = function (vector, result) {
  3508. result.copyFrom(vector);
  3509. result.normalize();
  3510. };
  3511. /**
  3512. * Project a Vector3 onto screen space
  3513. * @param vector defines the Vector3 to project
  3514. * @param world defines the world matrix to use
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @param viewport defines the screen viewport to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Project = function (vector, world, transform, viewport) {
  3520. var cw = viewport.width;
  3521. var ch = viewport.height;
  3522. var cx = viewport.x;
  3523. var cy = viewport.y;
  3524. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3525. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3526. var matrix = MathTmp.Matrix[0];
  3527. world.multiplyToRef(transform, matrix);
  3528. matrix.multiplyToRef(viewportMatrix, matrix);
  3529. return Vector3.TransformCoordinates(vector, matrix);
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param transform defines the transform (view x projection) matrix to use
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3541. var matrix = MathTmp.Matrix[0];
  3542. world.multiplyToRef(transform, matrix);
  3543. matrix.invert();
  3544. source.x = source.x / viewportWidth * 2 - 1;
  3545. source.y = -(source.y / viewportHeight * 2 - 1);
  3546. var vector = Vector3.TransformCoordinates(source, matrix);
  3547. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3548. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3549. vector = vector.scale(1.0 / num);
  3550. }
  3551. return vector;
  3552. };
  3553. /**
  3554. * Unproject from screen space to object space
  3555. * @param source defines the screen space Vector3 to use
  3556. * @param viewportWidth defines the current width of the viewport
  3557. * @param viewportHeight defines the current height of the viewport
  3558. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3559. * @param view defines the view matrix to use
  3560. * @param projection defines the projection matrix to use
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3564. var result = Vector3.Zero();
  3565. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Unproject from screen space to object space
  3570. * @param source defines the screen space Vector3 to use
  3571. * @param viewportWidth defines the current width of the viewport
  3572. * @param viewportHeight defines the current height of the viewport
  3573. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3574. * @param view defines the view matrix to use
  3575. * @param projection defines the projection matrix to use
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3579. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3580. };
  3581. /**
  3582. * Unproject from screen space to object space
  3583. * @param sourceX defines the screen space x coordinate to use
  3584. * @param sourceY defines the screen space y coordinate to use
  3585. * @param sourceZ defines the screen space z coordinate to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param view defines the view matrix to use
  3590. * @param projection defines the projection matrix to use
  3591. * @param result defines the Vector3 where to store the result
  3592. */
  3593. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(view, matrix);
  3596. matrix.multiplyToRef(projection, matrix);
  3597. matrix.invert();
  3598. var screenSource = MathTmp.Vector3[0];
  3599. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3600. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3601. screenSource.z = 2 * sourceZ - 1.0;
  3602. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3603. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3604. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3605. result.scaleInPlace(1.0 / num);
  3606. }
  3607. };
  3608. /**
  3609. * Gets the minimal coordinate values between two Vector3
  3610. * @param left defines the first operand
  3611. * @param right defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Minimize = function (left, right) {
  3615. var min = left.clone();
  3616. min.minimizeInPlace(right);
  3617. return min;
  3618. };
  3619. /**
  3620. * Gets the maximal coordinate values between two Vector3
  3621. * @param left defines the first operand
  3622. * @param right defines the second operand
  3623. * @returns the new Vector3
  3624. */
  3625. Vector3.Maximize = function (left, right) {
  3626. var max = left.clone();
  3627. max.maximizeInPlace(right);
  3628. return max;
  3629. };
  3630. /**
  3631. * Returns the distance between the vectors "value1" and "value2"
  3632. * @param value1 defines the first operand
  3633. * @param value2 defines the second operand
  3634. * @returns the distance
  3635. */
  3636. Vector3.Distance = function (value1, value2) {
  3637. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3638. };
  3639. /**
  3640. * Returns the squared distance between the vectors "value1" and "value2"
  3641. * @param value1 defines the first operand
  3642. * @param value2 defines the second operand
  3643. * @returns the squared distance
  3644. */
  3645. Vector3.DistanceSquared = function (value1, value2) {
  3646. var x = value1.x - value2.x;
  3647. var y = value1.y - value2.y;
  3648. var z = value1.z - value2.z;
  3649. return (x * x) + (y * y) + (z * z);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 located at the center between "value1" and "value2"
  3653. * @param value1 defines the first operand
  3654. * @param value2 defines the second operand
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Center = function (value1, value2) {
  3658. var center = value1.add(value2);
  3659. center.scaleInPlace(0.5);
  3660. return center;
  3661. };
  3662. /**
  3663. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3664. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3665. * to something in order to rotate it from its local system to the given target system
  3666. * Note: axis1, axis2 and axis3 are normalized during this operation
  3667. * @param axis1 defines the first axis
  3668. * @param axis2 defines the second axis
  3669. * @param axis3 defines the third axis
  3670. * @returns a new Vector3
  3671. */
  3672. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3673. var rotation = Vector3.Zero();
  3674. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3675. return rotation;
  3676. };
  3677. /**
  3678. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3679. * @param axis1 defines the first axis
  3680. * @param axis2 defines the second axis
  3681. * @param axis3 defines the third axis
  3682. * @param ref defines the Vector3 where to store the result
  3683. */
  3684. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3685. var quat = MathTmp.Quaternion[0];
  3686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3687. quat.toEulerAnglesToRef(ref);
  3688. };
  3689. return Vector3;
  3690. }());
  3691. BABYLON.Vector3 = Vector3;
  3692. //Vector4 class created for EulerAngle class conversion to Quaternion
  3693. var Vector4 = /** @class */ (function () {
  3694. /**
  3695. * Creates a Vector4 object from the passed floats.
  3696. */
  3697. function Vector4(x, y, z, w) {
  3698. this.x = x;
  3699. this.y = y;
  3700. this.z = z;
  3701. this.w = w;
  3702. }
  3703. /**
  3704. * Returns the string with the Vector4 coordinates.
  3705. */
  3706. Vector4.prototype.toString = function () {
  3707. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3708. };
  3709. /**
  3710. * Returns the string "Vector4".
  3711. */
  3712. Vector4.prototype.getClassName = function () {
  3713. return "Vector4";
  3714. };
  3715. /**
  3716. * Returns the Vector4 hash code.
  3717. */
  3718. Vector4.prototype.getHashCode = function () {
  3719. var hash = this.x || 0;
  3720. hash = (hash * 397) ^ (this.y || 0);
  3721. hash = (hash * 397) ^ (this.z || 0);
  3722. hash = (hash * 397) ^ (this.w || 0);
  3723. return hash;
  3724. };
  3725. // Operators
  3726. /**
  3727. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.asArray = function () {
  3730. var result = new Array();
  3731. this.toArray(result, 0);
  3732. return result;
  3733. };
  3734. /**
  3735. * Populates the passed array from the passed index with the Vector4 coordinates.
  3736. * Returns the Vector4.
  3737. */
  3738. Vector4.prototype.toArray = function (array, index) {
  3739. if (index === undefined) {
  3740. index = 0;
  3741. }
  3742. array[index] = this.x;
  3743. array[index + 1] = this.y;
  3744. array[index + 2] = this.z;
  3745. array[index + 3] = this.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Adds the passed vector to the current Vector4.
  3750. * Returns the updated Vector4.
  3751. */
  3752. Vector4.prototype.addInPlace = function (otherVector) {
  3753. this.x += otherVector.x;
  3754. this.y += otherVector.y;
  3755. this.z += otherVector.z;
  3756. this.w += otherVector.w;
  3757. return this;
  3758. };
  3759. /**
  3760. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3761. */
  3762. Vector4.prototype.add = function (otherVector) {
  3763. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3764. };
  3765. /**
  3766. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3767. * Returns the current Vector4.
  3768. */
  3769. Vector4.prototype.addToRef = function (otherVector, result) {
  3770. result.x = this.x + otherVector.x;
  3771. result.y = this.y + otherVector.y;
  3772. result.z = this.z + otherVector.z;
  3773. result.w = this.w + otherVector.w;
  3774. return this;
  3775. };
  3776. /**
  3777. * Subtract in place the passed vector from the current Vector4.
  3778. * Returns the updated Vector4.
  3779. */
  3780. Vector4.prototype.subtractInPlace = function (otherVector) {
  3781. this.x -= otherVector.x;
  3782. this.y -= otherVector.y;
  3783. this.z -= otherVector.z;
  3784. this.w -= otherVector.w;
  3785. return this;
  3786. };
  3787. /**
  3788. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3789. */
  3790. Vector4.prototype.subtract = function (otherVector) {
  3791. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3792. };
  3793. /**
  3794. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3795. * Returns the current Vector4.
  3796. */
  3797. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3798. result.x = this.x - otherVector.x;
  3799. result.y = this.y - otherVector.y;
  3800. result.z = this.z - otherVector.z;
  3801. result.w = this.w - otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3806. */
  3807. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3808. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3809. };
  3810. /**
  3811. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3815. result.x = this.x - x;
  3816. result.y = this.y - y;
  3817. result.z = this.z - z;
  3818. result.w = this.w - w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3823. */
  3824. Vector4.prototype.negate = function () {
  3825. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3826. };
  3827. /**
  3828. * Multiplies the current Vector4 coordinates by scale (float).
  3829. * Returns the updated Vector4.
  3830. */
  3831. Vector4.prototype.scaleInPlace = function (scale) {
  3832. this.x *= scale;
  3833. this.y *= scale;
  3834. this.z *= scale;
  3835. this.w *= scale;
  3836. return this;
  3837. };
  3838. /**
  3839. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3840. */
  3841. Vector4.prototype.scale = function (scale) {
  3842. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3843. };
  3844. /**
  3845. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3846. * Returns the current Vector4.
  3847. */
  3848. Vector4.prototype.scaleToRef = function (scale, result) {
  3849. result.x = this.x * scale;
  3850. result.y = this.y * scale;
  3851. result.z = this.z * scale;
  3852. result.w = this.w * scale;
  3853. return this;
  3854. };
  3855. /**
  3856. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3857. */
  3858. Vector4.prototype.equals = function (otherVector) {
  3859. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3860. };
  3861. /**
  3862. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3863. */
  3864. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3865. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3866. return otherVector
  3867. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3868. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3869. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3870. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3871. };
  3872. /**
  3873. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3876. return this.x === x && this.y === y && this.z === z && this.w === w;
  3877. };
  3878. /**
  3879. * Multiplies in place the current Vector4 by the passed one.
  3880. * Returns the updated Vector4.
  3881. */
  3882. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3883. this.x *= otherVector.x;
  3884. this.y *= otherVector.y;
  3885. this.z *= otherVector.z;
  3886. this.w *= otherVector.w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3891. */
  3892. Vector4.prototype.multiply = function (otherVector) {
  3893. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3894. };
  3895. /**
  3896. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3897. * Returns the current Vector4.
  3898. */
  3899. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3900. result.x = this.x * otherVector.x;
  3901. result.y = this.y * otherVector.y;
  3902. result.z = this.z * otherVector.z;
  3903. result.w = this.w * otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3908. */
  3909. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3910. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3914. */
  3915. Vector4.prototype.divide = function (otherVector) {
  3916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3920. * Returns the current Vector4.
  3921. */
  3922. Vector4.prototype.divideToRef = function (otherVector, result) {
  3923. result.x = this.x / otherVector.x;
  3924. result.y = this.y / otherVector.y;
  3925. result.z = this.z / otherVector.z;
  3926. result.w = this.w / otherVector.w;
  3927. return this;
  3928. };
  3929. /**
  3930. * Divides the current Vector3 coordinates by the passed ones.
  3931. * @returns the updated Vector3.
  3932. */
  3933. Vector4.prototype.divideInPlace = function (otherVector) {
  3934. return this.divideToRef(otherVector, this);
  3935. };
  3936. /**
  3937. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3938. * @param other defines the second operand
  3939. * @returns the current updated Vector4
  3940. */
  3941. Vector4.prototype.minimizeInPlace = function (other) {
  3942. if (other.x < this.x)
  3943. this.x = other.x;
  3944. if (other.y < this.y)
  3945. this.y = other.y;
  3946. if (other.z < this.z)
  3947. this.z = other.z;
  3948. if (other.w < this.w)
  3949. this.w = other.w;
  3950. return this;
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.maximizeInPlace = function (other) {
  3958. if (other.x > this.x)
  3959. this.x = other.x;
  3960. if (other.y > this.y)
  3961. this.y = other.y;
  3962. if (other.z > this.z)
  3963. this.z = other.z;
  3964. if (other.w > this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. // Properties
  3969. /**
  3970. * Returns the Vector4 length (float).
  3971. */
  3972. Vector4.prototype.length = function () {
  3973. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3974. };
  3975. /**
  3976. * Returns the Vector4 squared length (float).
  3977. */
  3978. Vector4.prototype.lengthSquared = function () {
  3979. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3980. };
  3981. // Methods
  3982. /**
  3983. * Normalizes in place the Vector4.
  3984. * Returns the updated Vector4.
  3985. */
  3986. Vector4.prototype.normalize = function () {
  3987. var len = this.length();
  3988. if (len === 0)
  3989. return this;
  3990. var num = 1.0 / len;
  3991. this.x *= num;
  3992. this.y *= num;
  3993. this.z *= num;
  3994. this.w *= num;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3999. */
  4000. Vector4.prototype.toVector3 = function () {
  4001. return new Vector3(this.x, this.y, this.z);
  4002. };
  4003. /**
  4004. * Returns a new Vector4 copied from the current one.
  4005. */
  4006. Vector4.prototype.clone = function () {
  4007. return new Vector4(this.x, this.y, this.z, this.w);
  4008. };
  4009. /**
  4010. * Updates the current Vector4 with the passed one coordinates.
  4011. * Returns the updated Vector4.
  4012. */
  4013. Vector4.prototype.copyFrom = function (source) {
  4014. this.x = source.x;
  4015. this.y = source.y;
  4016. this.z = source.z;
  4017. this.w = source.w;
  4018. return this;
  4019. };
  4020. /**
  4021. * Updates the current Vector4 coordinates with the passed floats.
  4022. * Returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4025. this.x = x;
  4026. this.y = y;
  4027. this.z = z;
  4028. this.w = w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Updates the current Vector4 coordinates with the passed floats.
  4033. * Returns the updated Vector4.
  4034. */
  4035. Vector4.prototype.set = function (x, y, z, w) {
  4036. return this.copyFromFloats(x, y, z, w);
  4037. };
  4038. // Statics
  4039. /**
  4040. * Returns a new Vector4 set from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArray = function (array, offset) {
  4043. if (!offset) {
  4044. offset = 0;
  4045. }
  4046. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed array.
  4050. */
  4051. Vector4.FromArrayToRef = function (array, offset, result) {
  4052. result.x = array[offset];
  4053. result.y = array[offset + 1];
  4054. result.z = array[offset + 2];
  4055. result.w = array[offset + 3];
  4056. };
  4057. /**
  4058. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4059. */
  4060. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4061. Vector4.FromArrayToRef(array, offset, result);
  4062. };
  4063. /**
  4064. * Updates the passed vector "result" coordinates from the passed floats.
  4065. */
  4066. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4067. result.x = x;
  4068. result.y = y;
  4069. result.z = z;
  4070. result.w = w;
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4074. */
  4075. Vector4.Zero = function () {
  4076. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4080. */
  4081. Vector4.One = function () {
  4082. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4083. };
  4084. /**
  4085. * Returns a new normalized Vector4 from the passed one.
  4086. */
  4087. Vector4.Normalize = function (vector) {
  4088. var result = Vector4.Zero();
  4089. Vector4.NormalizeToRef(vector, result);
  4090. return result;
  4091. };
  4092. /**
  4093. * Updates the passed vector "result" from the normalization of the passed one.
  4094. */
  4095. Vector4.NormalizeToRef = function (vector, result) {
  4096. result.copyFrom(vector);
  4097. result.normalize();
  4098. };
  4099. Vector4.Minimize = function (left, right) {
  4100. var min = left.clone();
  4101. min.minimizeInPlace(right);
  4102. return min;
  4103. };
  4104. Vector4.Maximize = function (left, right) {
  4105. var max = left.clone();
  4106. max.maximizeInPlace(right);
  4107. return max;
  4108. };
  4109. /**
  4110. * Returns the distance (float) between the vectors "value1" and "value2".
  4111. */
  4112. Vector4.Distance = function (value1, value2) {
  4113. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4114. };
  4115. /**
  4116. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4117. */
  4118. Vector4.DistanceSquared = function (value1, value2) {
  4119. var x = value1.x - value2.x;
  4120. var y = value1.y - value2.y;
  4121. var z = value1.z - value2.z;
  4122. var w = value1.w - value2.w;
  4123. return (x * x) + (y * y) + (z * z) + (w * w);
  4124. };
  4125. /**
  4126. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Center = function (value1, value2) {
  4129. var center = value1.add(value2);
  4130. center.scaleInPlace(0.5);
  4131. return center;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormal = function (vector, transformation) {
  4138. var result = Vector4.Zero();
  4139. Vector4.TransformNormalToRef(vector, transformation, result);
  4140. return result;
  4141. };
  4142. /**
  4143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4144. * This methods computes transformed normalized direction vectors only.
  4145. */
  4146. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4147. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4148. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4149. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4150. result.x = x;
  4151. result.y = y;
  4152. result.z = z;
  4153. result.w = vector.w;
  4154. };
  4155. /**
  4156. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4157. * This methods computes transformed normalized direction vectors only.
  4158. */
  4159. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4160. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4161. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4162. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4163. result.w = w;
  4164. };
  4165. return Vector4;
  4166. }());
  4167. BABYLON.Vector4 = Vector4;
  4168. var Size = /** @class */ (function () {
  4169. /**
  4170. * Creates a Size object from the passed width and height (floats).
  4171. */
  4172. function Size(width, height) {
  4173. this.width = width;
  4174. this.height = height;
  4175. }
  4176. // Returns a string with the Size width and height.
  4177. Size.prototype.toString = function () {
  4178. return "{W: " + this.width + ", H: " + this.height + "}";
  4179. };
  4180. /**
  4181. * Returns the string "Size"
  4182. */
  4183. Size.prototype.getClassName = function () {
  4184. return "Size";
  4185. };
  4186. /**
  4187. * Returns the Size hash code.
  4188. */
  4189. Size.prototype.getHashCode = function () {
  4190. var hash = this.width || 0;
  4191. hash = (hash * 397) ^ (this.height || 0);
  4192. return hash;
  4193. };
  4194. /**
  4195. * Updates the current size from the passed one.
  4196. * Returns the updated Size.
  4197. */
  4198. Size.prototype.copyFrom = function (src) {
  4199. this.width = src.width;
  4200. this.height = src.height;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.copyFromFloats = function (width, height) {
  4207. this.width = width;
  4208. this.height = height;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates in place the current Size from the passed floats.
  4213. * Returns the updated Size.
  4214. */
  4215. Size.prototype.set = function (width, height) {
  4216. return this.copyFromFloats(width, height);
  4217. };
  4218. /**
  4219. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4220. */
  4221. Size.prototype.multiplyByFloats = function (w, h) {
  4222. return new Size(this.width * w, this.height * h);
  4223. };
  4224. /**
  4225. * Returns a new Size copied from the passed one.
  4226. */
  4227. Size.prototype.clone = function () {
  4228. return new Size(this.width, this.height);
  4229. };
  4230. /**
  4231. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4232. */
  4233. Size.prototype.equals = function (other) {
  4234. if (!other) {
  4235. return false;
  4236. }
  4237. return (this.width === other.width) && (this.height === other.height);
  4238. };
  4239. Object.defineProperty(Size.prototype, "surface", {
  4240. /**
  4241. * Returns the surface of the Size : width * height (float).
  4242. */
  4243. get: function () {
  4244. return this.width * this.height;
  4245. },
  4246. enumerable: true,
  4247. configurable: true
  4248. });
  4249. /**
  4250. * Returns a new Size set to (0.0, 0.0)
  4251. */
  4252. Size.Zero = function () {
  4253. return new Size(0.0, 0.0);
  4254. };
  4255. /**
  4256. * Returns a new Size set as the addition result of the current Size and the passed one.
  4257. */
  4258. Size.prototype.add = function (otherSize) {
  4259. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4260. return r;
  4261. };
  4262. /**
  4263. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4264. */
  4265. Size.prototype.subtract = function (otherSize) {
  4266. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4267. return r;
  4268. };
  4269. /**
  4270. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4271. */
  4272. Size.Lerp = function (start, end, amount) {
  4273. var w = start.width + ((end.width - start.width) * amount);
  4274. var h = start.height + ((end.height - start.height) * amount);
  4275. return new Size(w, h);
  4276. };
  4277. return Size;
  4278. }());
  4279. BABYLON.Size = Size;
  4280. var Quaternion = /** @class */ (function () {
  4281. /**
  4282. * Creates a new Quaternion from the passed floats.
  4283. */
  4284. function Quaternion(x, y, z, w) {
  4285. if (x === void 0) { x = 0.0; }
  4286. if (y === void 0) { y = 0.0; }
  4287. if (z === void 0) { z = 0.0; }
  4288. if (w === void 0) { w = 1.0; }
  4289. this.x = x;
  4290. this.y = y;
  4291. this.z = z;
  4292. this.w = w;
  4293. }
  4294. /**
  4295. * Returns a string with the Quaternion coordinates.
  4296. */
  4297. Quaternion.prototype.toString = function () {
  4298. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4299. };
  4300. /**
  4301. * Returns the string "Quaternion".
  4302. */
  4303. Quaternion.prototype.getClassName = function () {
  4304. return "Quaternion";
  4305. };
  4306. /**
  4307. * Returns the Quaternion hash code.
  4308. */
  4309. Quaternion.prototype.getHashCode = function () {
  4310. var hash = this.x || 0;
  4311. hash = (hash * 397) ^ (this.y || 0);
  4312. hash = (hash * 397) ^ (this.z || 0);
  4313. hash = (hash * 397) ^ (this.w || 0);
  4314. return hash;
  4315. };
  4316. /**
  4317. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4318. */
  4319. Quaternion.prototype.asArray = function () {
  4320. return [this.x, this.y, this.z, this.w];
  4321. };
  4322. /**
  4323. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4324. */
  4325. Quaternion.prototype.equals = function (otherQuaternion) {
  4326. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4327. };
  4328. /**
  4329. * Returns a new Quaternion copied from the current one.
  4330. */
  4331. Quaternion.prototype.clone = function () {
  4332. return new Quaternion(this.x, this.y, this.z, this.w);
  4333. };
  4334. /**
  4335. * Updates the current Quaternion from the passed one coordinates.
  4336. * Returns the updated Quaterion.
  4337. */
  4338. Quaternion.prototype.copyFrom = function (other) {
  4339. this.x = other.x;
  4340. this.y = other.y;
  4341. this.z = other.z;
  4342. this.w = other.w;
  4343. return this;
  4344. };
  4345. /**
  4346. * Updates the current Quaternion from the passed float coordinates.
  4347. * Returns the updated Quaterion.
  4348. */
  4349. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4350. this.x = x;
  4351. this.y = y;
  4352. this.z = z;
  4353. this.w = w;
  4354. return this;
  4355. };
  4356. /**
  4357. * Updates the current Quaternion from the passed float coordinates.
  4358. * Returns the updated Quaterion.
  4359. */
  4360. Quaternion.prototype.set = function (x, y, z, w) {
  4361. return this.copyFromFloats(x, y, z, w);
  4362. };
  4363. /**
  4364. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4365. */
  4366. Quaternion.prototype.add = function (other) {
  4367. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4368. };
  4369. /**
  4370. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4371. */
  4372. Quaternion.prototype.subtract = function (other) {
  4373. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4374. };
  4375. /**
  4376. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4377. */
  4378. Quaternion.prototype.scale = function (value) {
  4379. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4454. */
  4455. Quaternion.prototype.toEulerAngles = function (order) {
  4456. if (order === void 0) { order = "YZX"; }
  4457. var result = Vector3.Zero();
  4458. this.toEulerAnglesToRef(result, order);
  4459. return result;
  4460. };
  4461. /**
  4462. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4463. * Returns the current Quaternion.
  4464. */
  4465. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4466. if (order === void 0) { order = "YZX"; }
  4467. var qz = this.z;
  4468. var qx = this.x;
  4469. var qy = this.y;
  4470. var qw = this.w;
  4471. var sqw = qw * qw;
  4472. var sqz = qz * qz;
  4473. var sqx = qx * qx;
  4474. var sqy = qy * qy;
  4475. var zAxisY = qy * qz - qx * qw;
  4476. var limit = .4999999;
  4477. if (zAxisY < -limit) {
  4478. result.y = 2 * Math.atan2(qy, qw);
  4479. result.x = Math.PI / 2;
  4480. result.z = 0;
  4481. }
  4482. else if (zAxisY > limit) {
  4483. result.y = 2 * Math.atan2(qy, qw);
  4484. result.x = -Math.PI / 2;
  4485. result.z = 0;
  4486. }
  4487. else {
  4488. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4489. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4490. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4491. }
  4492. return this;
  4493. };
  4494. /**
  4495. * Updates the passed rotation matrix with the current Quaternion values.
  4496. * Returns the current Quaternion.
  4497. */
  4498. Quaternion.prototype.toRotationMatrix = function (result) {
  4499. var xx = this.x * this.x;
  4500. var yy = this.y * this.y;
  4501. var zz = this.z * this.z;
  4502. var xy = this.x * this.y;
  4503. var zw = this.z * this.w;
  4504. var zx = this.z * this.x;
  4505. var yw = this.y * this.w;
  4506. var yz = this.y * this.z;
  4507. var xw = this.x * this.w;
  4508. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4509. result.m[1] = 2.0 * (xy + zw);
  4510. result.m[2] = 2.0 * (zx - yw);
  4511. result.m[3] = 0;
  4512. result.m[4] = 2.0 * (xy - zw);
  4513. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4514. result.m[6] = 2.0 * (yz + xw);
  4515. result.m[7] = 0;
  4516. result.m[8] = 2.0 * (zx + yw);
  4517. result.m[9] = 2.0 * (yz - xw);
  4518. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4519. result.m[11] = 0;
  4520. result.m[12] = 0;
  4521. result.m[13] = 0;
  4522. result.m[14] = 0;
  4523. result.m[15] = 1.0;
  4524. result._markAsUpdated();
  4525. return this;
  4526. };
  4527. /**
  4528. * Updates the current Quaternion from the passed rotation matrix values.
  4529. * Returns the updated Quaternion.
  4530. */
  4531. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4532. Quaternion.FromRotationMatrixToRef(matrix, this);
  4533. return this;
  4534. };
  4535. // Statics
  4536. /**
  4537. * Returns a new Quaternion set from the passed rotation matrix values.
  4538. */
  4539. Quaternion.FromRotationMatrix = function (matrix) {
  4540. var result = new Quaternion();
  4541. Quaternion.FromRotationMatrixToRef(matrix, result);
  4542. return result;
  4543. };
  4544. /**
  4545. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4546. */
  4547. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4548. var data = matrix.m;
  4549. var m11 = data[0], m12 = data[4], m13 = data[8];
  4550. var m21 = data[1], m22 = data[5], m23 = data[9];
  4551. var m31 = data[2], m32 = data[6], m33 = data[10];
  4552. var trace = m11 + m22 + m33;
  4553. var s;
  4554. if (trace > 0) {
  4555. s = 0.5 / Math.sqrt(trace + 1.0);
  4556. result.w = 0.25 / s;
  4557. result.x = (m32 - m23) * s;
  4558. result.y = (m13 - m31) * s;
  4559. result.z = (m21 - m12) * s;
  4560. }
  4561. else if (m11 > m22 && m11 > m33) {
  4562. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4563. result.w = (m32 - m23) / s;
  4564. result.x = 0.25 * s;
  4565. result.y = (m12 + m21) / s;
  4566. result.z = (m13 + m31) / s;
  4567. }
  4568. else if (m22 > m33) {
  4569. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4570. result.w = (m13 - m31) / s;
  4571. result.x = (m12 + m21) / s;
  4572. result.y = 0.25 * s;
  4573. result.z = (m23 + m32) / s;
  4574. }
  4575. else {
  4576. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4577. result.w = (m21 - m12) / s;
  4578. result.x = (m13 + m31) / s;
  4579. result.y = (m23 + m32) / s;
  4580. result.z = 0.25 * s;
  4581. }
  4582. };
  4583. /**
  4584. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4585. */
  4586. Quaternion.Zero = function () {
  4587. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4588. };
  4589. /**
  4590. * Returns a new Quaternion as the inverted current Quaternion.
  4591. */
  4592. Quaternion.Inverse = function (q) {
  4593. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4594. };
  4595. /**
  4596. * Returns the identity Quaternion.
  4597. */
  4598. Quaternion.Identity = function () {
  4599. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4600. };
  4601. Quaternion.IsIdentity = function (quaternion) {
  4602. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4603. };
  4604. /**
  4605. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4606. */
  4607. Quaternion.RotationAxis = function (axis, angle) {
  4608. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4609. };
  4610. /**
  4611. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4612. */
  4613. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4614. var sin = Math.sin(angle / 2);
  4615. axis.normalize();
  4616. result.w = Math.cos(angle / 2);
  4617. result.x = axis.x * sin;
  4618. result.y = axis.y * sin;
  4619. result.z = axis.z * sin;
  4620. return result;
  4621. };
  4622. /**
  4623. * Retuns a new Quaternion set from the starting index of the passed array.
  4624. */
  4625. Quaternion.FromArray = function (array, offset) {
  4626. if (!offset) {
  4627. offset = 0;
  4628. }
  4629. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4630. };
  4631. /**
  4632. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4633. */
  4634. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4635. var q = new Quaternion();
  4636. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4637. return q;
  4638. };
  4639. /**
  4640. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4641. */
  4642. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4643. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4644. var halfRoll = roll * 0.5;
  4645. var halfPitch = pitch * 0.5;
  4646. var halfYaw = yaw * 0.5;
  4647. var sinRoll = Math.sin(halfRoll);
  4648. var cosRoll = Math.cos(halfRoll);
  4649. var sinPitch = Math.sin(halfPitch);
  4650. var cosPitch = Math.cos(halfPitch);
  4651. var sinYaw = Math.sin(halfYaw);
  4652. var cosYaw = Math.cos(halfYaw);
  4653. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4654. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4655. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4656. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4657. };
  4658. /**
  4659. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4660. */
  4661. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4662. var result = new Quaternion();
  4663. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4664. return result;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4668. */
  4669. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4670. // Produces a quaternion from Euler angles in the z-x-z orientation
  4671. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4672. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4673. var halfBeta = beta * 0.5;
  4674. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4675. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4676. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4677. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4678. };
  4679. /**
  4680. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4681. * cf to Vector3.RotationFromAxis() documentation.
  4682. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4683. */
  4684. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4685. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4687. return quat;
  4688. };
  4689. /**
  4690. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4691. * cf to Vector3.RotationFromAxis() documentation.
  4692. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4693. */
  4694. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4695. var rotMat = MathTmp.Matrix[0];
  4696. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4697. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4698. };
  4699. Quaternion.Slerp = function (left, right, amount) {
  4700. var result = Quaternion.Identity();
  4701. Quaternion.SlerpToRef(left, right, amount, result);
  4702. return result;
  4703. };
  4704. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4705. var num2;
  4706. var num3;
  4707. var num = amount;
  4708. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4709. var flag = false;
  4710. if (num4 < 0) {
  4711. flag = true;
  4712. num4 = -num4;
  4713. }
  4714. if (num4 > 0.999999) {
  4715. num3 = 1 - num;
  4716. num2 = flag ? -num : num;
  4717. }
  4718. else {
  4719. var num5 = Math.acos(num4);
  4720. var num6 = (1.0 / Math.sin(num5));
  4721. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4722. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4723. }
  4724. result.x = (num3 * left.x) + (num2 * right.x);
  4725. result.y = (num3 * left.y) + (num2 * right.y);
  4726. result.z = (num3 * left.z) + (num2 * right.z);
  4727. result.w = (num3 * left.w) + (num2 * right.w);
  4728. };
  4729. /**
  4730. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4731. */
  4732. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4733. var squared = amount * amount;
  4734. var cubed = amount * squared;
  4735. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4736. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4737. var part3 = (cubed - (2.0 * squared)) + amount;
  4738. var part4 = cubed - squared;
  4739. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4740. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4741. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4742. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4743. return new Quaternion(x, y, z, w);
  4744. };
  4745. return Quaternion;
  4746. }());
  4747. BABYLON.Quaternion = Quaternion;
  4748. var Matrix = /** @class */ (function () {
  4749. function Matrix() {
  4750. this._isIdentity = false;
  4751. this._isIdentityDirty = true;
  4752. this.m = new Float32Array(16);
  4753. this._markAsUpdated();
  4754. }
  4755. Matrix.prototype._markAsUpdated = function () {
  4756. this.updateFlag = Matrix._updateFlagSeed++;
  4757. this._isIdentityDirty = true;
  4758. };
  4759. // Properties
  4760. /**
  4761. * Boolean : True is the matrix is the identity matrix
  4762. */
  4763. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4764. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4765. if (this._isIdentityDirty) {
  4766. this._isIdentityDirty = false;
  4767. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4768. this._isIdentity = false;
  4769. }
  4770. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4771. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4772. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4773. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4774. this._isIdentity = false;
  4775. }
  4776. else {
  4777. this._isIdentity = true;
  4778. }
  4779. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4780. this._isIdentity = false;
  4781. }
  4782. }
  4783. return this._isIdentity;
  4784. };
  4785. /**
  4786. * Returns the matrix determinant (float).
  4787. */
  4788. Matrix.prototype.determinant = function () {
  4789. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4790. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4791. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4792. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4793. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4794. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4795. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4796. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4797. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4798. };
  4799. // Methods
  4800. /**
  4801. * Returns the matrix underlying array.
  4802. */
  4803. Matrix.prototype.toArray = function () {
  4804. return this.m;
  4805. };
  4806. /**
  4807. * Returns the matrix underlying array.
  4808. */
  4809. Matrix.prototype.asArray = function () {
  4810. return this.toArray();
  4811. };
  4812. /**
  4813. * Inverts in place the Matrix.
  4814. * Returns the Matrix inverted.
  4815. */
  4816. Matrix.prototype.invert = function () {
  4817. this.invertToRef(this);
  4818. return this;
  4819. };
  4820. /**
  4821. * Sets all the matrix elements to zero.
  4822. * Returns the Matrix.
  4823. */
  4824. Matrix.prototype.reset = function () {
  4825. for (var index = 0; index < 16; index++) {
  4826. this.m[index] = 0.0;
  4827. }
  4828. this._markAsUpdated();
  4829. return this;
  4830. };
  4831. /**
  4832. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4833. */
  4834. Matrix.prototype.add = function (other) {
  4835. var result = new Matrix();
  4836. this.addToRef(other, result);
  4837. return result;
  4838. };
  4839. /**
  4840. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4841. * Returns the Matrix.
  4842. */
  4843. Matrix.prototype.addToRef = function (other, result) {
  4844. for (var index = 0; index < 16; index++) {
  4845. result.m[index] = this.m[index] + other.m[index];
  4846. }
  4847. result._markAsUpdated();
  4848. return this;
  4849. };
  4850. /**
  4851. * Adds in place the passed matrix to the current Matrix.
  4852. * Returns the updated Matrix.
  4853. */
  4854. Matrix.prototype.addToSelf = function (other) {
  4855. for (var index = 0; index < 16; index++) {
  4856. this.m[index] += other.m[index];
  4857. }
  4858. this._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the passed matrix with the current inverted Matrix.
  4863. * Returns the unmodified current Matrix.
  4864. */
  4865. Matrix.prototype.invertToRef = function (other) {
  4866. var l1 = this.m[0];
  4867. var l2 = this.m[1];
  4868. var l3 = this.m[2];
  4869. var l4 = this.m[3];
  4870. var l5 = this.m[4];
  4871. var l6 = this.m[5];
  4872. var l7 = this.m[6];
  4873. var l8 = this.m[7];
  4874. var l9 = this.m[8];
  4875. var l10 = this.m[9];
  4876. var l11 = this.m[10];
  4877. var l12 = this.m[11];
  4878. var l13 = this.m[12];
  4879. var l14 = this.m[13];
  4880. var l15 = this.m[14];
  4881. var l16 = this.m[15];
  4882. var l17 = (l11 * l16) - (l12 * l15);
  4883. var l18 = (l10 * l16) - (l12 * l14);
  4884. var l19 = (l10 * l15) - (l11 * l14);
  4885. var l20 = (l9 * l16) - (l12 * l13);
  4886. var l21 = (l9 * l15) - (l11 * l13);
  4887. var l22 = (l9 * l14) - (l10 * l13);
  4888. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4889. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4890. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4891. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4892. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4893. var l28 = (l7 * l16) - (l8 * l15);
  4894. var l29 = (l6 * l16) - (l8 * l14);
  4895. var l30 = (l6 * l15) - (l7 * l14);
  4896. var l31 = (l5 * l16) - (l8 * l13);
  4897. var l32 = (l5 * l15) - (l7 * l13);
  4898. var l33 = (l5 * l14) - (l6 * l13);
  4899. var l34 = (l7 * l12) - (l8 * l11);
  4900. var l35 = (l6 * l12) - (l8 * l10);
  4901. var l36 = (l6 * l11) - (l7 * l10);
  4902. var l37 = (l5 * l12) - (l8 * l9);
  4903. var l38 = (l5 * l11) - (l7 * l9);
  4904. var l39 = (l5 * l10) - (l6 * l9);
  4905. other.m[0] = l23 * l27;
  4906. other.m[4] = l24 * l27;
  4907. other.m[8] = l25 * l27;
  4908. other.m[12] = l26 * l27;
  4909. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4910. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4911. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4912. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4913. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4914. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4915. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4916. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4917. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4918. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4919. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4920. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4921. other._markAsUpdated();
  4922. return this;
  4923. };
  4924. /**
  4925. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4926. * Returns the updated Matrix.
  4927. */
  4928. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4929. this.m[12] = x;
  4930. this.m[13] = y;
  4931. this.m[14] = z;
  4932. this._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Inserts the translation vector in the current Matrix.
  4937. * Returns the updated Matrix.
  4938. */
  4939. Matrix.prototype.setTranslation = function (vector3) {
  4940. this.m[12] = vector3.x;
  4941. this.m[13] = vector3.y;
  4942. this.m[14] = vector3.z;
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 as the extracted translation from the Matrix.
  4948. */
  4949. Matrix.prototype.getTranslation = function () {
  4950. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4951. };
  4952. /**
  4953. * Fill a Vector3 with the extracted translation from the Matrix.
  4954. */
  4955. Matrix.prototype.getTranslationToRef = function (result) {
  4956. result.x = this.m[12];
  4957. result.y = this.m[13];
  4958. result.z = this.m[14];
  4959. return this;
  4960. };
  4961. /**
  4962. * Remove rotation and scaling part from the Matrix.
  4963. * Returns the updated Matrix.
  4964. */
  4965. Matrix.prototype.removeRotationAndScaling = function () {
  4966. this.setRowFromFloats(0, 1, 0, 0, 0);
  4967. this.setRowFromFloats(1, 0, 1, 0, 0);
  4968. this.setRowFromFloats(2, 0, 0, 1, 0);
  4969. return this;
  4970. };
  4971. /**
  4972. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4973. */
  4974. Matrix.prototype.multiply = function (other) {
  4975. var result = new Matrix();
  4976. this.multiplyToRef(other, result);
  4977. return result;
  4978. };
  4979. /**
  4980. * Updates the current Matrix from the passed one values.
  4981. * Returns the updated Matrix.
  4982. */
  4983. Matrix.prototype.copyFrom = function (other) {
  4984. for (var index = 0; index < 16; index++) {
  4985. this.m[index] = other.m[index];
  4986. }
  4987. this._markAsUpdated();
  4988. return this;
  4989. };
  4990. /**
  4991. * Populates the passed array from the starting index with the Matrix values.
  4992. * Returns the Matrix.
  4993. */
  4994. Matrix.prototype.copyToArray = function (array, offset) {
  4995. if (offset === void 0) { offset = 0; }
  4996. for (var index = 0; index < 16; index++) {
  4997. array[offset + index] = this.m[index];
  4998. }
  4999. return this;
  5000. };
  5001. /**
  5002. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5003. */
  5004. Matrix.prototype.multiplyToRef = function (other, result) {
  5005. this.multiplyToArray(other, result.m, 0);
  5006. result._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5011. */
  5012. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5013. var tm0 = this.m[0];
  5014. var tm1 = this.m[1];
  5015. var tm2 = this.m[2];
  5016. var tm3 = this.m[3];
  5017. var tm4 = this.m[4];
  5018. var tm5 = this.m[5];
  5019. var tm6 = this.m[6];
  5020. var tm7 = this.m[7];
  5021. var tm8 = this.m[8];
  5022. var tm9 = this.m[9];
  5023. var tm10 = this.m[10];
  5024. var tm11 = this.m[11];
  5025. var tm12 = this.m[12];
  5026. var tm13 = this.m[13];
  5027. var tm14 = this.m[14];
  5028. var tm15 = this.m[15];
  5029. var om0 = other.m[0];
  5030. var om1 = other.m[1];
  5031. var om2 = other.m[2];
  5032. var om3 = other.m[3];
  5033. var om4 = other.m[4];
  5034. var om5 = other.m[5];
  5035. var om6 = other.m[6];
  5036. var om7 = other.m[7];
  5037. var om8 = other.m[8];
  5038. var om9 = other.m[9];
  5039. var om10 = other.m[10];
  5040. var om11 = other.m[11];
  5041. var om12 = other.m[12];
  5042. var om13 = other.m[13];
  5043. var om14 = other.m[14];
  5044. var om15 = other.m[15];
  5045. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5046. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5047. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5048. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5049. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5050. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5051. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5052. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5053. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5054. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5055. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5056. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5057. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5058. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5059. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5060. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5061. return this;
  5062. };
  5063. /**
  5064. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5065. */
  5066. Matrix.prototype.equals = function (value) {
  5067. return value &&
  5068. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5069. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5070. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5071. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5072. };
  5073. /**
  5074. * Returns a new Matrix from the current Matrix.
  5075. */
  5076. Matrix.prototype.clone = function () {
  5077. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5078. };
  5079. /**
  5080. * Returns the string "Matrix"
  5081. */
  5082. Matrix.prototype.getClassName = function () {
  5083. return "Matrix";
  5084. };
  5085. /**
  5086. * Returns the Matrix hash code.
  5087. */
  5088. Matrix.prototype.getHashCode = function () {
  5089. var hash = this.m[0] || 0;
  5090. for (var i = 1; i < 16; i++) {
  5091. hash = (hash * 397) ^ (this.m[i] || 0);
  5092. }
  5093. return hash;
  5094. };
  5095. /**
  5096. * Decomposes the current Matrix into :
  5097. * - a scale vector3 passed as a reference to update,
  5098. * - a rotation quaternion passed as a reference to update,
  5099. * - a translation vector3 passed as a reference to update.
  5100. * Returns the true if operation was successful.
  5101. */
  5102. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5103. translation.x = this.m[12];
  5104. translation.y = this.m[13];
  5105. translation.z = this.m[14];
  5106. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5107. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5108. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5109. if (this.determinant() <= 0) {
  5110. scale.y *= -1;
  5111. }
  5112. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5113. rotation.x = 0;
  5114. rotation.y = 0;
  5115. rotation.z = 0;
  5116. rotation.w = 1;
  5117. return false;
  5118. }
  5119. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5120. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5121. return true;
  5122. };
  5123. /**
  5124. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5125. * @param ref matrix to store the result
  5126. */
  5127. Matrix.prototype.toNormalMatrix = function (ref) {
  5128. this.invertToRef(ref);
  5129. ref.transpose();
  5130. var m = ref.m;
  5131. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5132. };
  5133. /**
  5134. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5135. */
  5136. Matrix.prototype.getRotationMatrix = function () {
  5137. var result = Matrix.Identity();
  5138. this.getRotationMatrixToRef(result);
  5139. return result;
  5140. };
  5141. /**
  5142. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5143. * Returns the current Matrix.
  5144. */
  5145. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5146. var m = this.m;
  5147. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5148. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5149. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5150. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5151. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5152. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5153. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5154. return this;
  5155. };
  5156. // Statics
  5157. /**
  5158. * Returns a new Matrix set from the starting index of the passed array.
  5159. */
  5160. Matrix.FromArray = function (array, offset) {
  5161. var result = new Matrix();
  5162. if (!offset) {
  5163. offset = 0;
  5164. }
  5165. Matrix.FromArrayToRef(array, offset, result);
  5166. return result;
  5167. };
  5168. /**
  5169. * Sets the passed "result" matrix from the starting index of the passed array.
  5170. */
  5171. Matrix.FromArrayToRef = function (array, offset, result) {
  5172. for (var index = 0; index < 16; index++) {
  5173. result.m[index] = array[index + offset];
  5174. }
  5175. result._markAsUpdated();
  5176. };
  5177. /**
  5178. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5179. */
  5180. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5181. for (var index = 0; index < 16; index++) {
  5182. result.m[index] = array[index + offset] * scale;
  5183. }
  5184. result._markAsUpdated();
  5185. };
  5186. /**
  5187. * Sets the passed matrix "result" with the 16 passed floats.
  5188. */
  5189. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5190. result.m[0] = initialM11;
  5191. result.m[1] = initialM12;
  5192. result.m[2] = initialM13;
  5193. result.m[3] = initialM14;
  5194. result.m[4] = initialM21;
  5195. result.m[5] = initialM22;
  5196. result.m[6] = initialM23;
  5197. result.m[7] = initialM24;
  5198. result.m[8] = initialM31;
  5199. result.m[9] = initialM32;
  5200. result.m[10] = initialM33;
  5201. result.m[11] = initialM34;
  5202. result.m[12] = initialM41;
  5203. result.m[13] = initialM42;
  5204. result.m[14] = initialM43;
  5205. result.m[15] = initialM44;
  5206. result._markAsUpdated();
  5207. };
  5208. /**
  5209. * Returns the index-th row of the current matrix as a new Vector4.
  5210. */
  5211. Matrix.prototype.getRow = function (index) {
  5212. if (index < 0 || index > 3) {
  5213. return null;
  5214. }
  5215. var i = index * 4;
  5216. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5217. };
  5218. /**
  5219. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5220. * Returns the updated Matrix.
  5221. */
  5222. Matrix.prototype.setRow = function (index, row) {
  5223. if (index < 0 || index > 3) {
  5224. return this;
  5225. }
  5226. var i = index * 4;
  5227. this.m[i + 0] = row.x;
  5228. this.m[i + 1] = row.y;
  5229. this.m[i + 2] = row.z;
  5230. this.m[i + 3] = row.w;
  5231. this._markAsUpdated();
  5232. return this;
  5233. };
  5234. /**
  5235. * Compute the transpose of the matrix.
  5236. * Returns a new Matrix.
  5237. */
  5238. Matrix.prototype.transpose = function () {
  5239. return Matrix.Transpose(this);
  5240. };
  5241. /**
  5242. * Compute the transpose of the matrix.
  5243. * Returns the current matrix.
  5244. */
  5245. Matrix.prototype.transposeToRef = function (result) {
  5246. Matrix.TransposeToRef(this, result);
  5247. return this;
  5248. };
  5249. /**
  5250. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5251. * Returns the updated Matrix.
  5252. */
  5253. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5254. if (index < 0 || index > 3) {
  5255. return this;
  5256. }
  5257. var i = index * 4;
  5258. this.m[i + 0] = x;
  5259. this.m[i + 1] = y;
  5260. this.m[i + 2] = z;
  5261. this.m[i + 3] = w;
  5262. this._markAsUpdated();
  5263. return this;
  5264. };
  5265. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5266. /**
  5267. * Static identity matrix to be used as readonly matrix
  5268. * Must not be updated.
  5269. */
  5270. get: function () {
  5271. return Matrix._identityReadOnly;
  5272. },
  5273. enumerable: true,
  5274. configurable: true
  5275. });
  5276. /**
  5277. * Returns a new Matrix set from the 16 passed floats.
  5278. */
  5279. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5280. var result = new Matrix();
  5281. result.m[0] = initialM11;
  5282. result.m[1] = initialM12;
  5283. result.m[2] = initialM13;
  5284. result.m[3] = initialM14;
  5285. result.m[4] = initialM21;
  5286. result.m[5] = initialM22;
  5287. result.m[6] = initialM23;
  5288. result.m[7] = initialM24;
  5289. result.m[8] = initialM31;
  5290. result.m[9] = initialM32;
  5291. result.m[10] = initialM33;
  5292. result.m[11] = initialM34;
  5293. result.m[12] = initialM41;
  5294. result.m[13] = initialM42;
  5295. result.m[14] = initialM43;
  5296. result.m[15] = initialM44;
  5297. return result;
  5298. };
  5299. /**
  5300. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5301. */
  5302. Matrix.Compose = function (scale, rotation, translation) {
  5303. var result = Matrix.Identity();
  5304. Matrix.ComposeToRef(scale, rotation, translation, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5309. */
  5310. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5311. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5312. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5313. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5314. result.setTranslation(translation);
  5315. };
  5316. /**
  5317. * Returns a new indentity Matrix.
  5318. */
  5319. Matrix.Identity = function () {
  5320. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5321. };
  5322. /**
  5323. * Sets the passed "result" as an identity matrix.
  5324. */
  5325. Matrix.IdentityToRef = function (result) {
  5326. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5327. };
  5328. /**
  5329. * Returns a new zero Matrix.
  5330. */
  5331. Matrix.Zero = function () {
  5332. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5333. };
  5334. /**
  5335. * Returns a new rotation matrix for "angle" radians around the X axis.
  5336. */
  5337. Matrix.RotationX = function (angle) {
  5338. var result = new Matrix();
  5339. Matrix.RotationXToRef(angle, result);
  5340. return result;
  5341. };
  5342. /**
  5343. * Returns a new Matrix as the passed inverted one.
  5344. */
  5345. Matrix.Invert = function (source) {
  5346. var result = new Matrix();
  5347. source.invertToRef(result);
  5348. return result;
  5349. };
  5350. /**
  5351. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5352. */
  5353. Matrix.RotationXToRef = function (angle, result) {
  5354. var s = Math.sin(angle);
  5355. var c = Math.cos(angle);
  5356. result.m[0] = 1.0;
  5357. result.m[15] = 1.0;
  5358. result.m[5] = c;
  5359. result.m[10] = c;
  5360. result.m[9] = -s;
  5361. result.m[6] = s;
  5362. result.m[1] = 0.0;
  5363. result.m[2] = 0.0;
  5364. result.m[3] = 0.0;
  5365. result.m[4] = 0.0;
  5366. result.m[7] = 0.0;
  5367. result.m[8] = 0.0;
  5368. result.m[11] = 0.0;
  5369. result.m[12] = 0.0;
  5370. result.m[13] = 0.0;
  5371. result.m[14] = 0.0;
  5372. result._markAsUpdated();
  5373. };
  5374. /**
  5375. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5376. */
  5377. Matrix.RotationY = function (angle) {
  5378. var result = new Matrix();
  5379. Matrix.RotationYToRef(angle, result);
  5380. return result;
  5381. };
  5382. /**
  5383. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5384. */
  5385. Matrix.RotationYToRef = function (angle, result) {
  5386. var s = Math.sin(angle);
  5387. var c = Math.cos(angle);
  5388. result.m[5] = 1.0;
  5389. result.m[15] = 1.0;
  5390. result.m[0] = c;
  5391. result.m[2] = -s;
  5392. result.m[8] = s;
  5393. result.m[10] = c;
  5394. result.m[1] = 0.0;
  5395. result.m[3] = 0.0;
  5396. result.m[4] = 0.0;
  5397. result.m[6] = 0.0;
  5398. result.m[7] = 0.0;
  5399. result.m[9] = 0.0;
  5400. result.m[11] = 0.0;
  5401. result.m[12] = 0.0;
  5402. result.m[13] = 0.0;
  5403. result.m[14] = 0.0;
  5404. result._markAsUpdated();
  5405. };
  5406. /**
  5407. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5408. */
  5409. Matrix.RotationZ = function (angle) {
  5410. var result = new Matrix();
  5411. Matrix.RotationZToRef(angle, result);
  5412. return result;
  5413. };
  5414. /**
  5415. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5416. */
  5417. Matrix.RotationZToRef = function (angle, result) {
  5418. var s = Math.sin(angle);
  5419. var c = Math.cos(angle);
  5420. result.m[10] = 1.0;
  5421. result.m[15] = 1.0;
  5422. result.m[0] = c;
  5423. result.m[1] = s;
  5424. result.m[4] = -s;
  5425. result.m[5] = c;
  5426. result.m[2] = 0.0;
  5427. result.m[3] = 0.0;
  5428. result.m[6] = 0.0;
  5429. result.m[7] = 0.0;
  5430. result.m[8] = 0.0;
  5431. result.m[9] = 0.0;
  5432. result.m[11] = 0.0;
  5433. result.m[12] = 0.0;
  5434. result.m[13] = 0.0;
  5435. result.m[14] = 0.0;
  5436. result._markAsUpdated();
  5437. };
  5438. /**
  5439. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5440. */
  5441. Matrix.RotationAxis = function (axis, angle) {
  5442. var result = Matrix.Zero();
  5443. Matrix.RotationAxisToRef(axis, angle, result);
  5444. return result;
  5445. };
  5446. /**
  5447. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5448. */
  5449. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5450. var s = Math.sin(-angle);
  5451. var c = Math.cos(-angle);
  5452. var c1 = 1 - c;
  5453. axis.normalize();
  5454. result.m[0] = (axis.x * axis.x) * c1 + c;
  5455. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5456. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5457. result.m[3] = 0.0;
  5458. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5459. result.m[5] = (axis.y * axis.y) * c1 + c;
  5460. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5461. result.m[7] = 0.0;
  5462. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5463. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5464. result.m[10] = (axis.z * axis.z) * c1 + c;
  5465. result.m[11] = 0.0;
  5466. result.m[15] = 1.0;
  5467. result._markAsUpdated();
  5468. };
  5469. /**
  5470. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5471. */
  5472. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5473. var result = new Matrix();
  5474. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5475. return result;
  5476. };
  5477. /**
  5478. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5479. */
  5480. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5481. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5482. this._tempQuaternion.toRotationMatrix(result);
  5483. };
  5484. /**
  5485. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5486. */
  5487. Matrix.Scaling = function (x, y, z) {
  5488. var result = Matrix.Zero();
  5489. Matrix.ScalingToRef(x, y, z, result);
  5490. return result;
  5491. };
  5492. /**
  5493. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5494. */
  5495. Matrix.ScalingToRef = function (x, y, z, result) {
  5496. result.m[0] = x;
  5497. result.m[1] = 0.0;
  5498. result.m[2] = 0.0;
  5499. result.m[3] = 0.0;
  5500. result.m[4] = 0.0;
  5501. result.m[5] = y;
  5502. result.m[6] = 0.0;
  5503. result.m[7] = 0.0;
  5504. result.m[8] = 0.0;
  5505. result.m[9] = 0.0;
  5506. result.m[10] = z;
  5507. result.m[11] = 0.0;
  5508. result.m[12] = 0.0;
  5509. result.m[13] = 0.0;
  5510. result.m[14] = 0.0;
  5511. result.m[15] = 1.0;
  5512. result._markAsUpdated();
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5516. */
  5517. Matrix.Translation = function (x, y, z) {
  5518. var result = Matrix.Identity();
  5519. Matrix.TranslationToRef(x, y, z, result);
  5520. return result;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5524. */
  5525. Matrix.TranslationToRef = function (x, y, z, result) {
  5526. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5527. };
  5528. /**
  5529. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5530. * @param startValue defines the start value
  5531. * @param endValue defines the end value
  5532. * @param gradient defines the gradient factor
  5533. * @returns the new matrix
  5534. */
  5535. Matrix.Lerp = function (startValue, endValue, gradient) {
  5536. var result = Matrix.Zero();
  5537. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5542. * @param startValue defines the start value
  5543. * @param endValue defines the end value
  5544. * @param gradient defines the gradient factor
  5545. * @param result defines the Matrix object where to store data
  5546. */
  5547. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5548. for (var index = 0; index < 16; index++) {
  5549. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5550. }
  5551. result._markAsUpdated();
  5552. };
  5553. /**
  5554. * Returns a new Matrix whose values are computed by :
  5555. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5556. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5557. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5558. */
  5559. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5560. var startScale = new Vector3(0, 0, 0);
  5561. var startRotation = new Quaternion();
  5562. var startTranslation = new Vector3(0, 0, 0);
  5563. startValue.decompose(startScale, startRotation, startTranslation);
  5564. var endScale = new Vector3(0, 0, 0);
  5565. var endRotation = new Quaternion();
  5566. var endTranslation = new Vector3(0, 0, 0);
  5567. endValue.decompose(endScale, endRotation, endTranslation);
  5568. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5569. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5570. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5571. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5572. };
  5573. /**
  5574. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5575. * This methods works for a Left-Handed system.
  5576. */
  5577. Matrix.LookAtLH = function (eye, target, up) {
  5578. var result = Matrix.Zero();
  5579. Matrix.LookAtLHToRef(eye, target, up, result);
  5580. return result;
  5581. };
  5582. /**
  5583. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5584. * This methods works for a Left-Handed system.
  5585. */
  5586. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5587. // Z axis
  5588. target.subtractToRef(eye, this._zAxis);
  5589. this._zAxis.normalize();
  5590. // X axis
  5591. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5592. if (this._xAxis.lengthSquared() === 0) {
  5593. this._xAxis.x = 1.0;
  5594. }
  5595. else {
  5596. this._xAxis.normalize();
  5597. }
  5598. // Y axis
  5599. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5600. this._yAxis.normalize();
  5601. // Eye angles
  5602. var ex = -Vector3.Dot(this._xAxis, eye);
  5603. var ey = -Vector3.Dot(this._yAxis, eye);
  5604. var ez = -Vector3.Dot(this._zAxis, eye);
  5605. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5606. };
  5607. /**
  5608. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5609. * This methods works for a Right-Handed system.
  5610. */
  5611. Matrix.LookAtRH = function (eye, target, up) {
  5612. var result = Matrix.Zero();
  5613. Matrix.LookAtRHToRef(eye, target, up, result);
  5614. return result;
  5615. };
  5616. /**
  5617. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5618. * This methods works for a Left-Handed system.
  5619. */
  5620. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5621. // Z axis
  5622. eye.subtractToRef(target, this._zAxis);
  5623. this._zAxis.normalize();
  5624. // X axis
  5625. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5626. if (this._xAxis.lengthSquared() === 0) {
  5627. this._xAxis.x = 1.0;
  5628. }
  5629. else {
  5630. this._xAxis.normalize();
  5631. }
  5632. // Y axis
  5633. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5634. this._yAxis.normalize();
  5635. // Eye angles
  5636. var ex = -Vector3.Dot(this._xAxis, eye);
  5637. var ey = -Vector3.Dot(this._yAxis, eye);
  5638. var ez = -Vector3.Dot(this._zAxis, eye);
  5639. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5640. };
  5641. /**
  5642. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5643. */
  5644. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5645. var matrix = Matrix.Zero();
  5646. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5647. return matrix;
  5648. };
  5649. /**
  5650. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5651. */
  5652. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5653. var n = znear;
  5654. var f = zfar;
  5655. var a = 2.0 / width;
  5656. var b = 2.0 / height;
  5657. var c = 2.0 / (f - n);
  5658. var d = -(f + n) / (f - n);
  5659. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5660. };
  5661. /**
  5662. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5663. */
  5664. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5665. var matrix = Matrix.Zero();
  5666. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5667. return matrix;
  5668. };
  5669. /**
  5670. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5671. */
  5672. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5673. var n = znear;
  5674. var f = zfar;
  5675. var a = 2.0 / (right - left);
  5676. var b = 2.0 / (top - bottom);
  5677. var c = 2.0 / (f - n);
  5678. var d = -(f + n) / (f - n);
  5679. var i0 = (left + right) / (left - right);
  5680. var i1 = (top + bottom) / (bottom - top);
  5681. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5682. };
  5683. /**
  5684. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5685. */
  5686. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5687. var matrix = Matrix.Zero();
  5688. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5689. return matrix;
  5690. };
  5691. /**
  5692. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5693. */
  5694. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5695. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5696. result.m[10] *= -1.0;
  5697. };
  5698. /**
  5699. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5700. */
  5701. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5702. var matrix = Matrix.Zero();
  5703. var n = znear;
  5704. var f = zfar;
  5705. var a = 2.0 * n / width;
  5706. var b = 2.0 * n / height;
  5707. var c = (f + n) / (f - n);
  5708. var d = -2.0 * f * n / (f - n);
  5709. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5710. return matrix;
  5711. };
  5712. /**
  5713. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5714. */
  5715. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5716. var matrix = Matrix.Zero();
  5717. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5718. return matrix;
  5719. };
  5720. /**
  5721. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5722. */
  5723. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5724. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5725. var n = znear;
  5726. var f = zfar;
  5727. var t = 1.0 / (Math.tan(fov * 0.5));
  5728. var a = isVerticalFovFixed ? (t / aspect) : t;
  5729. var b = isVerticalFovFixed ? t : (t * aspect);
  5730. var c = (f + n) / (f - n);
  5731. var d = -2.0 * f * n / (f - n);
  5732. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5733. };
  5734. /**
  5735. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5736. */
  5737. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5738. var matrix = Matrix.Zero();
  5739. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5740. return matrix;
  5741. };
  5742. /**
  5743. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5744. */
  5745. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5746. //alternatively this could be expressed as:
  5747. // m = PerspectiveFovLHToRef
  5748. // m[10] *= -1.0;
  5749. // m[11] *= -1.0;
  5750. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5751. var n = znear;
  5752. var f = zfar;
  5753. var t = 1.0 / (Math.tan(fov * 0.5));
  5754. var a = isVerticalFovFixed ? (t / aspect) : t;
  5755. var b = isVerticalFovFixed ? t : (t * aspect);
  5756. var c = -(f + n) / (f - n);
  5757. var d = -2 * f * n / (f - n);
  5758. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5759. };
  5760. /**
  5761. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5762. */
  5763. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5764. if (rightHanded === void 0) { rightHanded = false; }
  5765. var rightHandedFactor = rightHanded ? -1 : 1;
  5766. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5767. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5768. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5769. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5770. var xScale = 2.0 / (leftTan + rightTan);
  5771. var yScale = 2.0 / (upTan + downTan);
  5772. result.m[0] = xScale;
  5773. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5774. result.m[5] = yScale;
  5775. result.m[6] = result.m[7] = 0.0;
  5776. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5777. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5778. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5779. result.m[10] = -zfar / (znear - zfar);
  5780. result.m[11] = 1.0 * rightHandedFactor;
  5781. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5782. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5783. // result.m[14] = (znear * zfar) / (znear - zfar);
  5784. result._markAsUpdated();
  5785. };
  5786. /**
  5787. * Returns the final transformation matrix : world * view * projection * viewport
  5788. */
  5789. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5790. var cw = viewport.width;
  5791. var ch = viewport.height;
  5792. var cx = viewport.x;
  5793. var cy = viewport.y;
  5794. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5795. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5796. };
  5797. /**
  5798. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5799. */
  5800. Matrix.GetAsMatrix2x2 = function (matrix) {
  5801. return new Float32Array([
  5802. matrix.m[0], matrix.m[1],
  5803. matrix.m[4], matrix.m[5]
  5804. ]);
  5805. };
  5806. /**
  5807. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5808. */
  5809. Matrix.GetAsMatrix3x3 = function (matrix) {
  5810. return new Float32Array([
  5811. matrix.m[0], matrix.m[1], matrix.m[2],
  5812. matrix.m[4], matrix.m[5], matrix.m[6],
  5813. matrix.m[8], matrix.m[9], matrix.m[10]
  5814. ]);
  5815. };
  5816. /**
  5817. * Compute the transpose of the passed Matrix.
  5818. * Returns a new Matrix.
  5819. */
  5820. Matrix.Transpose = function (matrix) {
  5821. var result = new Matrix();
  5822. Matrix.TransposeToRef(matrix, result);
  5823. return result;
  5824. };
  5825. /**
  5826. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5827. */
  5828. Matrix.TransposeToRef = function (matrix, result) {
  5829. result.m[0] = matrix.m[0];
  5830. result.m[1] = matrix.m[4];
  5831. result.m[2] = matrix.m[8];
  5832. result.m[3] = matrix.m[12];
  5833. result.m[4] = matrix.m[1];
  5834. result.m[5] = matrix.m[5];
  5835. result.m[6] = matrix.m[9];
  5836. result.m[7] = matrix.m[13];
  5837. result.m[8] = matrix.m[2];
  5838. result.m[9] = matrix.m[6];
  5839. result.m[10] = matrix.m[10];
  5840. result.m[11] = matrix.m[14];
  5841. result.m[12] = matrix.m[3];
  5842. result.m[13] = matrix.m[7];
  5843. result.m[14] = matrix.m[11];
  5844. result.m[15] = matrix.m[15];
  5845. };
  5846. /**
  5847. * Returns a new Matrix as the reflection matrix across the passed plane.
  5848. */
  5849. Matrix.Reflection = function (plane) {
  5850. var matrix = new Matrix();
  5851. Matrix.ReflectionToRef(plane, matrix);
  5852. return matrix;
  5853. };
  5854. /**
  5855. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5856. */
  5857. Matrix.ReflectionToRef = function (plane, result) {
  5858. plane.normalize();
  5859. var x = plane.normal.x;
  5860. var y = plane.normal.y;
  5861. var z = plane.normal.z;
  5862. var temp = -2 * x;
  5863. var temp2 = -2 * y;
  5864. var temp3 = -2 * z;
  5865. result.m[0] = (temp * x) + 1;
  5866. result.m[1] = temp2 * x;
  5867. result.m[2] = temp3 * x;
  5868. result.m[3] = 0.0;
  5869. result.m[4] = temp * y;
  5870. result.m[5] = (temp2 * y) + 1;
  5871. result.m[6] = temp3 * y;
  5872. result.m[7] = 0.0;
  5873. result.m[8] = temp * z;
  5874. result.m[9] = temp2 * z;
  5875. result.m[10] = (temp3 * z) + 1;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = temp * plane.d;
  5878. result.m[13] = temp2 * plane.d;
  5879. result.m[14] = temp3 * plane.d;
  5880. result.m[15] = 1.0;
  5881. result._markAsUpdated();
  5882. };
  5883. /**
  5884. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5885. */
  5886. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5887. result.m[0] = xaxis.x;
  5888. result.m[1] = xaxis.y;
  5889. result.m[2] = xaxis.z;
  5890. result.m[3] = 0.0;
  5891. result.m[4] = yaxis.x;
  5892. result.m[5] = yaxis.y;
  5893. result.m[6] = yaxis.z;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = zaxis.x;
  5896. result.m[9] = zaxis.y;
  5897. result.m[10] = zaxis.z;
  5898. result.m[11] = 0.0;
  5899. result.m[12] = 0.0;
  5900. result.m[13] = 0.0;
  5901. result.m[14] = 0.0;
  5902. result.m[15] = 1.0;
  5903. result._markAsUpdated();
  5904. };
  5905. /**
  5906. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5907. */
  5908. Matrix.FromQuaternionToRef = function (quat, result) {
  5909. var xx = quat.x * quat.x;
  5910. var yy = quat.y * quat.y;
  5911. var zz = quat.z * quat.z;
  5912. var xy = quat.x * quat.y;
  5913. var zw = quat.z * quat.w;
  5914. var zx = quat.z * quat.x;
  5915. var yw = quat.y * quat.w;
  5916. var yz = quat.y * quat.z;
  5917. var xw = quat.x * quat.w;
  5918. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5919. result.m[1] = 2.0 * (xy + zw);
  5920. result.m[2] = 2.0 * (zx - yw);
  5921. result.m[3] = 0.0;
  5922. result.m[4] = 2.0 * (xy - zw);
  5923. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5924. result.m[6] = 2.0 * (yz + xw);
  5925. result.m[7] = 0.0;
  5926. result.m[8] = 2.0 * (zx + yw);
  5927. result.m[9] = 2.0 * (yz - xw);
  5928. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5929. result.m[11] = 0.0;
  5930. result.m[12] = 0.0;
  5931. result.m[13] = 0.0;
  5932. result.m[14] = 0.0;
  5933. result.m[15] = 1.0;
  5934. result._markAsUpdated();
  5935. };
  5936. Matrix._tempQuaternion = new Quaternion();
  5937. Matrix._xAxis = Vector3.Zero();
  5938. Matrix._yAxis = Vector3.Zero();
  5939. Matrix._zAxis = Vector3.Zero();
  5940. Matrix._updateFlagSeed = 0;
  5941. Matrix._identityReadOnly = Matrix.Identity();
  5942. return Matrix;
  5943. }());
  5944. BABYLON.Matrix = Matrix;
  5945. var Plane = /** @class */ (function () {
  5946. /**
  5947. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5948. */
  5949. function Plane(a, b, c, d) {
  5950. this.normal = new Vector3(a, b, c);
  5951. this.d = d;
  5952. }
  5953. /**
  5954. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5955. */
  5956. Plane.prototype.asArray = function () {
  5957. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5958. };
  5959. // Methods
  5960. /**
  5961. * Returns a new plane copied from the current Plane.
  5962. */
  5963. Plane.prototype.clone = function () {
  5964. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5965. };
  5966. /**
  5967. * Returns the string "Plane".
  5968. */
  5969. Plane.prototype.getClassName = function () {
  5970. return "Plane";
  5971. };
  5972. /**
  5973. * Returns the Plane hash code.
  5974. */
  5975. Plane.prototype.getHashCode = function () {
  5976. var hash = this.normal.getHashCode();
  5977. hash = (hash * 397) ^ (this.d || 0);
  5978. return hash;
  5979. };
  5980. /**
  5981. * Normalize the current Plane in place.
  5982. * Returns the updated Plane.
  5983. */
  5984. Plane.prototype.normalize = function () {
  5985. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5986. var magnitude = 0.0;
  5987. if (norm !== 0) {
  5988. magnitude = 1.0 / norm;
  5989. }
  5990. this.normal.x *= magnitude;
  5991. this.normal.y *= magnitude;
  5992. this.normal.z *= magnitude;
  5993. this.d *= magnitude;
  5994. return this;
  5995. };
  5996. /**
  5997. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5998. */
  5999. Plane.prototype.transform = function (transformation) {
  6000. var transposedMatrix = Matrix.Transpose(transformation);
  6001. var x = this.normal.x;
  6002. var y = this.normal.y;
  6003. var z = this.normal.z;
  6004. var d = this.d;
  6005. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6006. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6007. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6008. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6009. return new Plane(normalX, normalY, normalZ, finalD);
  6010. };
  6011. /**
  6012. * Returns the dot product (float) of the point coordinates and the plane normal.
  6013. */
  6014. Plane.prototype.dotCoordinate = function (point) {
  6015. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6016. };
  6017. /**
  6018. * Updates the current Plane from the plane defined by the three passed points.
  6019. * Returns the updated Plane.
  6020. */
  6021. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6022. var x1 = point2.x - point1.x;
  6023. var y1 = point2.y - point1.y;
  6024. var z1 = point2.z - point1.z;
  6025. var x2 = point3.x - point1.x;
  6026. var y2 = point3.y - point1.y;
  6027. var z2 = point3.z - point1.z;
  6028. var yz = (y1 * z2) - (z1 * y2);
  6029. var xz = (z1 * x2) - (x1 * z2);
  6030. var xy = (x1 * y2) - (y1 * x2);
  6031. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6032. var invPyth;
  6033. if (pyth !== 0) {
  6034. invPyth = 1.0 / pyth;
  6035. }
  6036. else {
  6037. invPyth = 0.0;
  6038. }
  6039. this.normal.x = yz * invPyth;
  6040. this.normal.y = xz * invPyth;
  6041. this.normal.z = xy * invPyth;
  6042. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6043. return this;
  6044. };
  6045. /**
  6046. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6047. */
  6048. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6049. var dot = Vector3.Dot(this.normal, direction);
  6050. return (dot <= epsilon);
  6051. };
  6052. /**
  6053. * Returns the signed distance (float) from the passed point to the Plane.
  6054. */
  6055. Plane.prototype.signedDistanceTo = function (point) {
  6056. return Vector3.Dot(point, this.normal) + this.d;
  6057. };
  6058. // Statics
  6059. /**
  6060. * Returns a new Plane from the passed array.
  6061. */
  6062. Plane.FromArray = function (array) {
  6063. return new Plane(array[0], array[1], array[2], array[3]);
  6064. };
  6065. /**
  6066. * Returns a new Plane defined by the three passed points.
  6067. */
  6068. Plane.FromPoints = function (point1, point2, point3) {
  6069. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6070. result.copyFromPoints(point1, point2, point3);
  6071. return result;
  6072. };
  6073. /**
  6074. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6075. * Note : the vector "normal" is updated because normalized.
  6076. */
  6077. Plane.FromPositionAndNormal = function (origin, normal) {
  6078. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6079. normal.normalize();
  6080. result.normal = normal;
  6081. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6082. return result;
  6083. };
  6084. /**
  6085. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6086. */
  6087. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6088. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6089. return Vector3.Dot(point, normal) + d;
  6090. };
  6091. return Plane;
  6092. }());
  6093. BABYLON.Plane = Plane;
  6094. var Viewport = /** @class */ (function () {
  6095. /**
  6096. * Creates a Viewport object located at (x, y) and sized (width, height).
  6097. */
  6098. function Viewport(x, y, width, height) {
  6099. this.x = x;
  6100. this.y = y;
  6101. this.width = width;
  6102. this.height = height;
  6103. }
  6104. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6105. if (renderWidthOrEngine.getRenderWidth) {
  6106. var engine = renderWidthOrEngine;
  6107. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6108. }
  6109. var renderWidth = renderWidthOrEngine;
  6110. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6111. };
  6112. /**
  6113. * Returns a new Viewport copied from the current one.
  6114. */
  6115. Viewport.prototype.clone = function () {
  6116. return new Viewport(this.x, this.y, this.width, this.height);
  6117. };
  6118. return Viewport;
  6119. }());
  6120. BABYLON.Viewport = Viewport;
  6121. var Frustum = /** @class */ (function () {
  6122. function Frustum() {
  6123. }
  6124. /**
  6125. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6126. */
  6127. Frustum.GetPlanes = function (transform) {
  6128. var frustumPlanes = [];
  6129. for (var index = 0; index < 6; index++) {
  6130. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6131. }
  6132. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6133. return frustumPlanes;
  6134. };
  6135. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6136. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6137. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6138. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6139. frustumPlane.d = transform.m[15] + transform.m[14];
  6140. frustumPlane.normalize();
  6141. };
  6142. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6143. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6144. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6145. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6146. frustumPlane.d = transform.m[15] - transform.m[14];
  6147. frustumPlane.normalize();
  6148. };
  6149. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6150. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6151. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6152. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6153. frustumPlane.d = transform.m[15] + transform.m[12];
  6154. frustumPlane.normalize();
  6155. };
  6156. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6157. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6158. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6159. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6160. frustumPlane.d = transform.m[15] - transform.m[12];
  6161. frustumPlane.normalize();
  6162. };
  6163. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6164. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6165. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6166. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6167. frustumPlane.d = transform.m[15] - transform.m[13];
  6168. frustumPlane.normalize();
  6169. };
  6170. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6171. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6172. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6173. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6174. frustumPlane.d = transform.m[15] + transform.m[13];
  6175. frustumPlane.normalize();
  6176. };
  6177. /**
  6178. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6179. */
  6180. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6181. // Near
  6182. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6183. // Far
  6184. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6185. // Left
  6186. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6187. // Right
  6188. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6189. // Top
  6190. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6191. // Bottom
  6192. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6193. };
  6194. return Frustum;
  6195. }());
  6196. BABYLON.Frustum = Frustum;
  6197. var Space;
  6198. (function (Space) {
  6199. Space[Space["LOCAL"] = 0] = "LOCAL";
  6200. Space[Space["WORLD"] = 1] = "WORLD";
  6201. Space[Space["BONE"] = 2] = "BONE";
  6202. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6203. var Axis = /** @class */ (function () {
  6204. function Axis() {
  6205. }
  6206. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6207. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6208. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6209. return Axis;
  6210. }());
  6211. BABYLON.Axis = Axis;
  6212. ;
  6213. var BezierCurve = /** @class */ (function () {
  6214. function BezierCurve() {
  6215. }
  6216. /**
  6217. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6218. */
  6219. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6220. // Extract X (which is equal to time here)
  6221. var f0 = 1 - 3 * x2 + 3 * x1;
  6222. var f1 = 3 * x2 - 6 * x1;
  6223. var f2 = 3 * x1;
  6224. var refinedT = t;
  6225. for (var i = 0; i < 5; i++) {
  6226. var refinedT2 = refinedT * refinedT;
  6227. var refinedT3 = refinedT2 * refinedT;
  6228. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6229. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6230. refinedT -= (x - t) * slope;
  6231. refinedT = Math.min(1, Math.max(0, refinedT));
  6232. }
  6233. // Resolve cubic bezier for the given x
  6234. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6235. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6236. Math.pow(refinedT, 3);
  6237. };
  6238. return BezierCurve;
  6239. }());
  6240. BABYLON.BezierCurve = BezierCurve;
  6241. var Orientation;
  6242. (function (Orientation) {
  6243. Orientation[Orientation["CW"] = 0] = "CW";
  6244. Orientation[Orientation["CCW"] = 1] = "CCW";
  6245. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6246. var Angle = /** @class */ (function () {
  6247. /**
  6248. * Creates an Angle object of "radians" radians (float).
  6249. */
  6250. function Angle(radians) {
  6251. var _this = this;
  6252. /**
  6253. * Returns the Angle value in degrees (float).
  6254. */
  6255. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6256. /**
  6257. * Returns the Angle value in radians (float).
  6258. */
  6259. this.radians = function () { return _this._radians; };
  6260. this._radians = radians;
  6261. if (this._radians < 0.0)
  6262. this._radians += (2.0 * Math.PI);
  6263. }
  6264. /**
  6265. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6266. */
  6267. Angle.BetweenTwoPoints = function (a, b) {
  6268. var delta = b.subtract(a);
  6269. var theta = Math.atan2(delta.y, delta.x);
  6270. return new Angle(theta);
  6271. };
  6272. /**
  6273. * Returns a new Angle object from the passed float in radians.
  6274. */
  6275. Angle.FromRadians = function (radians) {
  6276. return new Angle(radians);
  6277. };
  6278. /**
  6279. * Returns a new Angle object from the passed float in degrees.
  6280. */
  6281. Angle.FromDegrees = function (degrees) {
  6282. return new Angle(degrees * Math.PI / 180.0);
  6283. };
  6284. return Angle;
  6285. }());
  6286. BABYLON.Angle = Angle;
  6287. var Arc2 = /** @class */ (function () {
  6288. /**
  6289. * Creates an Arc object from the three passed points : start, middle and end.
  6290. */
  6291. function Arc2(startPoint, midPoint, endPoint) {
  6292. this.startPoint = startPoint;
  6293. this.midPoint = midPoint;
  6294. this.endPoint = endPoint;
  6295. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6296. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6297. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6298. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6299. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6300. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6301. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6302. var a1 = this.startAngle.degrees();
  6303. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6304. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6305. // angles correction
  6306. if (a2 - a1 > +180.0)
  6307. a2 -= 360.0;
  6308. if (a2 - a1 < -180.0)
  6309. a2 += 360.0;
  6310. if (a3 - a2 > +180.0)
  6311. a3 -= 360.0;
  6312. if (a3 - a2 < -180.0)
  6313. a3 += 360.0;
  6314. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6315. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6316. }
  6317. return Arc2;
  6318. }());
  6319. BABYLON.Arc2 = Arc2;
  6320. var Path2 = /** @class */ (function () {
  6321. /**
  6322. * Creates a Path2 object from the starting 2D coordinates x and y.
  6323. */
  6324. function Path2(x, y) {
  6325. this._points = new Array();
  6326. this._length = 0.0;
  6327. this.closed = false;
  6328. this._points.push(new Vector2(x, y));
  6329. }
  6330. /**
  6331. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6332. * Returns the updated Path2.
  6333. */
  6334. Path2.prototype.addLineTo = function (x, y) {
  6335. if (this.closed) {
  6336. return this;
  6337. }
  6338. var newPoint = new Vector2(x, y);
  6339. var previousPoint = this._points[this._points.length - 1];
  6340. this._points.push(newPoint);
  6341. this._length += newPoint.subtract(previousPoint).length();
  6342. return this;
  6343. };
  6344. /**
  6345. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6346. * Returns the updated Path2.
  6347. */
  6348. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6349. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6350. if (this.closed) {
  6351. return this;
  6352. }
  6353. var startPoint = this._points[this._points.length - 1];
  6354. var midPoint = new Vector2(midX, midY);
  6355. var endPoint = new Vector2(endX, endY);
  6356. var arc = new Arc2(startPoint, midPoint, endPoint);
  6357. var increment = arc.angle.radians() / numberOfSegments;
  6358. if (arc.orientation === Orientation.CW)
  6359. increment *= -1;
  6360. var currentAngle = arc.startAngle.radians() + increment;
  6361. for (var i = 0; i < numberOfSegments; i++) {
  6362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6364. this.addLineTo(x, y);
  6365. currentAngle += increment;
  6366. }
  6367. return this;
  6368. };
  6369. /**
  6370. * Closes the Path2.
  6371. * Returns the Path2.
  6372. */
  6373. Path2.prototype.close = function () {
  6374. this.closed = true;
  6375. return this;
  6376. };
  6377. /**
  6378. * Returns the Path2 total length (float).
  6379. */
  6380. Path2.prototype.length = function () {
  6381. var result = this._length;
  6382. if (!this.closed) {
  6383. var lastPoint = this._points[this._points.length - 1];
  6384. var firstPoint = this._points[0];
  6385. result += (firstPoint.subtract(lastPoint).length());
  6386. }
  6387. return result;
  6388. };
  6389. /**
  6390. * Returns the Path2 internal array of points.
  6391. */
  6392. Path2.prototype.getPoints = function () {
  6393. return this._points;
  6394. };
  6395. /**
  6396. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6397. */
  6398. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6399. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6400. return Vector2.Zero();
  6401. }
  6402. var lengthPosition = normalizedLengthPosition * this.length();
  6403. var previousOffset = 0;
  6404. for (var i = 0; i < this._points.length; i++) {
  6405. var j = (i + 1) % this._points.length;
  6406. var a = this._points[i];
  6407. var b = this._points[j];
  6408. var bToA = b.subtract(a);
  6409. var nextOffset = (bToA.length() + previousOffset);
  6410. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6411. var dir = bToA.normalize();
  6412. var localOffset = lengthPosition - previousOffset;
  6413. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6414. }
  6415. previousOffset = nextOffset;
  6416. }
  6417. return Vector2.Zero();
  6418. };
  6419. /**
  6420. * Returns a new Path2 starting at the coordinates (x, y).
  6421. */
  6422. Path2.StartingAt = function (x, y) {
  6423. return new Path2(x, y);
  6424. };
  6425. return Path2;
  6426. }());
  6427. BABYLON.Path2 = Path2;
  6428. var Path3D = /** @class */ (function () {
  6429. /**
  6430. * new Path3D(path, normal, raw)
  6431. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6432. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6433. * path : an array of Vector3, the curve axis of the Path3D
  6434. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6435. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6436. */
  6437. function Path3D(path, firstNormal, raw) {
  6438. if (firstNormal === void 0) { firstNormal = null; }
  6439. this.path = path;
  6440. this._curve = new Array();
  6441. this._distances = new Array();
  6442. this._tangents = new Array();
  6443. this._normals = new Array();
  6444. this._binormals = new Array();
  6445. for (var p = 0; p < path.length; p++) {
  6446. this._curve[p] = path[p].clone(); // hard copy
  6447. }
  6448. this._raw = raw || false;
  6449. this._compute(firstNormal);
  6450. }
  6451. /**
  6452. * Returns the Path3D array of successive Vector3 designing its curve.
  6453. */
  6454. Path3D.prototype.getCurve = function () {
  6455. return this._curve;
  6456. };
  6457. /**
  6458. * Returns an array populated with tangent vectors on each Path3D curve point.
  6459. */
  6460. Path3D.prototype.getTangents = function () {
  6461. return this._tangents;
  6462. };
  6463. /**
  6464. * Returns an array populated with normal vectors on each Path3D curve point.
  6465. */
  6466. Path3D.prototype.getNormals = function () {
  6467. return this._normals;
  6468. };
  6469. /**
  6470. * Returns an array populated with binormal vectors on each Path3D curve point.
  6471. */
  6472. Path3D.prototype.getBinormals = function () {
  6473. return this._binormals;
  6474. };
  6475. /**
  6476. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6477. */
  6478. Path3D.prototype.getDistances = function () {
  6479. return this._distances;
  6480. };
  6481. /**
  6482. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6483. * Returns the same object updated.
  6484. */
  6485. Path3D.prototype.update = function (path, firstNormal) {
  6486. if (firstNormal === void 0) { firstNormal = null; }
  6487. for (var p = 0; p < path.length; p++) {
  6488. this._curve[p].x = path[p].x;
  6489. this._curve[p].y = path[p].y;
  6490. this._curve[p].z = path[p].z;
  6491. }
  6492. this._compute(firstNormal);
  6493. return this;
  6494. };
  6495. // private function compute() : computes tangents, normals and binormals
  6496. Path3D.prototype._compute = function (firstNormal) {
  6497. var l = this._curve.length;
  6498. // first and last tangents
  6499. this._tangents[0] = this._getFirstNonNullVector(0);
  6500. if (!this._raw) {
  6501. this._tangents[0].normalize();
  6502. }
  6503. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6504. if (!this._raw) {
  6505. this._tangents[l - 1].normalize();
  6506. }
  6507. // normals and binormals at first point : arbitrary vector with _normalVector()
  6508. var tg0 = this._tangents[0];
  6509. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6510. this._normals[0] = pp0;
  6511. if (!this._raw) {
  6512. this._normals[0].normalize();
  6513. }
  6514. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6515. if (!this._raw) {
  6516. this._binormals[0].normalize();
  6517. }
  6518. this._distances[0] = 0.0;
  6519. // normals and binormals : next points
  6520. var prev; // previous vector (segment)
  6521. var cur; // current vector (segment)
  6522. var curTang; // current tangent
  6523. // previous normal
  6524. var prevBinor; // previous binormal
  6525. for (var i = 1; i < l; i++) {
  6526. // tangents
  6527. prev = this._getLastNonNullVector(i);
  6528. if (i < l - 1) {
  6529. cur = this._getFirstNonNullVector(i);
  6530. this._tangents[i] = prev.add(cur);
  6531. this._tangents[i].normalize();
  6532. }
  6533. this._distances[i] = this._distances[i - 1] + prev.length();
  6534. // normals and binormals
  6535. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6536. curTang = this._tangents[i];
  6537. prevBinor = this._binormals[i - 1];
  6538. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6539. if (!this._raw) {
  6540. this._normals[i].normalize();
  6541. }
  6542. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6543. if (!this._raw) {
  6544. this._binormals[i].normalize();
  6545. }
  6546. }
  6547. };
  6548. // private function getFirstNonNullVector(index)
  6549. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6550. Path3D.prototype._getFirstNonNullVector = function (index) {
  6551. var i = 1;
  6552. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6553. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6554. i++;
  6555. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6556. }
  6557. return nNVector;
  6558. };
  6559. // private function getLastNonNullVector(index)
  6560. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6561. Path3D.prototype._getLastNonNullVector = function (index) {
  6562. var i = 1;
  6563. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6564. while (nLVector.length() === 0 && index > i + 1) {
  6565. i++;
  6566. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6567. }
  6568. return nLVector;
  6569. };
  6570. // private function normalVector(v0, vt, va) :
  6571. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6572. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6573. Path3D.prototype._normalVector = function (v0, vt, va) {
  6574. var normal0;
  6575. var tgl = vt.length();
  6576. if (tgl === 0.0) {
  6577. tgl = 1.0;
  6578. }
  6579. if (va === undefined || va === null) {
  6580. var point;
  6581. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6582. point = new Vector3(0.0, -1.0, 0.0);
  6583. }
  6584. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6585. point = new Vector3(1.0, 0.0, 0.0);
  6586. }
  6587. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6588. point = new Vector3(0.0, 0.0, 1.0);
  6589. }
  6590. else {
  6591. point = Vector3.Zero();
  6592. }
  6593. normal0 = Vector3.Cross(vt, point);
  6594. }
  6595. else {
  6596. normal0 = Vector3.Cross(vt, va);
  6597. Vector3.CrossToRef(normal0, vt, normal0);
  6598. }
  6599. normal0.normalize();
  6600. return normal0;
  6601. };
  6602. return Path3D;
  6603. }());
  6604. BABYLON.Path3D = Path3D;
  6605. var Curve3 = /** @class */ (function () {
  6606. /**
  6607. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6608. * A Curve3 is designed from a series of successive Vector3.
  6609. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6610. */
  6611. function Curve3(points) {
  6612. this._length = 0.0;
  6613. this._points = points;
  6614. this._length = this._computeLength(points);
  6615. }
  6616. /**
  6617. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6618. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6619. * @param v1 (Vector3) the control point
  6620. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6621. * @param nbPoints (integer) the wanted number of points in the curve
  6622. */
  6623. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6624. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6625. var bez = new Array();
  6626. var equation = function (t, val0, val1, val2) {
  6627. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6628. return res;
  6629. };
  6630. for (var i = 0; i <= nbPoints; i++) {
  6631. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6632. }
  6633. return new Curve3(bez);
  6634. };
  6635. /**
  6636. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6637. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6638. * @param v1 (Vector3) the first control point
  6639. * @param v2 (Vector3) the second control point
  6640. * @param v3 (Vector3) the end point of the Cubic Bezier
  6641. * @param nbPoints (integer) the wanted number of points in the curve
  6642. */
  6643. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6644. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6645. var bez = new Array();
  6646. var equation = function (t, val0, val1, val2, val3) {
  6647. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6648. return res;
  6649. };
  6650. for (var i = 0; i <= nbPoints; i++) {
  6651. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6652. }
  6653. return new Curve3(bez);
  6654. };
  6655. /**
  6656. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6657. * @param p1 (Vector3) the origin point of the Hermite Spline
  6658. * @param t1 (Vector3) the tangent vector at the origin point
  6659. * @param p2 (Vector3) the end point of the Hermite Spline
  6660. * @param t2 (Vector3) the tangent vector at the end point
  6661. * @param nbPoints (integer) the wanted number of points in the curve
  6662. */
  6663. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6664. var hermite = new Array();
  6665. var step = 1.0 / nbPoints;
  6666. for (var i = 0; i <= nbPoints; i++) {
  6667. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6668. }
  6669. return new Curve3(hermite);
  6670. };
  6671. /**
  6672. * Returns a Curve3 object along a CatmullRom Spline curve :
  6673. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6674. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6675. */
  6676. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6677. var totalPoints = new Array();
  6678. totalPoints.push(points[0].clone());
  6679. Array.prototype.push.apply(totalPoints, points);
  6680. totalPoints.push(points[points.length - 1].clone());
  6681. var catmullRom = new Array();
  6682. var step = 1.0 / nbPoints;
  6683. var amount = 0.0;
  6684. for (var i = 0; i < totalPoints.length - 3; i++) {
  6685. amount = 0;
  6686. for (var c = 0; c < nbPoints; c++) {
  6687. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6688. amount += step;
  6689. }
  6690. }
  6691. i--;
  6692. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6693. return new Curve3(catmullRom);
  6694. };
  6695. /**
  6696. * Returns the Curve3 stored array of successive Vector3
  6697. */
  6698. Curve3.prototype.getPoints = function () {
  6699. return this._points;
  6700. };
  6701. /**
  6702. * Returns the computed length (float) of the curve.
  6703. */
  6704. Curve3.prototype.length = function () {
  6705. return this._length;
  6706. };
  6707. /**
  6708. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6709. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6710. * curveA and curveB keep unchanged.
  6711. */
  6712. Curve3.prototype.continue = function (curve) {
  6713. var lastPoint = this._points[this._points.length - 1];
  6714. var continuedPoints = this._points.slice();
  6715. var curvePoints = curve.getPoints();
  6716. for (var i = 1; i < curvePoints.length; i++) {
  6717. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6718. }
  6719. var continuedCurve = new Curve3(continuedPoints);
  6720. return continuedCurve;
  6721. };
  6722. Curve3.prototype._computeLength = function (path) {
  6723. var l = 0;
  6724. for (var i = 1; i < path.length; i++) {
  6725. l += (path[i].subtract(path[i - 1])).length();
  6726. }
  6727. return l;
  6728. };
  6729. return Curve3;
  6730. }());
  6731. BABYLON.Curve3 = Curve3;
  6732. // Vertex formats
  6733. var PositionNormalVertex = /** @class */ (function () {
  6734. function PositionNormalVertex(position, normal) {
  6735. if (position === void 0) { position = Vector3.Zero(); }
  6736. if (normal === void 0) { normal = Vector3.Up(); }
  6737. this.position = position;
  6738. this.normal = normal;
  6739. }
  6740. PositionNormalVertex.prototype.clone = function () {
  6741. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6742. };
  6743. return PositionNormalVertex;
  6744. }());
  6745. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6746. var PositionNormalTextureVertex = /** @class */ (function () {
  6747. function PositionNormalTextureVertex(position, normal, uv) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. if (uv === void 0) { uv = Vector2.Zero(); }
  6751. this.position = position;
  6752. this.normal = normal;
  6753. this.uv = uv;
  6754. }
  6755. PositionNormalTextureVertex.prototype.clone = function () {
  6756. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6757. };
  6758. return PositionNormalTextureVertex;
  6759. }());
  6760. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6761. // Temporary pre-allocated objects for engine internal use
  6762. // usage in any internal function :
  6763. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6764. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6765. var Tmp = /** @class */ (function () {
  6766. function Tmp() {
  6767. }
  6768. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6769. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6770. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6771. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6772. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6773. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6774. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6775. Matrix.Zero(), Matrix.Zero(),
  6776. Matrix.Zero(), Matrix.Zero(),
  6777. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6778. return Tmp;
  6779. }());
  6780. BABYLON.Tmp = Tmp;
  6781. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6782. var MathTmp = /** @class */ (function () {
  6783. function MathTmp() {
  6784. }
  6785. MathTmp.Vector3 = [Vector3.Zero()];
  6786. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6787. MathTmp.Quaternion = [Quaternion.Zero()];
  6788. return MathTmp;
  6789. }());
  6790. })(BABYLON || (BABYLON = {}));
  6791. //# sourceMappingURL=babylon.math.js.map
  6792. var BABYLON;
  6793. (function (BABYLON) {
  6794. var Scalar = /** @class */ (function () {
  6795. function Scalar() {
  6796. }
  6797. /**
  6798. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6799. */
  6800. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6801. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6802. var num = a - b;
  6803. return -epsilon <= num && num <= epsilon;
  6804. };
  6805. /**
  6806. * Returns a string : the upper case translation of the number i to hexadecimal.
  6807. */
  6808. Scalar.ToHex = function (i) {
  6809. var str = i.toString(16);
  6810. if (i <= 15) {
  6811. return ("0" + str).toUpperCase();
  6812. }
  6813. return str.toUpperCase();
  6814. };
  6815. /**
  6816. * Returns -1 if value is negative and +1 is value is positive.
  6817. * Returns the value itself if it's equal to zero.
  6818. */
  6819. Scalar.Sign = function (value) {
  6820. value = +value; // convert to a number
  6821. if (value === 0 || isNaN(value))
  6822. return value;
  6823. return value > 0 ? 1 : -1;
  6824. };
  6825. /**
  6826. * Returns the value itself if it's between min and max.
  6827. * Returns min if the value is lower than min.
  6828. * Returns max if the value is greater than max.
  6829. */
  6830. Scalar.Clamp = function (value, min, max) {
  6831. if (min === void 0) { min = 0; }
  6832. if (max === void 0) { max = 1; }
  6833. return Math.min(max, Math.max(min, value));
  6834. };
  6835. /**
  6836. * Returns the log2 of value.
  6837. */
  6838. Scalar.Log2 = function (value) {
  6839. return Math.log(value) * Math.LOG2E;
  6840. };
  6841. /**
  6842. * Loops the value, so that it is never larger than length and never smaller than 0.
  6843. *
  6844. * This is similar to the modulo operator but it works with floating point numbers.
  6845. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6846. * With t = 5 and length = 2.5, the result would be 0.0.
  6847. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6848. */
  6849. Scalar.Repeat = function (value, length) {
  6850. return value - Math.floor(value / length) * length;
  6851. };
  6852. /**
  6853. * Normalize the value between 0.0 and 1.0 using min and max values
  6854. */
  6855. Scalar.Normalize = function (value, min, max) {
  6856. return (value - min) / (max - min);
  6857. };
  6858. /**
  6859. * Denormalize the value from 0.0 and 1.0 using min and max values
  6860. */
  6861. Scalar.Denormalize = function (normalized, min, max) {
  6862. return (normalized * (max - min) + min);
  6863. };
  6864. /**
  6865. * Calculates the shortest difference between two given angles given in degrees.
  6866. */
  6867. Scalar.DeltaAngle = function (current, target) {
  6868. var num = Scalar.Repeat(target - current, 360.0);
  6869. if (num > 180.0) {
  6870. num -= 360.0;
  6871. }
  6872. return num;
  6873. };
  6874. /**
  6875. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6876. *
  6877. * The returned value will move back and forth between 0 and length
  6878. */
  6879. Scalar.PingPong = function (tx, length) {
  6880. var t = Scalar.Repeat(tx, length * 2.0);
  6881. return length - Math.abs(t - length);
  6882. };
  6883. /**
  6884. * Interpolates between min and max with smoothing at the limits.
  6885. *
  6886. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6887. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6888. */
  6889. Scalar.SmoothStep = function (from, to, tx) {
  6890. var t = Scalar.Clamp(tx);
  6891. t = -2.0 * t * t * t + 3.0 * t * t;
  6892. return to * t + from * (1.0 - t);
  6893. };
  6894. /**
  6895. * Moves a value current towards target.
  6896. *
  6897. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6898. * Negative values of maxDelta pushes the value away from target.
  6899. */
  6900. Scalar.MoveTowards = function (current, target, maxDelta) {
  6901. var result = 0;
  6902. if (Math.abs(target - current) <= maxDelta) {
  6903. result = target;
  6904. }
  6905. else {
  6906. result = current + Scalar.Sign(target - current) * maxDelta;
  6907. }
  6908. return result;
  6909. };
  6910. /**
  6911. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6912. *
  6913. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6914. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6915. */
  6916. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6917. var num = Scalar.DeltaAngle(current, target);
  6918. var result = 0;
  6919. if (-maxDelta < num && num < maxDelta) {
  6920. result = target;
  6921. }
  6922. else {
  6923. target = current + num;
  6924. result = Scalar.MoveTowards(current, target, maxDelta);
  6925. }
  6926. return result;
  6927. };
  6928. /**
  6929. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6930. */
  6931. Scalar.Lerp = function (start, end, amount) {
  6932. return start + ((end - start) * amount);
  6933. };
  6934. /**
  6935. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6936. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6937. */
  6938. Scalar.LerpAngle = function (start, end, amount) {
  6939. var num = Scalar.Repeat(end - start, 360.0);
  6940. if (num > 180.0) {
  6941. num -= 360.0;
  6942. }
  6943. return start + num * Scalar.Clamp(amount);
  6944. };
  6945. /**
  6946. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6947. */
  6948. Scalar.InverseLerp = function (a, b, value) {
  6949. var result = 0;
  6950. if (a != b) {
  6951. result = Scalar.Clamp((value - a) / (b - a));
  6952. }
  6953. else {
  6954. result = 0.0;
  6955. }
  6956. return result;
  6957. };
  6958. /**
  6959. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6960. */
  6961. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6962. var squared = amount * amount;
  6963. var cubed = amount * squared;
  6964. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6965. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6966. var part3 = (cubed - (2.0 * squared)) + amount;
  6967. var part4 = cubed - squared;
  6968. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6969. };
  6970. /**
  6971. * Returns a random float number between and min and max values
  6972. */
  6973. Scalar.RandomRange = function (min, max) {
  6974. if (min === max)
  6975. return min;
  6976. return ((Math.random() * (max - min)) + min);
  6977. };
  6978. /**
  6979. * This function returns percentage of a number in a given range.
  6980. *
  6981. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6982. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6983. */
  6984. Scalar.RangeToPercent = function (number, min, max) {
  6985. return ((number - min) / (max - min));
  6986. };
  6987. /**
  6988. * This function returns number that corresponds to the percentage in a given range.
  6989. *
  6990. * PercentToRange(0.34,0,100) will return 34.
  6991. */
  6992. Scalar.PercentToRange = function (percent, min, max) {
  6993. return ((max - min) * percent + min);
  6994. };
  6995. /**
  6996. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6997. * @param angle The angle to normalize in radian.
  6998. * @return The converted angle.
  6999. */
  7000. Scalar.NormalizeRadians = function (angle) {
  7001. // More precise but slower version kept for reference.
  7002. // angle = angle % Tools.TwoPi;
  7003. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7004. //if (angle > Math.PI) {
  7005. // angle -= Tools.TwoPi;
  7006. //}
  7007. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7008. return angle;
  7009. };
  7010. /**
  7011. * Two pi constants convenient for computation.
  7012. */
  7013. Scalar.TwoPi = Math.PI * 2;
  7014. return Scalar;
  7015. }());
  7016. BABYLON.Scalar = Scalar;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.math.scalar.js.map
  7019. //# sourceMappingURL=babylon.mixins.js.map
  7020. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7021. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7022. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7023. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7024. //# sourceMappingURL=babylon.webgl2.js.map
  7025. var BABYLON;
  7026. (function (BABYLON) {
  7027. var __decoratorInitialStore = {};
  7028. var __mergedStore = {};
  7029. var _copySource = function (creationFunction, source, instanciate) {
  7030. var destination = creationFunction();
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7034. }
  7035. var classStore = getMergedStore(destination);
  7036. // Properties
  7037. for (var property in classStore) {
  7038. var propertyDescriptor = classStore[property];
  7039. var sourceProperty = source[property];
  7040. var propertyType = propertyDescriptor.type;
  7041. if (sourceProperty !== undefined && sourceProperty !== null) {
  7042. switch (propertyType) {
  7043. case 0: // Value
  7044. case 6:// Mesh reference
  7045. destination[property] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7049. break;
  7050. case 2: // Color3
  7051. case 3: // FresnelParameters
  7052. case 4: // Vector2
  7053. case 5: // Vector3
  7054. case 7: // Color Curves
  7055. case 10:// Quaternion
  7056. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7057. break;
  7058. }
  7059. }
  7060. }
  7061. return destination;
  7062. };
  7063. function getDirectStore(target) {
  7064. var classKey = target.getClassName();
  7065. if (!__decoratorInitialStore[classKey]) {
  7066. __decoratorInitialStore[classKey] = {};
  7067. }
  7068. return __decoratorInitialStore[classKey];
  7069. }
  7070. /**
  7071. * Return the list of properties flagged as serializable
  7072. * @param target: host object
  7073. */
  7074. function getMergedStore(target) {
  7075. var classKey = target.getClassName();
  7076. if (__mergedStore[classKey]) {
  7077. return __mergedStore[classKey];
  7078. }
  7079. __mergedStore[classKey] = {};
  7080. var store = __mergedStore[classKey];
  7081. var currentTarget = target;
  7082. var currentKey = classKey;
  7083. while (currentKey) {
  7084. var initialStore = __decoratorInitialStore[currentKey];
  7085. for (var property in initialStore) {
  7086. store[property] = initialStore[property];
  7087. }
  7088. var parent_1 = void 0;
  7089. var done = false;
  7090. do {
  7091. parent_1 = Object.getPrototypeOf(currentTarget);
  7092. if (!parent_1.getClassName) {
  7093. done = true;
  7094. break;
  7095. }
  7096. if (parent_1.getClassName() !== currentKey) {
  7097. break;
  7098. }
  7099. currentTarget = parent_1;
  7100. } while (parent_1);
  7101. if (done) {
  7102. break;
  7103. }
  7104. currentKey = parent_1.getClassName();
  7105. currentTarget = parent_1;
  7106. }
  7107. return store;
  7108. }
  7109. function generateSerializableMember(type, sourceName) {
  7110. return function (target, propertyKey) {
  7111. var classStore = getDirectStore(target);
  7112. if (!classStore[propertyKey]) {
  7113. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7114. }
  7115. };
  7116. }
  7117. function generateExpandMember(setCallback, targetKey) {
  7118. if (targetKey === void 0) { targetKey = null; }
  7119. return function (target, propertyKey) {
  7120. var key = targetKey || ("_" + propertyKey);
  7121. Object.defineProperty(target, propertyKey, {
  7122. get: function () {
  7123. return this[key];
  7124. },
  7125. set: function (value) {
  7126. if (this[key] === value) {
  7127. return;
  7128. }
  7129. this[key] = value;
  7130. target[setCallback].apply(this);
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. };
  7136. }
  7137. function expandToProperty(callback, targetKey) {
  7138. if (targetKey === void 0) { targetKey = null; }
  7139. return generateExpandMember(callback, targetKey);
  7140. }
  7141. BABYLON.expandToProperty = expandToProperty;
  7142. function serialize(sourceName) {
  7143. return generateSerializableMember(0, sourceName); // value member
  7144. }
  7145. BABYLON.serialize = serialize;
  7146. function serializeAsTexture(sourceName) {
  7147. return generateSerializableMember(1, sourceName); // texture member
  7148. }
  7149. BABYLON.serializeAsTexture = serializeAsTexture;
  7150. function serializeAsColor3(sourceName) {
  7151. return generateSerializableMember(2, sourceName); // color3 member
  7152. }
  7153. BABYLON.serializeAsColor3 = serializeAsColor3;
  7154. function serializeAsFresnelParameters(sourceName) {
  7155. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7156. }
  7157. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7158. function serializeAsVector2(sourceName) {
  7159. return generateSerializableMember(4, sourceName); // vector2 member
  7160. }
  7161. BABYLON.serializeAsVector2 = serializeAsVector2;
  7162. function serializeAsVector3(sourceName) {
  7163. return generateSerializableMember(5, sourceName); // vector3 member
  7164. }
  7165. BABYLON.serializeAsVector3 = serializeAsVector3;
  7166. function serializeAsMeshReference(sourceName) {
  7167. return generateSerializableMember(6, sourceName); // mesh reference member
  7168. }
  7169. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7170. function serializeAsColorCurves(sourceName) {
  7171. return generateSerializableMember(7, sourceName); // color curves
  7172. }
  7173. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7174. function serializeAsColor4(sourceName) {
  7175. return generateSerializableMember(8, sourceName); // color 4
  7176. }
  7177. BABYLON.serializeAsColor4 = serializeAsColor4;
  7178. function serializeAsImageProcessingConfiguration(sourceName) {
  7179. return generateSerializableMember(9, sourceName); // image processing
  7180. }
  7181. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7182. function serializeAsQuaternion(sourceName) {
  7183. return generateSerializableMember(10, sourceName); // quaternion member
  7184. }
  7185. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7186. var SerializationHelper = /** @class */ (function () {
  7187. function SerializationHelper() {
  7188. }
  7189. SerializationHelper.Serialize = function (entity, serializationObject) {
  7190. if (!serializationObject) {
  7191. serializationObject = {};
  7192. }
  7193. // Tags
  7194. if (BABYLON.Tags) {
  7195. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7196. }
  7197. var serializedProperties = getMergedStore(entity);
  7198. // Properties
  7199. for (var property in serializedProperties) {
  7200. var propertyDescriptor = serializedProperties[property];
  7201. var targetPropertyName = propertyDescriptor.sourceName || property;
  7202. var propertyType = propertyDescriptor.type;
  7203. var sourceProperty = entity[property];
  7204. if (sourceProperty !== undefined && sourceProperty !== null) {
  7205. switch (propertyType) {
  7206. case 0:// Value
  7207. serializationObject[targetPropertyName] = sourceProperty;
  7208. break;
  7209. case 1:// Texture
  7210. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7211. break;
  7212. case 2:// Color3
  7213. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7214. break;
  7215. case 3:// FresnelParameters
  7216. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7217. break;
  7218. case 4:// Vector2
  7219. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7220. break;
  7221. case 5:// Vector3
  7222. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7223. break;
  7224. case 6:// Mesh reference
  7225. serializationObject[targetPropertyName] = sourceProperty.id;
  7226. break;
  7227. case 7:// Color Curves
  7228. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7229. break;
  7230. case 8:// Color 4
  7231. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7232. break;
  7233. case 9:// Image Processing
  7234. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7235. break;
  7236. }
  7237. }
  7238. }
  7239. return serializationObject;
  7240. };
  7241. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7242. if (rootUrl === void 0) { rootUrl = null; }
  7243. var destination = creationFunction();
  7244. if (!rootUrl) {
  7245. rootUrl = "";
  7246. }
  7247. // Tags
  7248. if (BABYLON.Tags) {
  7249. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7250. }
  7251. var classStore = getMergedStore(destination);
  7252. // Properties
  7253. for (var property in classStore) {
  7254. var propertyDescriptor = classStore[property];
  7255. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7256. var propertyType = propertyDescriptor.type;
  7257. if (sourceProperty !== undefined && sourceProperty !== null) {
  7258. var dest = destination;
  7259. switch (propertyType) {
  7260. case 0:// Value
  7261. dest[property] = sourceProperty;
  7262. break;
  7263. case 1:// Texture
  7264. if (scene) {
  7265. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7266. }
  7267. break;
  7268. case 2:// Color3
  7269. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7270. break;
  7271. case 3:// FresnelParameters
  7272. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7273. break;
  7274. case 4:// Vector2
  7275. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7276. break;
  7277. case 5:// Vector3
  7278. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7279. break;
  7280. case 6:// Mesh reference
  7281. if (scene) {
  7282. dest[property] = scene.getLastMeshByID(sourceProperty);
  7283. }
  7284. break;
  7285. case 7:// Color Curves
  7286. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7287. break;
  7288. case 8:// Color 4
  7289. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7290. break;
  7291. case 9:// Image Processing
  7292. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7293. break;
  7294. }
  7295. }
  7296. }
  7297. return destination;
  7298. };
  7299. SerializationHelper.Clone = function (creationFunction, source) {
  7300. return _copySource(creationFunction, source, false);
  7301. };
  7302. SerializationHelper.Instanciate = function (creationFunction, source) {
  7303. return _copySource(creationFunction, source, true);
  7304. };
  7305. return SerializationHelper;
  7306. }());
  7307. BABYLON.SerializationHelper = SerializationHelper;
  7308. })(BABYLON || (BABYLON = {}));
  7309. //# sourceMappingURL=babylon.decorators.js.map
  7310. var BABYLON;
  7311. (function (BABYLON) {
  7312. /**
  7313. * Wrapper class for promise with external resolve and reject.
  7314. */
  7315. var Deferred = /** @class */ (function () {
  7316. /**
  7317. * Constructor for this deferred object.
  7318. */
  7319. function Deferred() {
  7320. var _this = this;
  7321. this.promise = new Promise(function (resolve, reject) {
  7322. _this._resolve = resolve;
  7323. _this._reject = reject;
  7324. });
  7325. }
  7326. Object.defineProperty(Deferred.prototype, "resolve", {
  7327. /**
  7328. * The resolve method of the promise associated with this deferred object.
  7329. */
  7330. get: function () {
  7331. return this._resolve;
  7332. },
  7333. enumerable: true,
  7334. configurable: true
  7335. });
  7336. Object.defineProperty(Deferred.prototype, "reject", {
  7337. /**
  7338. * The reject method of the promise associated with this deferred object.
  7339. */
  7340. get: function () {
  7341. return this._reject;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. return Deferred;
  7347. }());
  7348. BABYLON.Deferred = Deferred;
  7349. })(BABYLON || (BABYLON = {}));
  7350. //# sourceMappingURL=babylon.deferred.js.map
  7351. var BABYLON;
  7352. (function (BABYLON) {
  7353. /**
  7354. * A class serves as a medium between the observable and its observers
  7355. */
  7356. var EventState = /** @class */ (function () {
  7357. /**
  7358. * Create a new EventState
  7359. * @param mask defines the mask associated with this state
  7360. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7361. * @param target defines the original target of the state
  7362. * @param currentTarget defines the current target of the state
  7363. */
  7364. function EventState(mask, skipNextObservers, target, currentTarget) {
  7365. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7366. this.initalize(mask, skipNextObservers, target, currentTarget);
  7367. }
  7368. /**
  7369. * Initialize the current event state
  7370. * @param mask defines the mask associated with this state
  7371. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7372. * @param target defines the original target of the state
  7373. * @param currentTarget defines the current target of the state
  7374. * @returns the current event state
  7375. */
  7376. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7377. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7378. this.mask = mask;
  7379. this.skipNextObservers = skipNextObservers;
  7380. this.target = target;
  7381. this.currentTarget = currentTarget;
  7382. return this;
  7383. };
  7384. return EventState;
  7385. }());
  7386. BABYLON.EventState = EventState;
  7387. /**
  7388. * Represent an Observer registered to a given Observable object.
  7389. */
  7390. var Observer = /** @class */ (function () {
  7391. /**
  7392. * Creates a new observer
  7393. * @param callback defines the callback to call when the observer is notified
  7394. * @param mask defines the mask of the observer (used to filter notifications)
  7395. * @param scope defines the current scope used to restore the JS context
  7396. */
  7397. function Observer(
  7398. /**
  7399. * Defines the callback to call when the observer is notified
  7400. */
  7401. callback,
  7402. /**
  7403. * Defines the mask of the observer (used to filter notifications)
  7404. */
  7405. mask,
  7406. /**
  7407. * Defines the current scope used to restore the JS context
  7408. */
  7409. scope) {
  7410. if (scope === void 0) { scope = null; }
  7411. this.callback = callback;
  7412. this.mask = mask;
  7413. this.scope = scope;
  7414. /** @ignore */
  7415. this._willBeUnregistered = false;
  7416. /**
  7417. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7418. */
  7419. this.unregisterOnNextCall = false;
  7420. }
  7421. return Observer;
  7422. }());
  7423. BABYLON.Observer = Observer;
  7424. /**
  7425. * Represent a list of observers registered to multiple Observables object.
  7426. */
  7427. var MultiObserver = /** @class */ (function () {
  7428. function MultiObserver() {
  7429. }
  7430. /**
  7431. * Release associated resources
  7432. */
  7433. MultiObserver.prototype.dispose = function () {
  7434. if (this._observers && this._observables) {
  7435. for (var index = 0; index < this._observers.length; index++) {
  7436. this._observables[index].remove(this._observers[index]);
  7437. }
  7438. }
  7439. this._observers = null;
  7440. this._observables = null;
  7441. };
  7442. /**
  7443. * Raise a callback when one of the observable will notify
  7444. * @param observables defines a list of observables to watch
  7445. * @param callback defines the callback to call on notification
  7446. * @param mask defines the mask used to filter notifications
  7447. * @param scope defines the current scope used to restore the JS context
  7448. * @returns the new MultiObserver
  7449. */
  7450. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7451. if (mask === void 0) { mask = -1; }
  7452. if (scope === void 0) { scope = null; }
  7453. var result = new MultiObserver();
  7454. result._observers = new Array();
  7455. result._observables = observables;
  7456. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7457. var observable = observables_1[_i];
  7458. var observer = observable.add(callback, mask, false, scope);
  7459. if (observer) {
  7460. result._observers.push(observer);
  7461. }
  7462. }
  7463. return result;
  7464. };
  7465. return MultiObserver;
  7466. }());
  7467. BABYLON.MultiObserver = MultiObserver;
  7468. /**
  7469. * The Observable class is a simple implementation of the Observable pattern.
  7470. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  7471. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7472. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  7473. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  7474. */
  7475. var Observable = /** @class */ (function () {
  7476. /**
  7477. * Creates a new observable
  7478. * @param onObserverAdded defines a callback to call when a new observer is added
  7479. */
  7480. function Observable(onObserverAdded) {
  7481. this._observers = new Array();
  7482. this._eventState = new EventState(0);
  7483. if (onObserverAdded) {
  7484. this._onObserverAdded = onObserverAdded;
  7485. }
  7486. }
  7487. /**
  7488. * Create a new Observer with the specified callback
  7489. * @param callback the callback that will be executed for that Observer
  7490. * @param mask the mask used to filter observers
  7491. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  7492. * @param scope optional scope for the callback to be called from
  7493. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7494. * @returns the new observer created for the callback
  7495. */
  7496. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7497. if (mask === void 0) { mask = -1; }
  7498. if (insertFirst === void 0) { insertFirst = false; }
  7499. if (scope === void 0) { scope = null; }
  7500. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7501. if (!callback) {
  7502. return null;
  7503. }
  7504. var observer = new Observer(callback, mask, scope);
  7505. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7506. if (insertFirst) {
  7507. this._observers.unshift(observer);
  7508. }
  7509. else {
  7510. this._observers.push(observer);
  7511. }
  7512. if (this._onObserverAdded) {
  7513. this._onObserverAdded(observer);
  7514. }
  7515. return observer;
  7516. };
  7517. /**
  7518. * Remove an Observer from the Observable object
  7519. * @param observer the instance of the Observer to remove
  7520. * @returns false if it doesn't belong to this Observable
  7521. */
  7522. Observable.prototype.remove = function (observer) {
  7523. if (!observer) {
  7524. return false;
  7525. }
  7526. var index = this._observers.indexOf(observer);
  7527. if (index !== -1) {
  7528. this._observers.splice(index, 1);
  7529. return true;
  7530. }
  7531. return false;
  7532. };
  7533. /**
  7534. * Remove a callback from the Observable object
  7535. * @param callback the callback to remove
  7536. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7537. * @returns false if it doesn't belong to this Observable
  7538. */
  7539. Observable.prototype.removeCallback = function (callback, scope) {
  7540. for (var index = 0; index < this._observers.length; index++) {
  7541. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7542. this._observers.splice(index, 1);
  7543. return true;
  7544. }
  7545. }
  7546. return false;
  7547. };
  7548. Observable.prototype._deferUnregister = function (observer) {
  7549. var _this = this;
  7550. observer.unregisterOnNextCall = false;
  7551. observer._willBeUnregistered = true;
  7552. BABYLON.Tools.SetImmediate(function () {
  7553. _this.remove(observer);
  7554. });
  7555. };
  7556. /**
  7557. * Notify all Observers by calling their respective callback with the given data
  7558. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7559. * @param eventData defines the data to send to all observers
  7560. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7561. * @param target defines the original target of the state
  7562. * @param currentTarget defines the current target of the state
  7563. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7564. */
  7565. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7566. if (mask === void 0) { mask = -1; }
  7567. if (!this._observers.length) {
  7568. return true;
  7569. }
  7570. var state = this._eventState;
  7571. state.mask = mask;
  7572. state.target = target;
  7573. state.currentTarget = currentTarget;
  7574. state.skipNextObservers = false;
  7575. state.lastReturnValue = eventData;
  7576. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7577. var obs = _a[_i];
  7578. if (obs._willBeUnregistered) {
  7579. continue;
  7580. }
  7581. if (obs.mask & mask) {
  7582. if (obs.scope) {
  7583. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7584. }
  7585. else {
  7586. state.lastReturnValue = obs.callback(eventData, state);
  7587. }
  7588. if (obs.unregisterOnNextCall) {
  7589. this._deferUnregister(obs);
  7590. }
  7591. }
  7592. if (state.skipNextObservers) {
  7593. return false;
  7594. }
  7595. }
  7596. return true;
  7597. };
  7598. /**
  7599. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7600. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7601. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7602. * and it is crucial that all callbacks will be executed.
  7603. * The order of the callbacks is kept, callbacks are not executed parallel.
  7604. *
  7605. * @param eventData The data to be sent to each callback
  7606. * @param mask is used to filter observers defaults to -1
  7607. * @param target defines the callback target (see EventState)
  7608. * @param currentTarget defines he current object in the bubbling phase
  7609. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7610. */
  7611. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7612. var _this = this;
  7613. if (mask === void 0) { mask = -1; }
  7614. // create an empty promise
  7615. var p = Promise.resolve(eventData);
  7616. // no observers? return this promise.
  7617. if (!this._observers.length) {
  7618. return p;
  7619. }
  7620. var state = this._eventState;
  7621. state.mask = mask;
  7622. state.target = target;
  7623. state.currentTarget = currentTarget;
  7624. state.skipNextObservers = false;
  7625. // execute one callback after another (not using Promise.all, the order is important)
  7626. this._observers.forEach(function (obs) {
  7627. if (state.skipNextObservers) {
  7628. return;
  7629. }
  7630. if (obs._willBeUnregistered) {
  7631. return;
  7632. }
  7633. if (obs.mask & mask) {
  7634. if (obs.scope) {
  7635. p = p.then(function (lastReturnedValue) {
  7636. state.lastReturnValue = lastReturnedValue;
  7637. return obs.callback.apply(obs.scope, [eventData, state]);
  7638. });
  7639. }
  7640. else {
  7641. p = p.then(function (lastReturnedValue) {
  7642. state.lastReturnValue = lastReturnedValue;
  7643. return obs.callback(eventData, state);
  7644. });
  7645. }
  7646. if (obs.unregisterOnNextCall) {
  7647. _this._deferUnregister(obs);
  7648. }
  7649. }
  7650. });
  7651. // return the eventData
  7652. return p.then(function () { return eventData; });
  7653. };
  7654. /**
  7655. * Notify a specific observer
  7656. * @param observer defines the observer to notify
  7657. * @param eventData defines the data to be sent to each callback
  7658. * @param mask is used to filter observers defaults to -1
  7659. */
  7660. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7661. if (mask === void 0) { mask = -1; }
  7662. var state = this._eventState;
  7663. state.mask = mask;
  7664. state.skipNextObservers = false;
  7665. observer.callback(eventData, state);
  7666. };
  7667. /**
  7668. * Gets a boolean indicating if the observable has at least one observer
  7669. * @returns true is the Observable has at least one Observer registered
  7670. */
  7671. Observable.prototype.hasObservers = function () {
  7672. return this._observers.length > 0;
  7673. };
  7674. /**
  7675. * Clear the list of observers
  7676. */
  7677. Observable.prototype.clear = function () {
  7678. this._observers = new Array();
  7679. this._onObserverAdded = null;
  7680. };
  7681. /**
  7682. * Clone the current observable
  7683. * @returns a new observable
  7684. */
  7685. Observable.prototype.clone = function () {
  7686. var result = new Observable();
  7687. result._observers = this._observers.slice(0);
  7688. return result;
  7689. };
  7690. /**
  7691. * Does this observable handles observer registered with a given mask
  7692. * @param mask defines the mask to be tested
  7693. * @return whether or not one observer registered with the given mask is handeled
  7694. **/
  7695. Observable.prototype.hasSpecificMask = function (mask) {
  7696. if (mask === void 0) { mask = -1; }
  7697. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7698. var obs = _a[_i];
  7699. if (obs.mask & mask || obs.mask === mask) {
  7700. return true;
  7701. }
  7702. }
  7703. return false;
  7704. };
  7705. return Observable;
  7706. }());
  7707. BABYLON.Observable = Observable;
  7708. })(BABYLON || (BABYLON = {}));
  7709. //# sourceMappingURL=babylon.observable.js.map
  7710. var BABYLON;
  7711. (function (BABYLON) {
  7712. var SmartArray = /** @class */ (function () {
  7713. function SmartArray(capacity) {
  7714. this.length = 0;
  7715. this.data = new Array(capacity);
  7716. this._id = SmartArray._GlobalId++;
  7717. }
  7718. SmartArray.prototype.push = function (value) {
  7719. this.data[this.length++] = value;
  7720. if (this.length > this.data.length) {
  7721. this.data.length *= 2;
  7722. }
  7723. };
  7724. SmartArray.prototype.forEach = function (func) {
  7725. for (var index = 0; index < this.length; index++) {
  7726. func(this.data[index]);
  7727. }
  7728. };
  7729. SmartArray.prototype.sort = function (compareFn) {
  7730. this.data.sort(compareFn);
  7731. };
  7732. SmartArray.prototype.reset = function () {
  7733. this.length = 0;
  7734. };
  7735. SmartArray.prototype.dispose = function () {
  7736. this.reset();
  7737. if (this.data) {
  7738. this.data.length = 0;
  7739. this.data = [];
  7740. }
  7741. };
  7742. SmartArray.prototype.concat = function (array) {
  7743. if (array.length === 0) {
  7744. return;
  7745. }
  7746. if (this.length + array.length > this.data.length) {
  7747. this.data.length = (this.length + array.length) * 2;
  7748. }
  7749. for (var index = 0; index < array.length; index++) {
  7750. this.data[this.length++] = (array.data || array)[index];
  7751. }
  7752. };
  7753. SmartArray.prototype.indexOf = function (value) {
  7754. var position = this.data.indexOf(value);
  7755. if (position >= this.length) {
  7756. return -1;
  7757. }
  7758. return position;
  7759. };
  7760. SmartArray.prototype.contains = function (value) {
  7761. return this.data.indexOf(value) !== -1;
  7762. };
  7763. // Statics
  7764. SmartArray._GlobalId = 0;
  7765. return SmartArray;
  7766. }());
  7767. BABYLON.SmartArray = SmartArray;
  7768. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7769. __extends(SmartArrayNoDuplicate, _super);
  7770. function SmartArrayNoDuplicate() {
  7771. var _this = _super !== null && _super.apply(this, arguments) || this;
  7772. _this._duplicateId = 0;
  7773. return _this;
  7774. }
  7775. SmartArrayNoDuplicate.prototype.push = function (value) {
  7776. _super.prototype.push.call(this, value);
  7777. if (!value.__smartArrayFlags) {
  7778. value.__smartArrayFlags = {};
  7779. }
  7780. value.__smartArrayFlags[this._id] = this._duplicateId;
  7781. };
  7782. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7783. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7784. return false;
  7785. }
  7786. this.push(value);
  7787. return true;
  7788. };
  7789. SmartArrayNoDuplicate.prototype.reset = function () {
  7790. _super.prototype.reset.call(this);
  7791. this._duplicateId++;
  7792. };
  7793. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7794. if (array.length === 0) {
  7795. return;
  7796. }
  7797. if (this.length + array.length > this.data.length) {
  7798. this.data.length = (this.length + array.length) * 2;
  7799. }
  7800. for (var index = 0; index < array.length; index++) {
  7801. var item = (array.data || array)[index];
  7802. this.pushNoDuplicate(item);
  7803. }
  7804. };
  7805. return SmartArrayNoDuplicate;
  7806. }(SmartArray));
  7807. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7808. })(BABYLON || (BABYLON = {}));
  7809. //# sourceMappingURL=babylon.smartArray.js.map
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7813. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7814. var LoadFileError = /** @class */ (function (_super) {
  7815. __extends(LoadFileError, _super);
  7816. function LoadFileError(message, request) {
  7817. var _this = _super.call(this, message) || this;
  7818. _this.request = request;
  7819. _this.name = "LoadFileError";
  7820. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7821. return _this;
  7822. }
  7823. // Polyfill for Object.setPrototypeOf if necessary.
  7824. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7825. return LoadFileError;
  7826. }(Error));
  7827. BABYLON.LoadFileError = LoadFileError;
  7828. var RetryStrategy = /** @class */ (function () {
  7829. function RetryStrategy() {
  7830. }
  7831. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7832. if (maxRetries === void 0) { maxRetries = 3; }
  7833. if (baseInterval === void 0) { baseInterval = 500; }
  7834. return function (url, request, retryIndex) {
  7835. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7836. return -1;
  7837. }
  7838. return Math.pow(2, retryIndex) * baseInterval;
  7839. };
  7840. };
  7841. return RetryStrategy;
  7842. }());
  7843. BABYLON.RetryStrategy = RetryStrategy;
  7844. // Screenshots
  7845. var screenshotCanvas;
  7846. var cloneValue = function (source, destinationObject) {
  7847. if (!source)
  7848. return null;
  7849. if (source instanceof BABYLON.Mesh) {
  7850. return null;
  7851. }
  7852. if (source instanceof BABYLON.SubMesh) {
  7853. return source.clone(destinationObject);
  7854. }
  7855. else if (source.clone) {
  7856. return source.clone();
  7857. }
  7858. return null;
  7859. };
  7860. var Tools = /** @class */ (function () {
  7861. function Tools() {
  7862. }
  7863. /**
  7864. * Interpolates between a and b via alpha
  7865. * @param a The lower value (returned when alpha = 0)
  7866. * @param b The upper value (returned when alpha = 1)
  7867. * @param alpha The interpolation-factor
  7868. * @return The mixed value
  7869. */
  7870. Tools.Mix = function (a, b, alpha) {
  7871. return a * (1 - alpha) + b * alpha;
  7872. };
  7873. Tools.Instantiate = function (className) {
  7874. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7875. return Tools.RegisteredExternalClasses[className];
  7876. }
  7877. var arr = className.split(".");
  7878. var fn = (window || this);
  7879. for (var i = 0, len = arr.length; i < len; i++) {
  7880. fn = fn[arr[i]];
  7881. }
  7882. if (typeof fn !== "function") {
  7883. return null;
  7884. }
  7885. return fn;
  7886. };
  7887. /**
  7888. * Provides a slice function that will work even on IE
  7889. * @param data defines the array to slice
  7890. * @returns the new sliced array
  7891. */
  7892. Tools.Slice = function (data) {
  7893. if (data.slice) {
  7894. return data.slice();
  7895. }
  7896. return Array.prototype.slice.call(data);
  7897. };
  7898. Tools.SetImmediate = function (action) {
  7899. if (window.setImmediate) {
  7900. window.setImmediate(action);
  7901. }
  7902. else {
  7903. setTimeout(action, 1);
  7904. }
  7905. };
  7906. Tools.IsExponentOfTwo = function (value) {
  7907. var count = 1;
  7908. do {
  7909. count *= 2;
  7910. } while (count < value);
  7911. return count === value;
  7912. };
  7913. /**
  7914. * Find the next highest power of two.
  7915. * @param x Number to start search from.
  7916. * @return Next highest power of two.
  7917. */
  7918. Tools.CeilingPOT = function (x) {
  7919. x--;
  7920. x |= x >> 1;
  7921. x |= x >> 2;
  7922. x |= x >> 4;
  7923. x |= x >> 8;
  7924. x |= x >> 16;
  7925. x++;
  7926. return x;
  7927. };
  7928. /**
  7929. * Find the next lowest power of two.
  7930. * @param x Number to start search from.
  7931. * @return Next lowest power of two.
  7932. */
  7933. Tools.FloorPOT = function (x) {
  7934. x = x | (x >> 1);
  7935. x = x | (x >> 2);
  7936. x = x | (x >> 4);
  7937. x = x | (x >> 8);
  7938. x = x | (x >> 16);
  7939. return x - (x >> 1);
  7940. };
  7941. /**
  7942. * Find the nearest power of two.
  7943. * @param x Number to start search from.
  7944. * @return Next nearest power of two.
  7945. */
  7946. Tools.NearestPOT = function (x) {
  7947. var c = Tools.CeilingPOT(x);
  7948. var f = Tools.FloorPOT(x);
  7949. return (c - x) > (x - f) ? f : c;
  7950. };
  7951. Tools.GetExponentOfTwo = function (value, max, mode) {
  7952. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7953. var pot;
  7954. switch (mode) {
  7955. case BABYLON.Engine.SCALEMODE_FLOOR:
  7956. pot = Tools.FloorPOT(value);
  7957. break;
  7958. case BABYLON.Engine.SCALEMODE_NEAREST:
  7959. pot = Tools.NearestPOT(value);
  7960. break;
  7961. case BABYLON.Engine.SCALEMODE_CEILING:
  7962. default:
  7963. pot = Tools.CeilingPOT(value);
  7964. break;
  7965. }
  7966. return Math.min(pot, max);
  7967. };
  7968. Tools.GetFilename = function (path) {
  7969. var index = path.lastIndexOf("/");
  7970. if (index < 0)
  7971. return path;
  7972. return path.substring(index + 1);
  7973. };
  7974. /**
  7975. * Extracts the "folder" part of a path (everything before the filename).
  7976. * @param uri The URI to extract the info from
  7977. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7978. * @returns The "folder" part of the path
  7979. */
  7980. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7981. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7982. var index = uri.lastIndexOf("/");
  7983. if (index < 0) {
  7984. if (returnUnchangedIfNoSlash) {
  7985. return uri;
  7986. }
  7987. return "";
  7988. }
  7989. return uri.substring(0, index + 1);
  7990. };
  7991. Tools.GetDOMTextContent = function (element) {
  7992. var result = "";
  7993. var child = element.firstChild;
  7994. while (child) {
  7995. if (child.nodeType === 3) {
  7996. result += child.textContent;
  7997. }
  7998. child = child.nextSibling;
  7999. }
  8000. return result;
  8001. };
  8002. Tools.ToDegrees = function (angle) {
  8003. return angle * 180 / Math.PI;
  8004. };
  8005. Tools.ToRadians = function (angle) {
  8006. return angle * Math.PI / 180;
  8007. };
  8008. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8009. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8010. var output = "";
  8011. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8012. var i = 0;
  8013. var bytes = new Uint8Array(buffer);
  8014. while (i < bytes.length) {
  8015. chr1 = bytes[i++];
  8016. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8017. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8018. enc1 = chr1 >> 2;
  8019. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8020. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8021. enc4 = chr3 & 63;
  8022. if (isNaN(chr2)) {
  8023. enc3 = enc4 = 64;
  8024. }
  8025. else if (isNaN(chr3)) {
  8026. enc4 = 64;
  8027. }
  8028. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8029. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8030. }
  8031. return "data:image/png;base64," + output;
  8032. };
  8033. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8034. if (bias === void 0) { bias = null; }
  8035. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8036. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8037. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8038. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8039. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8040. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8041. }
  8042. if (bias) {
  8043. minimum.x -= minimum.x * bias.x + bias.y;
  8044. minimum.y -= minimum.y * bias.x + bias.y;
  8045. minimum.z -= minimum.z * bias.x + bias.y;
  8046. maximum.x += maximum.x * bias.x + bias.y;
  8047. maximum.y += maximum.y * bias.x + bias.y;
  8048. maximum.z += maximum.z * bias.x + bias.y;
  8049. }
  8050. return {
  8051. minimum: minimum,
  8052. maximum: maximum
  8053. };
  8054. };
  8055. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. if (!stride) {
  8060. stride = 3;
  8061. }
  8062. for (var index = start; index < start + count; index++) {
  8063. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8064. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8065. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8066. }
  8067. if (bias) {
  8068. minimum.x -= minimum.x * bias.x + bias.y;
  8069. minimum.y -= minimum.y * bias.x + bias.y;
  8070. minimum.z -= minimum.z * bias.x + bias.y;
  8071. maximum.x += maximum.x * bias.x + bias.y;
  8072. maximum.y += maximum.y * bias.x + bias.y;
  8073. maximum.z += maximum.z * bias.x + bias.y;
  8074. }
  8075. return {
  8076. minimum: minimum,
  8077. maximum: maximum
  8078. };
  8079. };
  8080. Tools.Vector2ArrayFeeder = function (array) {
  8081. return function (index) {
  8082. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8083. var length = isFloatArray ? array.length / 2 : array.length;
  8084. if (index >= length) {
  8085. return null;
  8086. }
  8087. if (isFloatArray) {
  8088. var fa = array;
  8089. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8090. }
  8091. var a = array;
  8092. return a[index];
  8093. };
  8094. };
  8095. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8096. if (bias === void 0) { bias = null; }
  8097. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8098. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8099. var i = 0;
  8100. var cur = feeder(i++);
  8101. while (cur) {
  8102. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8103. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8104. cur = feeder(i++);
  8105. }
  8106. if (bias) {
  8107. minimum.x -= minimum.x * bias.x + bias.y;
  8108. minimum.y -= minimum.y * bias.x + bias.y;
  8109. maximum.x += maximum.x * bias.x + bias.y;
  8110. maximum.y += maximum.y * bias.x + bias.y;
  8111. }
  8112. return {
  8113. minimum: minimum,
  8114. maximum: maximum
  8115. };
  8116. };
  8117. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8118. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8119. return null;
  8120. return Array.isArray(obj) ? obj : [obj];
  8121. };
  8122. // Misc.
  8123. Tools.GetPointerPrefix = function () {
  8124. var eventPrefix = "pointer";
  8125. // Check if pointer events are supported
  8126. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8127. eventPrefix = "mouse";
  8128. }
  8129. return eventPrefix;
  8130. };
  8131. /**
  8132. * @param func - the function to be called
  8133. * @param requester - the object that will request the next frame. Falls back to window.
  8134. */
  8135. Tools.QueueNewFrame = function (func, requester) {
  8136. if (!Tools.IsWindowObjectExist()) {
  8137. return setTimeout(func, 16);
  8138. }
  8139. if (!requester) {
  8140. requester = window;
  8141. }
  8142. if (requester.requestAnimationFrame) {
  8143. return requester.requestAnimationFrame(func);
  8144. }
  8145. else if (requester.msRequestAnimationFrame) {
  8146. return requester.msRequestAnimationFrame(func);
  8147. }
  8148. else if (requester.webkitRequestAnimationFrame) {
  8149. return requester.webkitRequestAnimationFrame(func);
  8150. }
  8151. else if (requester.mozRequestAnimationFrame) {
  8152. return requester.mozRequestAnimationFrame(func);
  8153. }
  8154. else if (requester.oRequestAnimationFrame) {
  8155. return requester.oRequestAnimationFrame(func);
  8156. }
  8157. else {
  8158. return window.setTimeout(func, 16);
  8159. }
  8160. };
  8161. Tools.RequestFullscreen = function (element) {
  8162. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8163. if (!requestFunction)
  8164. return;
  8165. requestFunction.call(element);
  8166. };
  8167. Tools.ExitFullscreen = function () {
  8168. if (document.exitFullscreen) {
  8169. document.exitFullscreen();
  8170. }
  8171. else if (document.mozCancelFullScreen) {
  8172. document.mozCancelFullScreen();
  8173. }
  8174. else if (document.webkitCancelFullScreen) {
  8175. document.webkitCancelFullScreen();
  8176. }
  8177. else if (document.msCancelFullScreen) {
  8178. document.msCancelFullScreen();
  8179. }
  8180. };
  8181. Tools.SetCorsBehavior = function (url, element) {
  8182. if (url && url.indexOf("data:") === 0) {
  8183. return;
  8184. }
  8185. if (Tools.CorsBehavior) {
  8186. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8187. element.crossOrigin = Tools.CorsBehavior;
  8188. }
  8189. else {
  8190. var result = Tools.CorsBehavior(url);
  8191. if (result) {
  8192. element.crossOrigin = result;
  8193. }
  8194. }
  8195. }
  8196. };
  8197. // External files
  8198. Tools.CleanUrl = function (url) {
  8199. url = url.replace(/#/mg, "%23");
  8200. return url;
  8201. };
  8202. Tools.LoadImage = function (url, onLoad, onError, database) {
  8203. if (url instanceof ArrayBuffer) {
  8204. url = Tools.EncodeArrayBufferTobase64(url);
  8205. }
  8206. url = Tools.CleanUrl(url);
  8207. url = Tools.PreprocessUrl(url);
  8208. var img = new Image();
  8209. Tools.SetCorsBehavior(url, img);
  8210. var loadHandler = function () {
  8211. img.removeEventListener("load", loadHandler);
  8212. img.removeEventListener("error", errorHandler);
  8213. onLoad(img);
  8214. };
  8215. var errorHandler = function (err) {
  8216. img.removeEventListener("load", loadHandler);
  8217. img.removeEventListener("error", errorHandler);
  8218. Tools.Error("Error while trying to load image: " + url);
  8219. if (onError) {
  8220. onError("Error while trying to load image: " + url, err);
  8221. }
  8222. };
  8223. img.addEventListener("load", loadHandler);
  8224. img.addEventListener("error", errorHandler);
  8225. var noIndexedDB = function () {
  8226. img.src = url;
  8227. };
  8228. var loadFromIndexedDB = function () {
  8229. if (database) {
  8230. database.loadImageFromDB(url, img);
  8231. }
  8232. };
  8233. //ANY database to do!
  8234. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8235. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8236. }
  8237. else {
  8238. if (url.indexOf("file:") !== -1) {
  8239. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8240. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8241. try {
  8242. var blobURL;
  8243. try {
  8244. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8245. }
  8246. catch (ex) {
  8247. // Chrome doesn't support oneTimeOnly parameter
  8248. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8249. }
  8250. img.src = blobURL;
  8251. }
  8252. catch (e) {
  8253. img.src = "";
  8254. }
  8255. return img;
  8256. }
  8257. }
  8258. noIndexedDB();
  8259. }
  8260. return img;
  8261. };
  8262. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8263. url = Tools.CleanUrl(url);
  8264. url = Tools.PreprocessUrl(url);
  8265. // If file and file input are set
  8266. if (url.indexOf("file:") !== -1) {
  8267. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8268. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8269. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8270. }
  8271. }
  8272. var loadUrl = Tools.BaseUrl + url;
  8273. var aborted = false;
  8274. var fileRequest = {
  8275. onCompleteObservable: new BABYLON.Observable(),
  8276. abort: function () { return aborted = true; },
  8277. };
  8278. var requestFile = function () {
  8279. var request = new XMLHttpRequest();
  8280. var retryHandle = null;
  8281. fileRequest.abort = function () {
  8282. aborted = true;
  8283. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8284. request.abort();
  8285. }
  8286. if (retryHandle !== null) {
  8287. clearTimeout(retryHandle);
  8288. retryHandle = null;
  8289. }
  8290. };
  8291. var retryLoop = function (retryIndex) {
  8292. request.open('GET', loadUrl, true);
  8293. if (useArrayBuffer) {
  8294. request.responseType = "arraybuffer";
  8295. }
  8296. if (onProgress) {
  8297. request.addEventListener("progress", onProgress);
  8298. }
  8299. var onLoadEnd = function () {
  8300. request.removeEventListener("loadend", onLoadEnd);
  8301. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8302. fileRequest.onCompleteObservable.clear();
  8303. };
  8304. request.addEventListener("loadend", onLoadEnd);
  8305. var onReadyStateChange = function () {
  8306. if (aborted) {
  8307. return;
  8308. }
  8309. // In case of undefined state in some browsers.
  8310. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8311. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8312. request.removeEventListener("readystatechange", onReadyStateChange);
  8313. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8314. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8315. return;
  8316. }
  8317. var retryStrategy = Tools.DefaultRetryStrategy;
  8318. if (retryStrategy) {
  8319. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8320. if (waitTime !== -1) {
  8321. // Prevent the request from completing for retry.
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. request = new XMLHttpRequest();
  8324. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8325. return;
  8326. }
  8327. }
  8328. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8329. if (onError) {
  8330. onError(request, e);
  8331. }
  8332. else {
  8333. throw e;
  8334. }
  8335. }
  8336. };
  8337. request.addEventListener("readystatechange", onReadyStateChange);
  8338. request.send();
  8339. };
  8340. retryLoop(0);
  8341. };
  8342. // Caching all files
  8343. if (database && database.enableSceneOffline) {
  8344. var noIndexedDB_1 = function () {
  8345. if (!aborted) {
  8346. requestFile();
  8347. }
  8348. };
  8349. var loadFromIndexedDB = function () {
  8350. // TODO: database needs to support aborting and should return a IFileRequest
  8351. if (aborted) {
  8352. return;
  8353. }
  8354. if (database) {
  8355. database.loadFileFromDB(url, function (data) {
  8356. if (!aborted) {
  8357. onSuccess(data);
  8358. }
  8359. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8360. }, onProgress ? function (event) {
  8361. if (!aborted) {
  8362. onProgress(event);
  8363. }
  8364. } : undefined, noIndexedDB_1, useArrayBuffer);
  8365. }
  8366. };
  8367. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8368. }
  8369. else {
  8370. requestFile();
  8371. }
  8372. return fileRequest;
  8373. };
  8374. /**
  8375. * Load a script (identified by an url). When the url returns, the
  8376. * content of this file is added into a new script element, attached to the DOM (body element)
  8377. */
  8378. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8379. var head = document.getElementsByTagName('head')[0];
  8380. var script = document.createElement('script');
  8381. script.type = 'text/javascript';
  8382. script.src = scriptUrl;
  8383. script.onload = function () {
  8384. if (onSuccess) {
  8385. onSuccess();
  8386. }
  8387. };
  8388. script.onerror = function (e) {
  8389. if (onError) {
  8390. onError("Unable to load script", e);
  8391. }
  8392. };
  8393. head.appendChild(script);
  8394. };
  8395. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8396. var reader = new FileReader();
  8397. var request = {
  8398. onCompleteObservable: new BABYLON.Observable(),
  8399. abort: function () { return reader.abort(); },
  8400. };
  8401. reader.onloadend = function (e) {
  8402. request.onCompleteObservable.notifyObservers(request);
  8403. };
  8404. reader.onload = function (e) {
  8405. //target doesn't have result from ts 1.3
  8406. callback(e.target['result']);
  8407. };
  8408. reader.onprogress = progressCallback;
  8409. reader.readAsDataURL(fileToLoad);
  8410. return request;
  8411. };
  8412. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8413. var reader = new FileReader();
  8414. var request = {
  8415. onCompleteObservable: new BABYLON.Observable(),
  8416. abort: function () { return reader.abort(); },
  8417. };
  8418. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8419. reader.onerror = function (e) {
  8420. Tools.Log("Error while reading file: " + fileToLoad.name);
  8421. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8422. };
  8423. reader.onload = function (e) {
  8424. //target doesn't have result from ts 1.3
  8425. callback(e.target['result']);
  8426. };
  8427. if (progressCallBack) {
  8428. reader.onprogress = progressCallBack;
  8429. }
  8430. if (!useArrayBuffer) {
  8431. // Asynchronous read
  8432. reader.readAsText(fileToLoad);
  8433. }
  8434. else {
  8435. reader.readAsArrayBuffer(fileToLoad);
  8436. }
  8437. return request;
  8438. };
  8439. //returns a downloadable url to a file content.
  8440. Tools.FileAsURL = function (content) {
  8441. var fileBlob = new Blob([content]);
  8442. var url = window.URL || window.webkitURL;
  8443. var link = url.createObjectURL(fileBlob);
  8444. return link;
  8445. };
  8446. // Misc.
  8447. Tools.Format = function (value, decimals) {
  8448. if (decimals === void 0) { decimals = 2; }
  8449. return value.toFixed(decimals);
  8450. };
  8451. Tools.CheckExtends = function (v, min, max) {
  8452. if (v.x < min.x)
  8453. min.x = v.x;
  8454. if (v.y < min.y)
  8455. min.y = v.y;
  8456. if (v.z < min.z)
  8457. min.z = v.z;
  8458. if (v.x > max.x)
  8459. max.x = v.x;
  8460. if (v.y > max.y)
  8461. max.y = v.y;
  8462. if (v.z > max.z)
  8463. max.z = v.z;
  8464. };
  8465. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8466. for (var prop in source) {
  8467. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8468. continue;
  8469. }
  8470. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8471. continue;
  8472. }
  8473. var sourceValue = source[prop];
  8474. var typeOfSourceValue = typeof sourceValue;
  8475. if (typeOfSourceValue === "function") {
  8476. continue;
  8477. }
  8478. if (typeOfSourceValue === "object") {
  8479. if (sourceValue instanceof Array) {
  8480. destination[prop] = [];
  8481. if (sourceValue.length > 0) {
  8482. if (typeof sourceValue[0] == "object") {
  8483. for (var index = 0; index < sourceValue.length; index++) {
  8484. var clonedValue = cloneValue(sourceValue[index], destination);
  8485. if (destination[prop].indexOf(clonedValue) === -1) {
  8486. destination[prop].push(clonedValue);
  8487. }
  8488. }
  8489. }
  8490. else {
  8491. destination[prop] = sourceValue.slice(0);
  8492. }
  8493. }
  8494. }
  8495. else {
  8496. destination[prop] = cloneValue(sourceValue, destination);
  8497. }
  8498. }
  8499. else {
  8500. destination[prop] = sourceValue;
  8501. }
  8502. }
  8503. };
  8504. Tools.IsEmpty = function (obj) {
  8505. for (var i in obj) {
  8506. if (obj.hasOwnProperty(i)) {
  8507. return false;
  8508. }
  8509. }
  8510. return true;
  8511. };
  8512. Tools.RegisterTopRootEvents = function (events) {
  8513. for (var index = 0; index < events.length; index++) {
  8514. var event = events[index];
  8515. window.addEventListener(event.name, event.handler, false);
  8516. try {
  8517. if (window.parent) {
  8518. window.parent.addEventListener(event.name, event.handler, false);
  8519. }
  8520. }
  8521. catch (e) {
  8522. // Silently fails...
  8523. }
  8524. }
  8525. };
  8526. Tools.UnregisterTopRootEvents = function (events) {
  8527. for (var index = 0; index < events.length; index++) {
  8528. var event = events[index];
  8529. window.removeEventListener(event.name, event.handler);
  8530. try {
  8531. if (window.parent) {
  8532. window.parent.removeEventListener(event.name, event.handler);
  8533. }
  8534. }
  8535. catch (e) {
  8536. // Silently fails...
  8537. }
  8538. }
  8539. };
  8540. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. // Read the contents of the framebuffer
  8543. var numberOfChannelsByLine = width * 4;
  8544. var halfHeight = height / 2;
  8545. //Reading datas from WebGL
  8546. var data = engine.readPixels(0, 0, width, height);
  8547. //To flip image on Y axis.
  8548. for (var i = 0; i < halfHeight; i++) {
  8549. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8550. var currentCell = j + i * numberOfChannelsByLine;
  8551. var targetLine = height - i - 1;
  8552. var targetCell = j + targetLine * numberOfChannelsByLine;
  8553. var temp = data[currentCell];
  8554. data[currentCell] = data[targetCell];
  8555. data[targetCell] = temp;
  8556. }
  8557. }
  8558. // Create a 2D canvas to store the result
  8559. if (!screenshotCanvas) {
  8560. screenshotCanvas = document.createElement('canvas');
  8561. }
  8562. screenshotCanvas.width = width;
  8563. screenshotCanvas.height = height;
  8564. var context = screenshotCanvas.getContext('2d');
  8565. if (context) {
  8566. // Copy the pixels to a 2D canvas
  8567. var imageData = context.createImageData(width, height);
  8568. var castData = (imageData.data);
  8569. castData.set(data);
  8570. context.putImageData(imageData, 0, 0);
  8571. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8572. }
  8573. };
  8574. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8575. if (mimeType === void 0) { mimeType = "image/png"; }
  8576. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8577. if (successCallback) {
  8578. successCallback(base64Image);
  8579. }
  8580. else {
  8581. // We need HTMLCanvasElement.toBlob for HD screenshots
  8582. if (!screenshotCanvas.toBlob) {
  8583. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8584. screenshotCanvas.toBlob = function (callback, type, quality) {
  8585. var _this = this;
  8586. setTimeout(function () {
  8587. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8588. for (var i = 0; i < len; i++) {
  8589. arr[i] = binStr.charCodeAt(i);
  8590. }
  8591. callback(new Blob([arr], { type: type || 'image/png' }));
  8592. });
  8593. };
  8594. }
  8595. screenshotCanvas.toBlob(function (blob) {
  8596. var url = URL.createObjectURL(blob);
  8597. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8598. if (("download" in document.createElement("a"))) {
  8599. var a = window.document.createElement("a");
  8600. a.href = url;
  8601. if (fileName) {
  8602. a.setAttribute("download", fileName);
  8603. }
  8604. else {
  8605. var date = new Date();
  8606. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8607. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8608. }
  8609. window.document.body.appendChild(a);
  8610. a.addEventListener("click", function () {
  8611. if (a.parentElement) {
  8612. a.parentElement.removeChild(a);
  8613. }
  8614. });
  8615. a.click();
  8616. }
  8617. else {
  8618. var newWindow = window.open("");
  8619. if (!newWindow)
  8620. return;
  8621. var img = newWindow.document.createElement("img");
  8622. img.onload = function () {
  8623. // no longer need to read the blob so it's revoked
  8624. URL.revokeObjectURL(url);
  8625. };
  8626. img.src = url;
  8627. newWindow.document.body.appendChild(img);
  8628. }
  8629. });
  8630. }
  8631. };
  8632. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8633. if (mimeType === void 0) { mimeType = "image/png"; }
  8634. var width;
  8635. var height;
  8636. // If a precision value is specified
  8637. if (size.precision) {
  8638. width = Math.round(engine.getRenderWidth() * size.precision);
  8639. height = Math.round(width / engine.getAspectRatio(camera));
  8640. }
  8641. else if (size.width && size.height) {
  8642. width = size.width;
  8643. height = size.height;
  8644. }
  8645. else if (size.width && !size.height) {
  8646. width = size.width;
  8647. height = Math.round(width / engine.getAspectRatio(camera));
  8648. }
  8649. else if (size.height && !size.width) {
  8650. height = size.height;
  8651. width = Math.round(height * engine.getAspectRatio(camera));
  8652. }
  8653. else if (!isNaN(size)) {
  8654. height = size;
  8655. width = size;
  8656. }
  8657. else {
  8658. Tools.Error("Invalid 'size' parameter !");
  8659. return;
  8660. }
  8661. if (!screenshotCanvas) {
  8662. screenshotCanvas = document.createElement('canvas');
  8663. }
  8664. screenshotCanvas.width = width;
  8665. screenshotCanvas.height = height;
  8666. var renderContext = screenshotCanvas.getContext("2d");
  8667. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8668. var newWidth = width;
  8669. var newHeight = newWidth / ratio;
  8670. if (newHeight > height) {
  8671. newHeight = height;
  8672. newWidth = newHeight * ratio;
  8673. }
  8674. var offsetX = Math.max(0, width - newWidth) / 2;
  8675. var offsetY = Math.max(0, height - newHeight) / 2;
  8676. var renderingCanvas = engine.getRenderingCanvas();
  8677. if (renderContext && renderingCanvas) {
  8678. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8679. }
  8680. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8681. };
  8682. /**
  8683. * Generates an image screenshot from the specified camera.
  8684. *
  8685. * @param engine The engine to use for rendering
  8686. * @param camera The camera to use for rendering
  8687. * @param size This parameter can be set to a single number or to an object with the
  8688. * following (optional) properties: precision, width, height. If a single number is passed,
  8689. * it will be used for both width and height. If an object is passed, the screenshot size
  8690. * will be derived from the parameters. The precision property is a multiplier allowing
  8691. * rendering at a higher or lower resolution.
  8692. * @param successCallback The callback receives a single parameter which contains the
  8693. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8694. * src parameter of an <img> to display it.
  8695. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8696. * Check your browser for supported MIME types.
  8697. * @param samples Texture samples (default: 1)
  8698. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8699. * @param fileName A name for for the downloaded file.
  8700. * @constructor
  8701. */
  8702. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8703. if (mimeType === void 0) { mimeType = "image/png"; }
  8704. if (samples === void 0) { samples = 1; }
  8705. if (antialiasing === void 0) { antialiasing = false; }
  8706. var width;
  8707. var height;
  8708. //If a precision value is specified
  8709. if (size.precision) {
  8710. width = Math.round(engine.getRenderWidth() * size.precision);
  8711. height = Math.round(width / engine.getAspectRatio(camera));
  8712. size = { width: width, height: height };
  8713. }
  8714. else if (size.width && size.height) {
  8715. width = size.width;
  8716. height = size.height;
  8717. }
  8718. else if (size.width && !size.height) {
  8719. width = size.width;
  8720. height = Math.round(width / engine.getAspectRatio(camera));
  8721. size = { width: width, height: height };
  8722. }
  8723. else if (size.height && !size.width) {
  8724. height = size.height;
  8725. width = Math.round(height * engine.getAspectRatio(camera));
  8726. size = { width: width, height: height };
  8727. }
  8728. else if (!isNaN(size)) {
  8729. height = size;
  8730. width = size;
  8731. }
  8732. else {
  8733. Tools.Error("Invalid 'size' parameter !");
  8734. return;
  8735. }
  8736. var scene = camera.getScene();
  8737. var previousCamera = null;
  8738. if (scene.activeCamera !== camera) {
  8739. previousCamera = scene.activeCamera;
  8740. scene.activeCamera = camera;
  8741. }
  8742. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8743. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8744. texture.renderList = null;
  8745. texture.samples = samples;
  8746. if (antialiasing) {
  8747. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8748. }
  8749. texture.onAfterRenderObservable.add(function () {
  8750. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8751. });
  8752. scene.incrementRenderId();
  8753. scene.resetCachedMaterial();
  8754. texture.render(true);
  8755. texture.dispose();
  8756. if (previousCamera) {
  8757. scene.activeCamera = previousCamera;
  8758. }
  8759. camera.getProjectionMatrix(true); // Force cache refresh;
  8760. };
  8761. // XHR response validator for local file scenario
  8762. Tools.ValidateXHRData = function (xhr, dataType) {
  8763. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8764. if (dataType === void 0) { dataType = 7; }
  8765. try {
  8766. if (dataType & 1) {
  8767. if (xhr.responseText && xhr.responseText.length > 0) {
  8768. return true;
  8769. }
  8770. else if (dataType === 1) {
  8771. return false;
  8772. }
  8773. }
  8774. if (dataType & 2) {
  8775. // Check header width and height since there is no "TGA" magic number
  8776. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8777. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8778. return true;
  8779. }
  8780. else if (dataType === 2) {
  8781. return false;
  8782. }
  8783. }
  8784. if (dataType & 4) {
  8785. // Check for the "DDS" magic number
  8786. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8787. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8788. return true;
  8789. }
  8790. else {
  8791. return false;
  8792. }
  8793. }
  8794. }
  8795. catch (e) {
  8796. // Global protection
  8797. }
  8798. return false;
  8799. };
  8800. /**
  8801. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8802. * Be aware Math.random() could cause collisions, but:
  8803. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  8804. */
  8805. Tools.RandomId = function () {
  8806. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8807. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8808. return v.toString(16);
  8809. });
  8810. };
  8811. /**
  8812. * Test if the given uri is a base64 string.
  8813. * @param uri The uri to test
  8814. * @return True if the uri is a base64 string or false otherwise.
  8815. */
  8816. Tools.IsBase64 = function (uri) {
  8817. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8818. };
  8819. /**
  8820. * Decode the given base64 uri.
  8821. * @param uri The uri to decode
  8822. * @return The decoded base64 data.
  8823. */
  8824. Tools.DecodeBase64 = function (uri) {
  8825. var decodedString = atob(uri.split(",")[1]);
  8826. var bufferLength = decodedString.length;
  8827. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8828. for (var i = 0; i < bufferLength; i++) {
  8829. bufferView[i] = decodedString.charCodeAt(i);
  8830. }
  8831. return bufferView.buffer;
  8832. };
  8833. Object.defineProperty(Tools, "NoneLogLevel", {
  8834. get: function () {
  8835. return Tools._NoneLogLevel;
  8836. },
  8837. enumerable: true,
  8838. configurable: true
  8839. });
  8840. Object.defineProperty(Tools, "MessageLogLevel", {
  8841. get: function () {
  8842. return Tools._MessageLogLevel;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Tools, "WarningLogLevel", {
  8848. get: function () {
  8849. return Tools._WarningLogLevel;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(Tools, "ErrorLogLevel", {
  8855. get: function () {
  8856. return Tools._ErrorLogLevel;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(Tools, "AllLogLevel", {
  8862. get: function () {
  8863. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8864. },
  8865. enumerable: true,
  8866. configurable: true
  8867. });
  8868. Tools._AddLogEntry = function (entry) {
  8869. Tools._LogCache = entry + Tools._LogCache;
  8870. if (Tools.OnNewCacheEntry) {
  8871. Tools.OnNewCacheEntry(entry);
  8872. }
  8873. };
  8874. Tools._FormatMessage = function (message) {
  8875. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8876. var date = new Date();
  8877. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8878. };
  8879. Tools._LogDisabled = function (message) {
  8880. // nothing to do
  8881. };
  8882. Tools._LogEnabled = function (message) {
  8883. var formattedMessage = Tools._FormatMessage(message);
  8884. console.log("BJS - " + formattedMessage);
  8885. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8886. Tools._AddLogEntry(entry);
  8887. };
  8888. Tools._WarnDisabled = function (message) {
  8889. // nothing to do
  8890. };
  8891. Tools._WarnEnabled = function (message) {
  8892. var formattedMessage = Tools._FormatMessage(message);
  8893. console.warn("BJS - " + formattedMessage);
  8894. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8895. Tools._AddLogEntry(entry);
  8896. };
  8897. Tools._ErrorDisabled = function (message) {
  8898. // nothing to do
  8899. };
  8900. Tools._ErrorEnabled = function (message) {
  8901. Tools.errorsCount++;
  8902. var formattedMessage = Tools._FormatMessage(message);
  8903. console.error("BJS - " + formattedMessage);
  8904. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8905. Tools._AddLogEntry(entry);
  8906. };
  8907. Object.defineProperty(Tools, "LogCache", {
  8908. get: function () {
  8909. return Tools._LogCache;
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Tools.ClearLogCache = function () {
  8915. Tools._LogCache = "";
  8916. Tools.errorsCount = 0;
  8917. };
  8918. Object.defineProperty(Tools, "LogLevels", {
  8919. set: function (level) {
  8920. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8921. Tools.Log = Tools._LogEnabled;
  8922. }
  8923. else {
  8924. Tools.Log = Tools._LogDisabled;
  8925. }
  8926. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8927. Tools.Warn = Tools._WarnEnabled;
  8928. }
  8929. else {
  8930. Tools.Warn = Tools._WarnDisabled;
  8931. }
  8932. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8933. Tools.Error = Tools._ErrorEnabled;
  8934. }
  8935. else {
  8936. Tools.Error = Tools._ErrorDisabled;
  8937. }
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Tools.IsWindowObjectExist = function () {
  8943. return (typeof window) !== "undefined";
  8944. };
  8945. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8946. get: function () {
  8947. return Tools._PerformanceNoneLogLevel;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8953. get: function () {
  8954. return Tools._PerformanceUserMarkLogLevel;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8960. get: function () {
  8961. return Tools._PerformanceConsoleLogLevel;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8967. set: function (level) {
  8968. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8969. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8970. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8971. return;
  8972. }
  8973. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8974. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8975. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8976. return;
  8977. }
  8978. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8979. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8985. };
  8986. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8987. };
  8988. Tools._StartUserMark = function (counterName, condition) {
  8989. if (condition === void 0) { condition = true; }
  8990. if (!Tools._performance) {
  8991. if (!Tools.IsWindowObjectExist()) {
  8992. return;
  8993. }
  8994. Tools._performance = window.performance;
  8995. }
  8996. if (!condition || !Tools._performance.mark) {
  8997. return;
  8998. }
  8999. Tools._performance.mark(counterName + "-Begin");
  9000. };
  9001. Tools._EndUserMark = function (counterName, condition) {
  9002. if (condition === void 0) { condition = true; }
  9003. if (!condition || !Tools._performance.mark) {
  9004. return;
  9005. }
  9006. Tools._performance.mark(counterName + "-End");
  9007. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9008. };
  9009. Tools._StartPerformanceConsole = function (counterName, condition) {
  9010. if (condition === void 0) { condition = true; }
  9011. if (!condition) {
  9012. return;
  9013. }
  9014. Tools._StartUserMark(counterName, condition);
  9015. if (console.time) {
  9016. console.time(counterName);
  9017. }
  9018. };
  9019. Tools._EndPerformanceConsole = function (counterName, condition) {
  9020. if (condition === void 0) { condition = true; }
  9021. if (!condition) {
  9022. return;
  9023. }
  9024. Tools._EndUserMark(counterName, condition);
  9025. if (console.time) {
  9026. console.timeEnd(counterName);
  9027. }
  9028. };
  9029. Object.defineProperty(Tools, "Now", {
  9030. get: function () {
  9031. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9032. return window.performance.now();
  9033. }
  9034. return new Date().getTime();
  9035. },
  9036. enumerable: true,
  9037. configurable: true
  9038. });
  9039. /**
  9040. * This method will return the name of the class used to create the instance of the given object.
  9041. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9042. * @param object the object to get the class name from
  9043. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9044. */
  9045. Tools.GetClassName = function (object, isType) {
  9046. if (isType === void 0) { isType = false; }
  9047. var name = null;
  9048. if (!isType && object.getClassName) {
  9049. name = object.getClassName();
  9050. }
  9051. else {
  9052. if (object instanceof Object) {
  9053. var classObj = isType ? object : Object.getPrototypeOf(object);
  9054. name = classObj.constructor["__bjsclassName__"];
  9055. }
  9056. if (!name) {
  9057. name = typeof object;
  9058. }
  9059. }
  9060. return name;
  9061. };
  9062. Tools.First = function (array, predicate) {
  9063. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9064. var el = array_1[_i];
  9065. if (predicate(el)) {
  9066. return el;
  9067. }
  9068. }
  9069. return null;
  9070. };
  9071. /**
  9072. * This method will return the name of the full name of the class, including its owning module (if any).
  9073. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9074. * @param object the object to get the class name from
  9075. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9076. */
  9077. Tools.getFullClassName = function (object, isType) {
  9078. if (isType === void 0) { isType = false; }
  9079. var className = null;
  9080. var moduleName = null;
  9081. if (!isType && object.getClassName) {
  9082. className = object.getClassName();
  9083. }
  9084. else {
  9085. if (object instanceof Object) {
  9086. var classObj = isType ? object : Object.getPrototypeOf(object);
  9087. className = classObj.constructor["__bjsclassName__"];
  9088. moduleName = classObj.constructor["__bjsmoduleName__"];
  9089. }
  9090. if (!className) {
  9091. className = typeof object;
  9092. }
  9093. }
  9094. if (!className) {
  9095. return null;
  9096. }
  9097. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9098. };
  9099. /**
  9100. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9101. * @param array
  9102. */
  9103. Tools.arrayOrStringFeeder = function (array) {
  9104. return function (index) {
  9105. if (index >= array.length) {
  9106. return null;
  9107. }
  9108. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9109. if (val && val.getHashCode) {
  9110. val = val.getHashCode();
  9111. }
  9112. if (typeof val === "string") {
  9113. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9114. }
  9115. return val;
  9116. };
  9117. };
  9118. /**
  9119. * Compute the hashCode of a stream of number
  9120. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9121. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9122. * @return the hash code computed
  9123. */
  9124. Tools.hashCodeFromStream = function (feeder) {
  9125. // Based from here: http://stackoverflow.com/a/7616484/802124
  9126. var hash = 0;
  9127. var index = 0;
  9128. var chr = feeder(index++);
  9129. while (chr != null) {
  9130. hash = ((hash << 5) - hash) + chr;
  9131. hash |= 0; // Convert to 32bit integer
  9132. chr = feeder(index++);
  9133. }
  9134. return hash;
  9135. };
  9136. /**
  9137. * Returns a promise that resolves after the given amount of time.
  9138. * @param delay Number of milliseconds to delay
  9139. * @returns Promise that resolves after the given amount of time
  9140. */
  9141. Tools.DelayAsync = function (delay) {
  9142. return new Promise(function (resolve) {
  9143. setTimeout(function () {
  9144. resolve();
  9145. }, delay);
  9146. });
  9147. };
  9148. Tools.BaseUrl = "";
  9149. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9150. /**
  9151. * Default behaviour for cors in the application.
  9152. * It can be a string if the expected behavior is identical in the entire app.
  9153. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9154. */
  9155. Tools.CorsBehavior = "anonymous";
  9156. Tools.UseFallbackTexture = true;
  9157. /**
  9158. * Use this object to register external classes like custom textures or material
  9159. * to allow the laoders to instantiate them
  9160. */
  9161. Tools.RegisteredExternalClasses = {};
  9162. // Used in case of a texture loading problem
  9163. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9164. Tools.PreprocessUrl = function (url) {
  9165. return url;
  9166. };
  9167. // Logs
  9168. Tools._NoneLogLevel = 0;
  9169. Tools._MessageLogLevel = 1;
  9170. Tools._WarningLogLevel = 2;
  9171. Tools._ErrorLogLevel = 4;
  9172. Tools._LogCache = "";
  9173. Tools.errorsCount = 0;
  9174. Tools.Log = Tools._LogEnabled;
  9175. Tools.Warn = Tools._WarnEnabled;
  9176. Tools.Error = Tools._ErrorEnabled;
  9177. // Performances
  9178. Tools._PerformanceNoneLogLevel = 0;
  9179. Tools._PerformanceUserMarkLogLevel = 1;
  9180. Tools._PerformanceConsoleLogLevel = 2;
  9181. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9182. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9183. return Tools;
  9184. }());
  9185. BABYLON.Tools = Tools;
  9186. /**
  9187. * This class is used to track a performance counter which is number based.
  9188. * The user has access to many properties which give statistics of different nature
  9189. *
  9190. * The implementer can track two kinds of Performance Counter: time and count
  9191. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9192. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9193. */
  9194. var PerfCounter = /** @class */ (function () {
  9195. function PerfCounter() {
  9196. this._startMonitoringTime = 0;
  9197. this._min = 0;
  9198. this._max = 0;
  9199. this._average = 0;
  9200. this._lastSecAverage = 0;
  9201. this._current = 0;
  9202. this._totalValueCount = 0;
  9203. this._totalAccumulated = 0;
  9204. this._lastSecAccumulated = 0;
  9205. this._lastSecTime = 0;
  9206. this._lastSecValueCount = 0;
  9207. }
  9208. Object.defineProperty(PerfCounter.prototype, "min", {
  9209. /**
  9210. * Returns the smallest value ever
  9211. */
  9212. get: function () {
  9213. return this._min;
  9214. },
  9215. enumerable: true,
  9216. configurable: true
  9217. });
  9218. Object.defineProperty(PerfCounter.prototype, "max", {
  9219. /**
  9220. * Returns the biggest value ever
  9221. */
  9222. get: function () {
  9223. return this._max;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(PerfCounter.prototype, "average", {
  9229. /**
  9230. * Returns the average value since the performance counter is running
  9231. */
  9232. get: function () {
  9233. return this._average;
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9239. /**
  9240. * Returns the average value of the last second the counter was monitored
  9241. */
  9242. get: function () {
  9243. return this._lastSecAverage;
  9244. },
  9245. enumerable: true,
  9246. configurable: true
  9247. });
  9248. Object.defineProperty(PerfCounter.prototype, "current", {
  9249. /**
  9250. * Returns the current value
  9251. */
  9252. get: function () {
  9253. return this._current;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(PerfCounter.prototype, "total", {
  9259. get: function () {
  9260. return this._totalAccumulated;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "count", {
  9266. get: function () {
  9267. return this._totalValueCount;
  9268. },
  9269. enumerable: true,
  9270. configurable: true
  9271. });
  9272. /**
  9273. * Call this method to start monitoring a new frame.
  9274. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9275. */
  9276. PerfCounter.prototype.fetchNewFrame = function () {
  9277. this._totalValueCount++;
  9278. this._current = 0;
  9279. this._lastSecValueCount++;
  9280. };
  9281. /**
  9282. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9283. * @param newCount the count value to add to the monitored count
  9284. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9285. */
  9286. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9287. if (!PerfCounter.Enabled) {
  9288. return;
  9289. }
  9290. this._current += newCount;
  9291. if (fetchResult) {
  9292. this._fetchResult();
  9293. }
  9294. };
  9295. /**
  9296. * Start monitoring this performance counter
  9297. */
  9298. PerfCounter.prototype.beginMonitoring = function () {
  9299. if (!PerfCounter.Enabled) {
  9300. return;
  9301. }
  9302. this._startMonitoringTime = Tools.Now;
  9303. };
  9304. /**
  9305. * Compute the time lapsed since the previous beginMonitoring() call.
  9306. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9307. */
  9308. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9309. if (newFrame === void 0) { newFrame = true; }
  9310. if (!PerfCounter.Enabled) {
  9311. return;
  9312. }
  9313. if (newFrame) {
  9314. this.fetchNewFrame();
  9315. }
  9316. var currentTime = Tools.Now;
  9317. this._current = currentTime - this._startMonitoringTime;
  9318. if (newFrame) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. PerfCounter.prototype._fetchResult = function () {
  9323. this._totalAccumulated += this._current;
  9324. this._lastSecAccumulated += this._current;
  9325. // Min/Max update
  9326. this._min = Math.min(this._min, this._current);
  9327. this._max = Math.max(this._max, this._current);
  9328. this._average = this._totalAccumulated / this._totalValueCount;
  9329. // Reset last sec?
  9330. var now = Tools.Now;
  9331. if ((now - this._lastSecTime) > 1000) {
  9332. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9333. this._lastSecTime = now;
  9334. this._lastSecAccumulated = 0;
  9335. this._lastSecValueCount = 0;
  9336. }
  9337. };
  9338. PerfCounter.Enabled = true;
  9339. return PerfCounter;
  9340. }());
  9341. BABYLON.PerfCounter = PerfCounter;
  9342. /**
  9343. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9344. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9345. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9346. * @param name The name of the class, case should be preserved
  9347. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9348. */
  9349. function className(name, module) {
  9350. return function (target) {
  9351. target["__bjsclassName__"] = name;
  9352. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9353. };
  9354. }
  9355. BABYLON.className = className;
  9356. /**
  9357. * An implementation of a loop for asynchronous functions.
  9358. */
  9359. var AsyncLoop = /** @class */ (function () {
  9360. /**
  9361. * Constroctor.
  9362. * @param iterations the number of iterations.
  9363. * @param _fn the function to run each iteration
  9364. * @param _successCallback the callback that will be called upon succesful execution
  9365. * @param offset starting offset.
  9366. */
  9367. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. this.iterations = iterations;
  9370. this._fn = _fn;
  9371. this._successCallback = _successCallback;
  9372. this.index = offset - 1;
  9373. this._done = false;
  9374. }
  9375. /**
  9376. * Execute the next iteration. Must be called after the last iteration was finished.
  9377. */
  9378. AsyncLoop.prototype.executeNext = function () {
  9379. if (!this._done) {
  9380. if (this.index + 1 < this.iterations) {
  9381. ++this.index;
  9382. this._fn(this);
  9383. }
  9384. else {
  9385. this.breakLoop();
  9386. }
  9387. }
  9388. };
  9389. /**
  9390. * Break the loop and run the success callback.
  9391. */
  9392. AsyncLoop.prototype.breakLoop = function () {
  9393. this._done = true;
  9394. this._successCallback();
  9395. };
  9396. /**
  9397. * Helper function
  9398. */
  9399. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9400. if (offset === void 0) { offset = 0; }
  9401. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9402. loop.executeNext();
  9403. return loop;
  9404. };
  9405. /**
  9406. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9407. * @param iterations total number of iterations
  9408. * @param syncedIterations number of synchronous iterations in each async iteration.
  9409. * @param fn the function to call each iteration.
  9410. * @param callback a success call back that will be called when iterating stops.
  9411. * @param breakFunction a break condition (optional)
  9412. * @param timeout timeout settings for the setTimeout function. default - 0.
  9413. * @constructor
  9414. */
  9415. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9416. if (timeout === void 0) { timeout = 0; }
  9417. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9418. if (breakFunction && breakFunction())
  9419. loop.breakLoop();
  9420. else {
  9421. setTimeout(function () {
  9422. for (var i = 0; i < syncedIterations; ++i) {
  9423. var iteration = (loop.index * syncedIterations) + i;
  9424. if (iteration >= iterations)
  9425. break;
  9426. fn(iteration);
  9427. if (breakFunction && breakFunction()) {
  9428. loop.breakLoop();
  9429. break;
  9430. }
  9431. }
  9432. loop.executeNext();
  9433. }, timeout);
  9434. }
  9435. }, callback);
  9436. };
  9437. return AsyncLoop;
  9438. }());
  9439. BABYLON.AsyncLoop = AsyncLoop;
  9440. })(BABYLON || (BABYLON = {}));
  9441. //# sourceMappingURL=babylon.tools.js.map
  9442. var BABYLON;
  9443. (function (BABYLON) {
  9444. var PromiseStates;
  9445. (function (PromiseStates) {
  9446. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9447. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9448. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9449. })(PromiseStates || (PromiseStates = {}));
  9450. var FulFillmentAgregator = /** @class */ (function () {
  9451. function FulFillmentAgregator() {
  9452. this.count = 0;
  9453. this.target = 0;
  9454. this.results = [];
  9455. }
  9456. return FulFillmentAgregator;
  9457. }());
  9458. var InternalPromise = /** @class */ (function () {
  9459. function InternalPromise(resolver) {
  9460. var _this = this;
  9461. this._state = PromiseStates.Pending;
  9462. this._children = new Array();
  9463. this._rejectWasConsumed = false;
  9464. if (!resolver) {
  9465. return;
  9466. }
  9467. try {
  9468. resolver(function (value) {
  9469. _this._resolve(value);
  9470. }, function (reason) {
  9471. _this._reject(reason);
  9472. });
  9473. }
  9474. catch (e) {
  9475. this._reject(e);
  9476. }
  9477. }
  9478. InternalPromise.prototype.catch = function (onRejected) {
  9479. return this.then(undefined, onRejected);
  9480. };
  9481. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9482. var _this = this;
  9483. var newPromise = new InternalPromise();
  9484. newPromise._onFulfilled = onFulfilled;
  9485. newPromise._onRejected = onRejected;
  9486. // Composition
  9487. this._children.push(newPromise);
  9488. if (this._state !== PromiseStates.Pending) {
  9489. BABYLON.Tools.SetImmediate(function () {
  9490. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9491. var returnedValue = newPromise._resolve(_this._result);
  9492. if (returnedValue !== undefined && returnedValue !== null) {
  9493. if (returnedValue._state !== undefined) {
  9494. var returnedPromise = returnedValue;
  9495. newPromise._children.push(returnedPromise);
  9496. newPromise = returnedPromise;
  9497. }
  9498. else {
  9499. newPromise._result = returnedValue;
  9500. }
  9501. }
  9502. }
  9503. else {
  9504. newPromise._reject(_this._reason);
  9505. }
  9506. });
  9507. }
  9508. return newPromise;
  9509. };
  9510. InternalPromise.prototype._moveChildren = function (children) {
  9511. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9512. if (this._state === PromiseStates.Fulfilled) {
  9513. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9514. var child = _b[_i];
  9515. child._resolve(this._result);
  9516. }
  9517. }
  9518. else if (this._state === PromiseStates.Rejected) {
  9519. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9520. var child = _d[_c];
  9521. child._reject(this._reason);
  9522. }
  9523. }
  9524. var _a;
  9525. };
  9526. InternalPromise.prototype._resolve = function (value) {
  9527. try {
  9528. this._state = PromiseStates.Fulfilled;
  9529. this._result = value;
  9530. var returnedValue = null;
  9531. if (this._onFulfilled) {
  9532. returnedValue = this._onFulfilled(value);
  9533. }
  9534. if (returnedValue !== undefined && returnedValue !== null) {
  9535. if (returnedValue._state !== undefined) {
  9536. // Transmit children
  9537. var returnedPromise = returnedValue;
  9538. returnedPromise._moveChildren(this._children);
  9539. }
  9540. else {
  9541. value = returnedValue;
  9542. }
  9543. }
  9544. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9545. var child = _a[_i];
  9546. child._resolve(value);
  9547. }
  9548. this._children.length = 0;
  9549. delete this._onFulfilled;
  9550. delete this._onRejected;
  9551. return returnedValue;
  9552. }
  9553. catch (e) {
  9554. this._reject(e, true);
  9555. }
  9556. return null;
  9557. };
  9558. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9559. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9560. this._state = PromiseStates.Rejected;
  9561. this._reason = reason;
  9562. if (this._onRejected && !onLocalThrow) {
  9563. try {
  9564. this._onRejected(reason);
  9565. this._rejectWasConsumed = true;
  9566. }
  9567. catch (e) {
  9568. reason = e;
  9569. }
  9570. }
  9571. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9572. var child = _a[_i];
  9573. if (this._rejectWasConsumed) {
  9574. child._resolve(null);
  9575. }
  9576. else {
  9577. child._reject(reason);
  9578. }
  9579. }
  9580. this._children.length = 0;
  9581. delete this._onFulfilled;
  9582. delete this._onRejected;
  9583. };
  9584. InternalPromise.resolve = function (value) {
  9585. var newPromise = new InternalPromise();
  9586. newPromise._resolve(value);
  9587. return newPromise;
  9588. };
  9589. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9590. promise.then(function (value) {
  9591. agregator.results[index] = value;
  9592. agregator.count++;
  9593. if (agregator.count === agregator.target) {
  9594. agregator.rootPromise._resolve(agregator.results);
  9595. }
  9596. return null;
  9597. }, function (reason) {
  9598. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9599. agregator.rootPromise._reject(reason);
  9600. }
  9601. });
  9602. };
  9603. InternalPromise.all = function (promises) {
  9604. var newPromise = new InternalPromise();
  9605. var agregator = new FulFillmentAgregator();
  9606. agregator.target = promises.length;
  9607. agregator.rootPromise = newPromise;
  9608. if (promises.length) {
  9609. for (var index = 0; index < promises.length; index++) {
  9610. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9611. }
  9612. }
  9613. else {
  9614. newPromise._resolve([]);
  9615. }
  9616. return newPromise;
  9617. };
  9618. InternalPromise.race = function (promises) {
  9619. var newPromise = new InternalPromise();
  9620. if (promises.length) {
  9621. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9622. var promise = promises_1[_i];
  9623. promise.then(function (value) {
  9624. if (newPromise) {
  9625. newPromise._resolve(value);
  9626. newPromise = null;
  9627. }
  9628. return null;
  9629. }, function (reason) {
  9630. if (newPromise) {
  9631. newPromise._reject(reason);
  9632. newPromise = null;
  9633. }
  9634. });
  9635. }
  9636. }
  9637. return newPromise;
  9638. };
  9639. return InternalPromise;
  9640. }());
  9641. /**
  9642. * Helper class that provides a small promise polyfill
  9643. */
  9644. var PromisePolyfill = /** @class */ (function () {
  9645. function PromisePolyfill() {
  9646. }
  9647. /**
  9648. * Static function used to check if the polyfill is required
  9649. * If this is the case then the function will inject the polyfill to window.Promise
  9650. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9651. */
  9652. PromisePolyfill.Apply = function (force) {
  9653. if (force === void 0) { force = false; }
  9654. if (force || typeof Promise === 'undefined') {
  9655. var root = window;
  9656. root.Promise = InternalPromise;
  9657. }
  9658. };
  9659. return PromisePolyfill;
  9660. }());
  9661. BABYLON.PromisePolyfill = PromisePolyfill;
  9662. })(BABYLON || (BABYLON = {}));
  9663. //# sourceMappingURL=babylon.promise.js.map
  9664. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9665. var BABYLON;
  9666. (function (BABYLON) {
  9667. /**
  9668. * Helper class to push actions to a pool of workers.
  9669. */
  9670. var WorkerPool = /** @class */ (function () {
  9671. /**
  9672. * Constructor
  9673. * @param workers Array of workers to use for actions
  9674. */
  9675. function WorkerPool(workers) {
  9676. this._pendingActions = new Array();
  9677. this._workerInfos = workers.map(function (worker) { return ({
  9678. worker: worker,
  9679. active: false
  9680. }); });
  9681. }
  9682. /**
  9683. * Terminates all workers and clears any pending actions.
  9684. */
  9685. WorkerPool.prototype.dispose = function () {
  9686. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9687. var workerInfo = _a[_i];
  9688. workerInfo.worker.terminate();
  9689. }
  9690. delete this._workerInfos;
  9691. delete this._pendingActions;
  9692. };
  9693. /**
  9694. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9695. * pended until a worker has completed its action.
  9696. * @param action The action to perform. Call onComplete when the action is complete.
  9697. */
  9698. WorkerPool.prototype.push = function (action) {
  9699. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9700. var workerInfo = _a[_i];
  9701. if (!workerInfo.active) {
  9702. this._execute(workerInfo, action);
  9703. return;
  9704. }
  9705. }
  9706. this._pendingActions.push(action);
  9707. };
  9708. WorkerPool.prototype._execute = function (workerInfo, action) {
  9709. var _this = this;
  9710. workerInfo.active = true;
  9711. action(workerInfo.worker, function () {
  9712. workerInfo.active = false;
  9713. var nextAction = _this._pendingActions.shift();
  9714. if (nextAction) {
  9715. _this._execute(workerInfo, nextAction);
  9716. }
  9717. });
  9718. };
  9719. return WorkerPool;
  9720. }());
  9721. BABYLON.WorkerPool = WorkerPool;
  9722. })(BABYLON || (BABYLON = {}));
  9723. //# sourceMappingURL=babylon.workerPool.js.map
  9724. var BABYLON;
  9725. (function (BABYLON) {
  9726. var _AlphaState = /** @class */ (function () {
  9727. /**
  9728. * Initializes the state.
  9729. */
  9730. function _AlphaState() {
  9731. this._isAlphaBlendDirty = false;
  9732. this._isBlendFunctionParametersDirty = false;
  9733. this._isBlendEquationParametersDirty = false;
  9734. this._isBlendConstantsDirty = false;
  9735. this._alphaBlend = false;
  9736. this._blendFunctionParameters = new Array(4);
  9737. this._blendEquationParameters = new Array(2);
  9738. this._blendConstants = new Array(4);
  9739. this.reset();
  9740. }
  9741. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9742. get: function () {
  9743. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9749. get: function () {
  9750. return this._alphaBlend;
  9751. },
  9752. set: function (value) {
  9753. if (this._alphaBlend === value) {
  9754. return;
  9755. }
  9756. this._alphaBlend = value;
  9757. this._isAlphaBlendDirty = true;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9763. if (this._blendConstants[0] === r &&
  9764. this._blendConstants[1] === g &&
  9765. this._blendConstants[2] === b &&
  9766. this._blendConstants[3] === a) {
  9767. return;
  9768. }
  9769. this._blendConstants[0] = r;
  9770. this._blendConstants[1] = g;
  9771. this._blendConstants[2] = b;
  9772. this._blendConstants[3] = a;
  9773. this._isBlendConstantsDirty = true;
  9774. };
  9775. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9776. if (this._blendFunctionParameters[0] === value0 &&
  9777. this._blendFunctionParameters[1] === value1 &&
  9778. this._blendFunctionParameters[2] === value2 &&
  9779. this._blendFunctionParameters[3] === value3) {
  9780. return;
  9781. }
  9782. this._blendFunctionParameters[0] = value0;
  9783. this._blendFunctionParameters[1] = value1;
  9784. this._blendFunctionParameters[2] = value2;
  9785. this._blendFunctionParameters[3] = value3;
  9786. this._isBlendFunctionParametersDirty = true;
  9787. };
  9788. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9789. if (this._blendEquationParameters[0] === rgb &&
  9790. this._blendEquationParameters[1] === alpha) {
  9791. return;
  9792. }
  9793. this._blendEquationParameters[0] = rgb;
  9794. this._blendEquationParameters[1] = alpha;
  9795. this._isBlendEquationParametersDirty = true;
  9796. };
  9797. _AlphaState.prototype.reset = function () {
  9798. this._alphaBlend = false;
  9799. this._blendFunctionParameters[0] = null;
  9800. this._blendFunctionParameters[1] = null;
  9801. this._blendFunctionParameters[2] = null;
  9802. this._blendFunctionParameters[3] = null;
  9803. this._blendEquationParameters[0] = null;
  9804. this._blendEquationParameters[1] = null;
  9805. this._blendConstants[0] = null;
  9806. this._blendConstants[1] = null;
  9807. this._blendConstants[2] = null;
  9808. this._blendConstants[3] = null;
  9809. this._isAlphaBlendDirty = true;
  9810. this._isBlendFunctionParametersDirty = false;
  9811. this._isBlendEquationParametersDirty = false;
  9812. this._isBlendConstantsDirty = false;
  9813. };
  9814. _AlphaState.prototype.apply = function (gl) {
  9815. if (!this.isDirty) {
  9816. return;
  9817. }
  9818. // Alpha blend
  9819. if (this._isAlphaBlendDirty) {
  9820. if (this._alphaBlend) {
  9821. gl.enable(gl.BLEND);
  9822. }
  9823. else {
  9824. gl.disable(gl.BLEND);
  9825. }
  9826. this._isAlphaBlendDirty = false;
  9827. }
  9828. // Alpha function
  9829. if (this._isBlendFunctionParametersDirty) {
  9830. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9831. this._isBlendFunctionParametersDirty = false;
  9832. }
  9833. // Alpha equation
  9834. if (this._isBlendEquationParametersDirty) {
  9835. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9836. this._isBlendEquationParametersDirty = false;
  9837. }
  9838. // Constants
  9839. if (this._isBlendConstantsDirty) {
  9840. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9841. this._isBlendConstantsDirty = false;
  9842. }
  9843. };
  9844. return _AlphaState;
  9845. }());
  9846. BABYLON._AlphaState = _AlphaState;
  9847. })(BABYLON || (BABYLON = {}));
  9848. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9849. var BABYLON;
  9850. (function (BABYLON) {
  9851. var _DepthCullingState = /** @class */ (function () {
  9852. /**
  9853. * Initializes the state.
  9854. */
  9855. function _DepthCullingState() {
  9856. this._isDepthTestDirty = false;
  9857. this._isDepthMaskDirty = false;
  9858. this._isDepthFuncDirty = false;
  9859. this._isCullFaceDirty = false;
  9860. this._isCullDirty = false;
  9861. this._isZOffsetDirty = false;
  9862. this._isFrontFaceDirty = false;
  9863. this.reset();
  9864. }
  9865. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9866. get: function () {
  9867. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9873. get: function () {
  9874. return this._zOffset;
  9875. },
  9876. set: function (value) {
  9877. if (this._zOffset === value) {
  9878. return;
  9879. }
  9880. this._zOffset = value;
  9881. this._isZOffsetDirty = true;
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9887. get: function () {
  9888. return this._cullFace;
  9889. },
  9890. set: function (value) {
  9891. if (this._cullFace === value) {
  9892. return;
  9893. }
  9894. this._cullFace = value;
  9895. this._isCullFaceDirty = true;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9901. get: function () {
  9902. return this._cull;
  9903. },
  9904. set: function (value) {
  9905. if (this._cull === value) {
  9906. return;
  9907. }
  9908. this._cull = value;
  9909. this._isCullDirty = true;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9915. get: function () {
  9916. return this._depthFunc;
  9917. },
  9918. set: function (value) {
  9919. if (this._depthFunc === value) {
  9920. return;
  9921. }
  9922. this._depthFunc = value;
  9923. this._isDepthFuncDirty = true;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9929. get: function () {
  9930. return this._depthMask;
  9931. },
  9932. set: function (value) {
  9933. if (this._depthMask === value) {
  9934. return;
  9935. }
  9936. this._depthMask = value;
  9937. this._isDepthMaskDirty = true;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9943. get: function () {
  9944. return this._depthTest;
  9945. },
  9946. set: function (value) {
  9947. if (this._depthTest === value) {
  9948. return;
  9949. }
  9950. this._depthTest = value;
  9951. this._isDepthTestDirty = true;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9957. get: function () {
  9958. return this._frontFace;
  9959. },
  9960. set: function (value) {
  9961. if (this._frontFace === value) {
  9962. return;
  9963. }
  9964. this._frontFace = value;
  9965. this._isFrontFaceDirty = true;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. _DepthCullingState.prototype.reset = function () {
  9971. this._depthMask = true;
  9972. this._depthTest = true;
  9973. this._depthFunc = null;
  9974. this._cullFace = null;
  9975. this._cull = null;
  9976. this._zOffset = 0;
  9977. this._frontFace = null;
  9978. this._isDepthTestDirty = true;
  9979. this._isDepthMaskDirty = true;
  9980. this._isDepthFuncDirty = false;
  9981. this._isCullFaceDirty = false;
  9982. this._isCullDirty = false;
  9983. this._isZOffsetDirty = false;
  9984. this._isFrontFaceDirty = false;
  9985. };
  9986. _DepthCullingState.prototype.apply = function (gl) {
  9987. if (!this.isDirty) {
  9988. return;
  9989. }
  9990. // Cull
  9991. if (this._isCullDirty) {
  9992. if (this.cull) {
  9993. gl.enable(gl.CULL_FACE);
  9994. }
  9995. else {
  9996. gl.disable(gl.CULL_FACE);
  9997. }
  9998. this._isCullDirty = false;
  9999. }
  10000. // Cull face
  10001. if (this._isCullFaceDirty) {
  10002. gl.cullFace(this.cullFace);
  10003. this._isCullFaceDirty = false;
  10004. }
  10005. // Depth mask
  10006. if (this._isDepthMaskDirty) {
  10007. gl.depthMask(this.depthMask);
  10008. this._isDepthMaskDirty = false;
  10009. }
  10010. // Depth test
  10011. if (this._isDepthTestDirty) {
  10012. if (this.depthTest) {
  10013. gl.enable(gl.DEPTH_TEST);
  10014. }
  10015. else {
  10016. gl.disable(gl.DEPTH_TEST);
  10017. }
  10018. this._isDepthTestDirty = false;
  10019. }
  10020. // Depth func
  10021. if (this._isDepthFuncDirty) {
  10022. gl.depthFunc(this.depthFunc);
  10023. this._isDepthFuncDirty = false;
  10024. }
  10025. // zOffset
  10026. if (this._isZOffsetDirty) {
  10027. if (this.zOffset) {
  10028. gl.enable(gl.POLYGON_OFFSET_FILL);
  10029. gl.polygonOffset(this.zOffset, 0);
  10030. }
  10031. else {
  10032. gl.disable(gl.POLYGON_OFFSET_FILL);
  10033. }
  10034. this._isZOffsetDirty = false;
  10035. }
  10036. // Front face
  10037. if (this._isFrontFaceDirty) {
  10038. gl.frontFace(this.frontFace);
  10039. this._isFrontFaceDirty = false;
  10040. }
  10041. };
  10042. return _DepthCullingState;
  10043. }());
  10044. BABYLON._DepthCullingState = _DepthCullingState;
  10045. })(BABYLON || (BABYLON = {}));
  10046. //# sourceMappingURL=babylon.depthCullingState.js.map
  10047. var BABYLON;
  10048. (function (BABYLON) {
  10049. var _StencilState = /** @class */ (function () {
  10050. function _StencilState() {
  10051. this._isStencilTestDirty = false;
  10052. this._isStencilMaskDirty = false;
  10053. this._isStencilFuncDirty = false;
  10054. this._isStencilOpDirty = false;
  10055. this.reset();
  10056. }
  10057. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10058. get: function () {
  10059. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10060. },
  10061. enumerable: true,
  10062. configurable: true
  10063. });
  10064. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10065. get: function () {
  10066. return this._stencilFunc;
  10067. },
  10068. set: function (value) {
  10069. if (this._stencilFunc === value) {
  10070. return;
  10071. }
  10072. this._stencilFunc = value;
  10073. this._isStencilFuncDirty = true;
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10079. get: function () {
  10080. return this._stencilFuncRef;
  10081. },
  10082. set: function (value) {
  10083. if (this._stencilFuncRef === value) {
  10084. return;
  10085. }
  10086. this._stencilFuncRef = value;
  10087. this._isStencilFuncDirty = true;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10093. get: function () {
  10094. return this._stencilFuncMask;
  10095. },
  10096. set: function (value) {
  10097. if (this._stencilFuncMask === value) {
  10098. return;
  10099. }
  10100. this._stencilFuncMask = value;
  10101. this._isStencilFuncDirty = true;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10107. get: function () {
  10108. return this._stencilOpStencilFail;
  10109. },
  10110. set: function (value) {
  10111. if (this._stencilOpStencilFail === value) {
  10112. return;
  10113. }
  10114. this._stencilOpStencilFail = value;
  10115. this._isStencilOpDirty = true;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10121. get: function () {
  10122. return this._stencilOpDepthFail;
  10123. },
  10124. set: function (value) {
  10125. if (this._stencilOpDepthFail === value) {
  10126. return;
  10127. }
  10128. this._stencilOpDepthFail = value;
  10129. this._isStencilOpDirty = true;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10135. get: function () {
  10136. return this._stencilOpStencilDepthPass;
  10137. },
  10138. set: function (value) {
  10139. if (this._stencilOpStencilDepthPass === value) {
  10140. return;
  10141. }
  10142. this._stencilOpStencilDepthPass = value;
  10143. this._isStencilOpDirty = true;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10149. get: function () {
  10150. return this._stencilMask;
  10151. },
  10152. set: function (value) {
  10153. if (this._stencilMask === value) {
  10154. return;
  10155. }
  10156. this._stencilMask = value;
  10157. this._isStencilMaskDirty = true;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10163. get: function () {
  10164. return this._stencilTest;
  10165. },
  10166. set: function (value) {
  10167. if (this._stencilTest === value) {
  10168. return;
  10169. }
  10170. this._stencilTest = value;
  10171. this._isStencilTestDirty = true;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. _StencilState.prototype.reset = function () {
  10177. this._stencilTest = false;
  10178. this._stencilMask = 0xFF;
  10179. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10180. this._stencilFuncRef = 1;
  10181. this._stencilFuncMask = 0xFF;
  10182. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10183. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10184. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10185. this._isStencilTestDirty = true;
  10186. this._isStencilMaskDirty = true;
  10187. this._isStencilFuncDirty = true;
  10188. this._isStencilOpDirty = true;
  10189. };
  10190. _StencilState.prototype.apply = function (gl) {
  10191. if (!this.isDirty) {
  10192. return;
  10193. }
  10194. // Stencil test
  10195. if (this._isStencilTestDirty) {
  10196. if (this.stencilTest) {
  10197. gl.enable(gl.STENCIL_TEST);
  10198. }
  10199. else {
  10200. gl.disable(gl.STENCIL_TEST);
  10201. }
  10202. this._isStencilTestDirty = false;
  10203. }
  10204. // Stencil mask
  10205. if (this._isStencilMaskDirty) {
  10206. gl.stencilMask(this.stencilMask);
  10207. this._isStencilMaskDirty = false;
  10208. }
  10209. // Stencil func
  10210. if (this._isStencilFuncDirty) {
  10211. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10212. this._isStencilFuncDirty = false;
  10213. }
  10214. // Stencil op
  10215. if (this._isStencilOpDirty) {
  10216. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10217. this._isStencilOpDirty = false;
  10218. }
  10219. };
  10220. return _StencilState;
  10221. }());
  10222. BABYLON._StencilState = _StencilState;
  10223. })(BABYLON || (BABYLON = {}));
  10224. //# sourceMappingURL=babylon.stencilState.js.map
  10225. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10226. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10227. s = arguments[i];
  10228. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10229. t[p] = s[p];
  10230. }
  10231. return t;
  10232. };
  10233. var BABYLON;
  10234. (function (BABYLON) {
  10235. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10236. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10237. };
  10238. var compileRawShader = function (gl, source, type) {
  10239. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10240. gl.shaderSource(shader, source);
  10241. gl.compileShader(shader);
  10242. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10243. var log = gl.getShaderInfoLog(shader);
  10244. if (log) {
  10245. throw new Error(log);
  10246. }
  10247. }
  10248. if (!shader) {
  10249. throw new Error("Something went wrong while compile the shader.");
  10250. }
  10251. return shader;
  10252. };
  10253. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10254. var magFilter = gl.NEAREST;
  10255. var minFilter = gl.NEAREST;
  10256. switch (samplingMode) {
  10257. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10258. magFilter = gl.LINEAR;
  10259. if (generateMipMaps) {
  10260. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10261. }
  10262. else {
  10263. minFilter = gl.LINEAR;
  10264. }
  10265. break;
  10266. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10267. magFilter = gl.LINEAR;
  10268. if (generateMipMaps) {
  10269. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10270. }
  10271. else {
  10272. minFilter = gl.LINEAR;
  10273. }
  10274. break;
  10275. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10276. magFilter = gl.NEAREST;
  10277. if (generateMipMaps) {
  10278. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10279. }
  10280. else {
  10281. minFilter = gl.NEAREST;
  10282. }
  10283. break;
  10284. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10285. magFilter = gl.NEAREST;
  10286. if (generateMipMaps) {
  10287. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10288. }
  10289. else {
  10290. minFilter = gl.NEAREST;
  10291. }
  10292. break;
  10293. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10294. magFilter = gl.NEAREST;
  10295. if (generateMipMaps) {
  10296. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10297. }
  10298. else {
  10299. minFilter = gl.LINEAR;
  10300. }
  10301. break;
  10302. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10303. magFilter = gl.NEAREST;
  10304. if (generateMipMaps) {
  10305. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10306. }
  10307. else {
  10308. minFilter = gl.LINEAR;
  10309. }
  10310. break;
  10311. case BABYLON.Texture.NEAREST_LINEAR:
  10312. magFilter = gl.NEAREST;
  10313. minFilter = gl.LINEAR;
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST:
  10316. magFilter = gl.NEAREST;
  10317. minFilter = gl.NEAREST;
  10318. break;
  10319. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10320. magFilter = gl.LINEAR;
  10321. if (generateMipMaps) {
  10322. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10323. }
  10324. else {
  10325. minFilter = gl.NEAREST;
  10326. }
  10327. break;
  10328. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10329. magFilter = gl.LINEAR;
  10330. if (generateMipMaps) {
  10331. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10332. }
  10333. else {
  10334. minFilter = gl.NEAREST;
  10335. }
  10336. break;
  10337. case BABYLON.Texture.LINEAR_LINEAR:
  10338. magFilter = gl.LINEAR;
  10339. minFilter = gl.LINEAR;
  10340. break;
  10341. case BABYLON.Texture.LINEAR_NEAREST:
  10342. magFilter = gl.LINEAR;
  10343. minFilter = gl.NEAREST;
  10344. break;
  10345. }
  10346. return {
  10347. min: minFilter,
  10348. mag: magFilter
  10349. };
  10350. };
  10351. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10352. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10353. var img;
  10354. var onload = function () {
  10355. loadedImages[index] = img;
  10356. loadedImages._internalCount++;
  10357. if (scene) {
  10358. scene._removePendingData(img);
  10359. }
  10360. if (loadedImages._internalCount === 6) {
  10361. onfinish(loadedImages);
  10362. }
  10363. };
  10364. var onerror = function (message, exception) {
  10365. if (scene) {
  10366. scene._removePendingData(img);
  10367. }
  10368. if (onErrorCallBack) {
  10369. onErrorCallBack(message, exception);
  10370. }
  10371. };
  10372. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10373. if (scene) {
  10374. scene._addPendingData(img);
  10375. }
  10376. };
  10377. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10378. if (onError === void 0) { onError = null; }
  10379. var loadedImages = [];
  10380. loadedImages._internalCount = 0;
  10381. for (var index = 0; index < 6; index++) {
  10382. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10383. }
  10384. };
  10385. var BufferPointer = /** @class */ (function () {
  10386. function BufferPointer() {
  10387. }
  10388. return BufferPointer;
  10389. }());
  10390. var InstancingAttributeInfo = /** @class */ (function () {
  10391. function InstancingAttributeInfo() {
  10392. }
  10393. return InstancingAttributeInfo;
  10394. }());
  10395. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10396. /**
  10397. * Define options used to create a render target texture
  10398. */
  10399. var RenderTargetCreationOptions = /** @class */ (function () {
  10400. function RenderTargetCreationOptions() {
  10401. }
  10402. return RenderTargetCreationOptions;
  10403. }());
  10404. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10405. /**
  10406. * Define options used to create a depth texture
  10407. */
  10408. var DepthTextureCreationOptions = /** @class */ (function () {
  10409. function DepthTextureCreationOptions() {
  10410. }
  10411. return DepthTextureCreationOptions;
  10412. }());
  10413. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10414. /**
  10415. * Regroup several parameters relative to the browser in use
  10416. */
  10417. var EngineCapabilities = /** @class */ (function () {
  10418. function EngineCapabilities() {
  10419. }
  10420. return EngineCapabilities;
  10421. }());
  10422. BABYLON.EngineCapabilities = EngineCapabilities;
  10423. /**
  10424. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10425. */
  10426. var Engine = /** @class */ (function () {
  10427. /**
  10428. * @constructor
  10429. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10430. * @param antialias defines enable antialiasing (default: false)
  10431. * @param options defines further options to be sent to the getContext() function
  10432. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10433. */
  10434. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10435. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10436. var _this = this;
  10437. // Public members
  10438. this.forcePOTTextures = false;
  10439. this.isFullscreen = false;
  10440. this.isPointerLock = false;
  10441. this.cullBackFaces = true;
  10442. this.renderEvenInBackground = true;
  10443. this.preventCacheWipeBetweenFrames = false;
  10444. // To enable/disable IDB support and avoid XHR on .manifest
  10445. this.enableOfflineSupport = false;
  10446. this.scenes = new Array();
  10447. this.postProcesses = new Array();
  10448. // Observables
  10449. /**
  10450. * Observable event triggered each time the rendering canvas is resized
  10451. */
  10452. this.onResizeObservable = new BABYLON.Observable();
  10453. /**
  10454. * Observable event triggered each time the canvas loses focus
  10455. */
  10456. this.onCanvasBlurObservable = new BABYLON.Observable();
  10457. /**
  10458. * Observable event triggered each time the canvas gains focus
  10459. */
  10460. this.onCanvasFocusObservable = new BABYLON.Observable();
  10461. /**
  10462. * Observable event triggered each time the canvas receives pointerout event
  10463. */
  10464. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10465. /**
  10466. * Observable event triggered before each texture is initialized
  10467. */
  10468. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10469. //WebVR
  10470. this._vrDisplay = undefined;
  10471. this._vrSupported = false;
  10472. this._vrExclusivePointerMode = false;
  10473. // Uniform buffers list
  10474. this.disableUniformBuffers = false;
  10475. this._uniformBuffers = new Array();
  10476. // Observables
  10477. /**
  10478. * Observable raised when the engine begins a new frame
  10479. */
  10480. this.onBeginFrameObservable = new BABYLON.Observable();
  10481. /**
  10482. * Observable raised when the engine ends the current frame
  10483. */
  10484. this.onEndFrameObservable = new BABYLON.Observable();
  10485. /**
  10486. * Observable raised when the engine is about to compile a shader
  10487. */
  10488. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10489. /**
  10490. * Observable raised when the engine has jsut compiled a shader
  10491. */
  10492. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10493. this._windowIsBackground = false;
  10494. this._webGLVersion = 1.0;
  10495. this._badOS = false;
  10496. this._badDesktopOS = false;
  10497. /**
  10498. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10499. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10500. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10501. */
  10502. this.disableTextureBindingOptimization = false;
  10503. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10504. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10505. this.onVRRequestPresentStart = new BABYLON.Observable();
  10506. this._colorWrite = true;
  10507. this._drawCalls = new BABYLON.PerfCounter();
  10508. this._textureCollisions = new BABYLON.PerfCounter();
  10509. this._renderingQueueLaunched = false;
  10510. this._activeRenderLoops = new Array();
  10511. // Deterministic lockstepMaxSteps
  10512. this._deterministicLockstep = false;
  10513. this._lockstepMaxSteps = 4;
  10514. // Lost context
  10515. this.onContextLostObservable = new BABYLON.Observable();
  10516. this.onContextRestoredObservable = new BABYLON.Observable();
  10517. this._contextWasLost = false;
  10518. this._doNotHandleContextLost = false;
  10519. // FPS
  10520. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10521. this._fps = 60;
  10522. this._deltaTime = 0;
  10523. /**
  10524. * Turn this value on if you want to pause FPS computation when in background
  10525. */
  10526. this.disablePerformanceMonitorInBackground = false;
  10527. // States
  10528. this._depthCullingState = new BABYLON._DepthCullingState();
  10529. this._stencilState = new BABYLON._StencilState();
  10530. this._alphaState = new BABYLON._AlphaState();
  10531. this._alphaMode = Engine.ALPHA_DISABLE;
  10532. // Cache
  10533. this._internalTexturesCache = new Array();
  10534. this._activeChannel = 0;
  10535. this._currentTextureChannel = -1;
  10536. this._boundTexturesCache = {};
  10537. this._compiledEffects = {};
  10538. this._vertexAttribArraysEnabled = [];
  10539. this._uintIndicesCurrentlySet = false;
  10540. this._currentBoundBuffer = new Array();
  10541. this._currentBufferPointers = new Array();
  10542. this._currentInstanceLocations = new Array();
  10543. this._currentInstanceBuffers = new Array();
  10544. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10545. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10546. this._vaoRecordInProgress = false;
  10547. this._mustWipeVertexAttributes = false;
  10548. this._nextFreeTextureSlots = new Array();
  10549. this._maxSimultaneousTextures = 0;
  10550. this._activeRequests = new Array();
  10551. // Hardware supported Compressed Textures
  10552. this._texturesSupported = new Array();
  10553. this._onVRFullScreenTriggered = function () {
  10554. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10555. //get the old size before we change
  10556. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10557. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10558. //get the width and height, change the render size
  10559. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10560. _this.setHardwareScalingLevel(1);
  10561. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10562. }
  10563. else {
  10564. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10565. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10566. }
  10567. };
  10568. this._boundUniforms = {};
  10569. // Register promises
  10570. BABYLON.PromisePolyfill.Apply();
  10571. var canvas = null;
  10572. Engine.Instances.push(this);
  10573. if (!canvasOrContext) {
  10574. return;
  10575. }
  10576. options = options || {};
  10577. if (canvasOrContext.getContext) {
  10578. canvas = canvasOrContext;
  10579. this._renderingCanvas = canvas;
  10580. if (antialias != null) {
  10581. options.antialias = antialias;
  10582. }
  10583. if (options.deterministicLockstep === undefined) {
  10584. options.deterministicLockstep = false;
  10585. }
  10586. if (options.lockstepMaxSteps === undefined) {
  10587. options.lockstepMaxSteps = 4;
  10588. }
  10589. if (options.preserveDrawingBuffer === undefined) {
  10590. options.preserveDrawingBuffer = false;
  10591. }
  10592. if (options.audioEngine === undefined) {
  10593. options.audioEngine = true;
  10594. }
  10595. if (options.stencil === undefined) {
  10596. options.stencil = true;
  10597. }
  10598. this._deterministicLockstep = options.deterministicLockstep;
  10599. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10600. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10601. // Exceptions
  10602. if (navigator && navigator.userAgent) {
  10603. var ua = navigator.userAgent;
  10604. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10605. var exception = _a[_i];
  10606. var key = exception.key;
  10607. var targets = exception.targets;
  10608. if (ua.indexOf(key) > -1) {
  10609. if (exception.capture && exception.captureConstraint) {
  10610. var capture = exception.capture;
  10611. var constraint = exception.captureConstraint;
  10612. var regex = new RegExp(capture);
  10613. var matches = regex.exec(ua);
  10614. if (matches && matches.length > 0) {
  10615. var capturedValue = parseInt(matches[matches.length - 1]);
  10616. if (capturedValue >= constraint) {
  10617. continue;
  10618. }
  10619. }
  10620. }
  10621. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10622. var target = targets_1[_b];
  10623. switch (target) {
  10624. case "uniformBuffer":
  10625. this.disableUniformBuffers = true;
  10626. break;
  10627. case "textureBindingOptimization":
  10628. this.disableTextureBindingOptimization = true;
  10629. break;
  10630. }
  10631. }
  10632. break;
  10633. }
  10634. }
  10635. }
  10636. // GL
  10637. if (!options.disableWebGL2Support) {
  10638. try {
  10639. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10640. if (this._gl) {
  10641. this._webGLVersion = 2.0;
  10642. }
  10643. }
  10644. catch (e) {
  10645. // Do nothing
  10646. }
  10647. }
  10648. if (!this._gl) {
  10649. if (!canvas) {
  10650. throw new Error("The provided canvas is null or undefined.");
  10651. }
  10652. try {
  10653. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10654. }
  10655. catch (e) {
  10656. throw new Error("WebGL not supported");
  10657. }
  10658. }
  10659. if (!this._gl) {
  10660. throw new Error("WebGL not supported");
  10661. }
  10662. this._onCanvasFocus = function () {
  10663. _this.onCanvasFocusObservable.notifyObservers(_this);
  10664. };
  10665. this._onCanvasBlur = function () {
  10666. _this.onCanvasBlurObservable.notifyObservers(_this);
  10667. };
  10668. canvas.addEventListener("focus", this._onCanvasFocus);
  10669. canvas.addEventListener("blur", this._onCanvasBlur);
  10670. this._onBlur = function () {
  10671. if (_this.disablePerformanceMonitorInBackground) {
  10672. _this._performanceMonitor.disable();
  10673. }
  10674. _this._windowIsBackground = true;
  10675. };
  10676. this._onFocus = function () {
  10677. if (_this.disablePerformanceMonitorInBackground) {
  10678. _this._performanceMonitor.enable();
  10679. }
  10680. _this._windowIsBackground = false;
  10681. };
  10682. this._onCanvasPointerOut = function (ev) {
  10683. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10684. };
  10685. window.addEventListener("blur", this._onBlur);
  10686. window.addEventListener("focus", this._onFocus);
  10687. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10688. // Context lost
  10689. if (!this._doNotHandleContextLost) {
  10690. this._onContextLost = function (evt) {
  10691. evt.preventDefault();
  10692. _this._contextWasLost = true;
  10693. BABYLON.Tools.Warn("WebGL context lost.");
  10694. _this.onContextLostObservable.notifyObservers(_this);
  10695. };
  10696. this._onContextRestored = function (evt) {
  10697. // Adding a timeout to avoid race condition at browser level
  10698. setTimeout(function () {
  10699. // Rebuild gl context
  10700. _this._initGLContext();
  10701. // Rebuild effects
  10702. _this._rebuildEffects();
  10703. // Rebuild textures
  10704. _this._rebuildInternalTextures();
  10705. // Rebuild buffers
  10706. _this._rebuildBuffers();
  10707. // Cache
  10708. _this.wipeCaches(true);
  10709. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10710. _this.onContextRestoredObservable.notifyObservers(_this);
  10711. _this._contextWasLost = false;
  10712. }, 0);
  10713. };
  10714. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10715. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10716. }
  10717. }
  10718. else {
  10719. this._gl = canvasOrContext;
  10720. this._renderingCanvas = this._gl.canvas;
  10721. if (this._gl.renderbufferStorageMultisample) {
  10722. this._webGLVersion = 2.0;
  10723. }
  10724. options.stencil = this._gl.getContextAttributes().stencil;
  10725. }
  10726. // Viewport
  10727. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10728. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10729. this.resize();
  10730. this._isStencilEnable = options.stencil ? true : false;
  10731. this._initGLContext();
  10732. if (canvas) {
  10733. // Fullscreen
  10734. this._onFullscreenChange = function () {
  10735. if (document.fullscreen !== undefined) {
  10736. _this.isFullscreen = document.fullscreen;
  10737. }
  10738. else if (document.mozFullScreen !== undefined) {
  10739. _this.isFullscreen = document.mozFullScreen;
  10740. }
  10741. else if (document.webkitIsFullScreen !== undefined) {
  10742. _this.isFullscreen = document.webkitIsFullScreen;
  10743. }
  10744. else if (document.msIsFullScreen !== undefined) {
  10745. _this.isFullscreen = document.msIsFullScreen;
  10746. }
  10747. // Pointer lock
  10748. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10749. canvas.requestPointerLock = canvas.requestPointerLock ||
  10750. canvas.msRequestPointerLock ||
  10751. canvas.mozRequestPointerLock ||
  10752. canvas.webkitRequestPointerLock;
  10753. if (canvas.requestPointerLock) {
  10754. canvas.requestPointerLock();
  10755. }
  10756. }
  10757. };
  10758. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10759. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10760. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10761. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10762. // Pointer lock
  10763. this._onPointerLockChange = function () {
  10764. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10765. document.webkitPointerLockElement === canvas ||
  10766. document.msPointerLockElement === canvas ||
  10767. document.pointerLockElement === canvas);
  10768. };
  10769. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10770. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10771. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10772. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10773. this._onVRDisplayPointerRestricted = function () {
  10774. if (canvas) {
  10775. canvas.requestPointerLock();
  10776. }
  10777. };
  10778. this._onVRDisplayPointerUnrestricted = function () {
  10779. document.exitPointerLock();
  10780. };
  10781. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10782. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10783. }
  10784. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10785. Engine.audioEngine = new BABYLON.AudioEngine();
  10786. }
  10787. // Prepare buffer pointers
  10788. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10789. this._currentBufferPointers[i] = new BufferPointer();
  10790. }
  10791. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10792. // Load WebVR Devices
  10793. if (options.autoEnableWebVR) {
  10794. this.initWebVR();
  10795. }
  10796. // Detect if we are running on a faulty buggy OS.
  10797. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10798. // Detect if we are running on a faulty buggy desktop OS.
  10799. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10800. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10801. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10802. }
  10803. Object.defineProperty(Engine, "LastCreatedEngine", {
  10804. get: function () {
  10805. if (Engine.Instances.length === 0) {
  10806. return null;
  10807. }
  10808. return Engine.Instances[Engine.Instances.length - 1];
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "LastCreatedScene", {
  10814. get: function () {
  10815. var lastCreatedEngine = Engine.LastCreatedEngine;
  10816. if (!lastCreatedEngine) {
  10817. return null;
  10818. }
  10819. if (lastCreatedEngine.scenes.length === 0) {
  10820. return null;
  10821. }
  10822. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. /**
  10828. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10829. */
  10830. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10831. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10832. var engine = Engine.Instances[engineIndex];
  10833. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10834. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10835. }
  10836. }
  10837. };
  10838. Object.defineProperty(Engine, "NEVER", {
  10839. get: function () {
  10840. return Engine._NEVER;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "ALWAYS", {
  10846. get: function () {
  10847. return Engine._ALWAYS;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(Engine, "LESS", {
  10853. get: function () {
  10854. return Engine._LESS;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(Engine, "EQUAL", {
  10860. get: function () {
  10861. return Engine._EQUAL;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(Engine, "LEQUAL", {
  10867. get: function () {
  10868. return Engine._LEQUAL;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(Engine, "GREATER", {
  10874. get: function () {
  10875. return Engine._GREATER;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine, "GEQUAL", {
  10881. get: function () {
  10882. return Engine._GEQUAL;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(Engine, "NOTEQUAL", {
  10888. get: function () {
  10889. return Engine._NOTEQUAL;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(Engine, "KEEP", {
  10895. get: function () {
  10896. return Engine._KEEP;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(Engine, "REPLACE", {
  10902. get: function () {
  10903. return Engine._REPLACE;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(Engine, "INCR", {
  10909. get: function () {
  10910. return Engine._INCR;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(Engine, "DECR", {
  10916. get: function () {
  10917. return Engine._DECR;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine, "INVERT", {
  10923. get: function () {
  10924. return Engine._INVERT;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine, "INCR_WRAP", {
  10930. get: function () {
  10931. return Engine._INCR_WRAP;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine, "DECR_WRAP", {
  10937. get: function () {
  10938. return Engine._DECR_WRAP;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10944. get: function () {
  10945. return Engine._ALPHA_DISABLE;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10951. get: function () {
  10952. return Engine._ALPHA_ONEONE;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(Engine, "ALPHA_ADD", {
  10958. get: function () {
  10959. return Engine._ALPHA_ADD;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10965. get: function () {
  10966. return Engine._ALPHA_COMBINE;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10972. get: function () {
  10973. return Engine._ALPHA_SUBTRACT;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10979. get: function () {
  10980. return Engine._ALPHA_MULTIPLY;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10986. get: function () {
  10987. return Engine._ALPHA_MAXIMIZED;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10993. get: function () {
  10994. return Engine._ALPHA_PREMULTIPLIED;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11000. get: function () {
  11001. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11007. get: function () {
  11008. return Engine._ALPHA_INTERPOLATE;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11014. get: function () {
  11015. return Engine._ALPHA_SCREENMODE;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11021. get: function () {
  11022. return Engine._DELAYLOADSTATE_NONE;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11028. get: function () {
  11029. return Engine._DELAYLOADSTATE_LOADED;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11035. get: function () {
  11036. return Engine._DELAYLOADSTATE_LOADING;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11042. get: function () {
  11043. return Engine._DELAYLOADSTATE_NOTLOADED;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11049. get: function () {
  11050. return Engine._TEXTUREFORMAT_ALPHA;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11056. get: function () {
  11057. return Engine._TEXTUREFORMAT_LUMINANCE;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11063. /**
  11064. * R32F
  11065. */
  11066. get: function () {
  11067. return Engine._TEXTUREFORMAT_R32F;
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11073. /**
  11074. * RG32F
  11075. */
  11076. get: function () {
  11077. return Engine._TEXTUREFORMAT_RG32F;
  11078. },
  11079. enumerable: true,
  11080. configurable: true
  11081. });
  11082. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11083. /**
  11084. * RGB32F
  11085. */
  11086. get: function () {
  11087. return Engine._TEXTUREFORMAT_RGB32F;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11093. /**
  11094. * RGBA32F
  11095. */
  11096. get: function () {
  11097. return Engine._TEXTUREFORMAT_RGBA32F;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11103. get: function () {
  11104. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11110. get: function () {
  11111. return Engine._TEXTUREFORMAT_RGB;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11117. get: function () {
  11118. return Engine._TEXTUREFORMAT_RGBA;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11124. get: function () {
  11125. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11131. get: function () {
  11132. return Engine._TEXTURETYPE_FLOAT;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11138. get: function () {
  11139. return Engine._TEXTURETYPE_HALF_FLOAT;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11145. get: function () {
  11146. return Engine._SCALEMODE_FLOOR;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11152. get: function () {
  11153. return Engine._SCALEMODE_NEAREST;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11159. get: function () {
  11160. return Engine._SCALEMODE_CEILING;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine, "Version", {
  11166. get: function () {
  11167. return "3.2.0-alphaB";
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11173. get: function () {
  11174. return this._vrExclusivePointerMode;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11180. get: function () {
  11181. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11187. get: function () {
  11188. return this._webGLVersion < 2 || this.forcePOTTextures;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(Engine.prototype, "badOS", {
  11194. get: function () {
  11195. return this._badOS;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11201. get: function () {
  11202. return this._badDesktopOS;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11208. get: function () {
  11209. return this._performanceMonitor;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11215. get: function () {
  11216. return this._texturesSupported;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11222. get: function () {
  11223. return this._textureFormatInUse;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(Engine.prototype, "currentViewport", {
  11229. get: function () {
  11230. return this._cachedViewport;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11236. // Empty texture
  11237. get: function () {
  11238. if (!this._emptyTexture) {
  11239. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11240. }
  11241. return this._emptyTexture;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11247. get: function () {
  11248. if (!this._emptyTexture3D) {
  11249. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11250. }
  11251. return this._emptyTexture3D;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11257. get: function () {
  11258. if (!this._emptyCubeTexture) {
  11259. var faceData = new Uint8Array(4);
  11260. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11261. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11262. }
  11263. return this._emptyCubeTexture;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Engine.prototype._rebuildInternalTextures = function () {
  11269. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11270. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11271. var internalTexture = currentState_1[_i];
  11272. internalTexture._rebuild();
  11273. }
  11274. };
  11275. Engine.prototype._rebuildEffects = function () {
  11276. for (var key in this._compiledEffects) {
  11277. var effect = this._compiledEffects[key];
  11278. effect._prepareEffect();
  11279. }
  11280. BABYLON.Effect.ResetCache();
  11281. };
  11282. Engine.prototype._rebuildBuffers = function () {
  11283. // Index / Vertex
  11284. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11285. var scene = _a[_i];
  11286. scene.resetCachedMaterial();
  11287. scene._rebuildGeometries();
  11288. scene._rebuildTextures();
  11289. }
  11290. // Uniforms
  11291. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11292. var uniformBuffer = _c[_b];
  11293. uniformBuffer._rebuild();
  11294. }
  11295. };
  11296. Engine.prototype._initGLContext = function () {
  11297. // Caps
  11298. this._caps = new EngineCapabilities();
  11299. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11300. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11301. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11302. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11303. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11304. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11305. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11306. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11307. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11308. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11309. // Infos
  11310. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11311. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11312. if (rendererInfo != null) {
  11313. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11314. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11315. }
  11316. if (!this._glVendor) {
  11317. this._glVendor = "Unknown vendor";
  11318. }
  11319. if (!this._glRenderer) {
  11320. this._glRenderer = "Unknown renderer";
  11321. }
  11322. // Constants
  11323. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11324. if (this._gl.RGBA16F !== 0x881A) {
  11325. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11326. }
  11327. if (this._gl.RGBA32F !== 0x8814) {
  11328. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11329. }
  11330. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11331. this._gl.DEPTH24_STENCIL8 = 35056;
  11332. }
  11333. // Extensions
  11334. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11335. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11336. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11337. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11338. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11339. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11340. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11341. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11342. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11343. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11344. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11345. this._caps.highPrecisionShaderSupported = true;
  11346. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11347. if (this._caps.timerQuery) {
  11348. if (this._webGLVersion === 1) {
  11349. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11350. }
  11351. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11352. }
  11353. // Checks if some of the format renders first to allow the use of webgl inspector.
  11354. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11355. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11356. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11357. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11358. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11359. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11360. if (this._webGLVersion > 1) {
  11361. this._gl.HALF_FLOAT_OES = 0x140B;
  11362. }
  11363. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11364. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11365. // Draw buffers
  11366. if (this._webGLVersion > 1) {
  11367. this._caps.drawBuffersExtension = true;
  11368. }
  11369. else {
  11370. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11371. if (drawBuffersExtension !== null) {
  11372. this._caps.drawBuffersExtension = true;
  11373. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11374. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11375. for (var i = 0; i < 16; i++) {
  11376. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11377. }
  11378. }
  11379. else {
  11380. this._caps.drawBuffersExtension = false;
  11381. }
  11382. }
  11383. // Depth Texture
  11384. if (this._webGLVersion > 1) {
  11385. this._caps.depthTextureExtension = true;
  11386. }
  11387. else {
  11388. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11389. if (depthTextureExtension != null) {
  11390. this._caps.depthTextureExtension = true;
  11391. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11392. }
  11393. }
  11394. // Vertex array object
  11395. if (this._webGLVersion > 1) {
  11396. this._caps.vertexArrayObject = true;
  11397. }
  11398. else {
  11399. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11400. if (vertexArrayObjectExtension != null) {
  11401. this._caps.vertexArrayObject = true;
  11402. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11403. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11404. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11405. }
  11406. else {
  11407. this._caps.vertexArrayObject = false;
  11408. }
  11409. }
  11410. // Instances count
  11411. if (this._webGLVersion > 1) {
  11412. this._caps.instancedArrays = true;
  11413. }
  11414. else {
  11415. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11416. if (instanceExtension != null) {
  11417. this._caps.instancedArrays = true;
  11418. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11419. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11420. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11421. }
  11422. else {
  11423. this._caps.instancedArrays = false;
  11424. }
  11425. }
  11426. // Intelligently add supported compressed formats in order to check for.
  11427. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11428. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11429. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11430. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11431. if (this._caps.astc)
  11432. this.texturesSupported.push('-astc.ktx');
  11433. if (this._caps.s3tc)
  11434. this.texturesSupported.push('-dxt.ktx');
  11435. if (this._caps.pvrtc)
  11436. this.texturesSupported.push('-pvrtc.ktx');
  11437. if (this._caps.etc2)
  11438. this.texturesSupported.push('-etc2.ktx');
  11439. if (this._caps.etc1)
  11440. this.texturesSupported.push('-etc1.ktx');
  11441. if (this._gl.getShaderPrecisionFormat) {
  11442. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11443. if (highp) {
  11444. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11445. }
  11446. }
  11447. // Depth buffer
  11448. this.setDepthBuffer(true);
  11449. this.setDepthFunctionToLessOrEqual();
  11450. this.setDepthWrite(true);
  11451. // Texture maps
  11452. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11453. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11454. this._nextFreeTextureSlots.push(slot);
  11455. }
  11456. };
  11457. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11458. get: function () {
  11459. return this._webGLVersion;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11465. /**
  11466. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11467. */
  11468. get: function () {
  11469. return this._isStencilEnable;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Engine.prototype._prepareWorkingCanvas = function () {
  11475. if (this._workingCanvas) {
  11476. return;
  11477. }
  11478. this._workingCanvas = document.createElement("canvas");
  11479. var context = this._workingCanvas.getContext("2d");
  11480. if (context) {
  11481. this._workingContext = context;
  11482. }
  11483. };
  11484. Engine.prototype.resetTextureCache = function () {
  11485. for (var key in this._boundTexturesCache) {
  11486. var boundTexture = this._boundTexturesCache[key];
  11487. if (boundTexture) {
  11488. this._removeDesignatedSlot(boundTexture);
  11489. }
  11490. this._boundTexturesCache[key] = null;
  11491. }
  11492. if (!this.disableTextureBindingOptimization) {
  11493. this._nextFreeTextureSlots = [];
  11494. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11495. this._nextFreeTextureSlots.push(slot);
  11496. }
  11497. }
  11498. this._currentTextureChannel = -1;
  11499. };
  11500. Engine.prototype.isDeterministicLockStep = function () {
  11501. return this._deterministicLockstep;
  11502. };
  11503. Engine.prototype.getLockstepMaxSteps = function () {
  11504. return this._lockstepMaxSteps;
  11505. };
  11506. Engine.prototype.getGlInfo = function () {
  11507. return {
  11508. vendor: this._glVendor,
  11509. renderer: this._glRenderer,
  11510. version: this._glVersion
  11511. };
  11512. };
  11513. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11514. if (useScreen === void 0) { useScreen = false; }
  11515. var viewport = camera.viewport;
  11516. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11517. };
  11518. Engine.prototype.getRenderWidth = function (useScreen) {
  11519. if (useScreen === void 0) { useScreen = false; }
  11520. if (!useScreen && this._currentRenderTarget) {
  11521. return this._currentRenderTarget.width;
  11522. }
  11523. return this._gl.drawingBufferWidth;
  11524. };
  11525. Engine.prototype.getRenderHeight = function (useScreen) {
  11526. if (useScreen === void 0) { useScreen = false; }
  11527. if (!useScreen && this._currentRenderTarget) {
  11528. return this._currentRenderTarget.height;
  11529. }
  11530. return this._gl.drawingBufferHeight;
  11531. };
  11532. Engine.prototype.getRenderingCanvas = function () {
  11533. return this._renderingCanvas;
  11534. };
  11535. Engine.prototype.getRenderingCanvasClientRect = function () {
  11536. if (!this._renderingCanvas) {
  11537. return null;
  11538. }
  11539. return this._renderingCanvas.getBoundingClientRect();
  11540. };
  11541. Engine.prototype.setHardwareScalingLevel = function (level) {
  11542. this._hardwareScalingLevel = level;
  11543. this.resize();
  11544. };
  11545. Engine.prototype.getHardwareScalingLevel = function () {
  11546. return this._hardwareScalingLevel;
  11547. };
  11548. Engine.prototype.getLoadedTexturesCache = function () {
  11549. return this._internalTexturesCache;
  11550. };
  11551. Engine.prototype.getCaps = function () {
  11552. return this._caps;
  11553. };
  11554. Object.defineProperty(Engine.prototype, "drawCalls", {
  11555. /** The number of draw calls submitted last frame */
  11556. get: function () {
  11557. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11558. return 0;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11564. get: function () {
  11565. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11566. return null;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Engine.prototype.getDepthFunction = function () {
  11572. return this._depthCullingState.depthFunc;
  11573. };
  11574. Engine.prototype.setDepthFunction = function (depthFunc) {
  11575. this._depthCullingState.depthFunc = depthFunc;
  11576. };
  11577. Engine.prototype.setDepthFunctionToGreater = function () {
  11578. this._depthCullingState.depthFunc = this._gl.GREATER;
  11579. };
  11580. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11581. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11582. };
  11583. Engine.prototype.setDepthFunctionToLess = function () {
  11584. this._depthCullingState.depthFunc = this._gl.LESS;
  11585. };
  11586. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11587. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11588. };
  11589. Engine.prototype.getStencilBuffer = function () {
  11590. return this._stencilState.stencilTest;
  11591. };
  11592. Engine.prototype.setStencilBuffer = function (enable) {
  11593. this._stencilState.stencilTest = enable;
  11594. };
  11595. Engine.prototype.getStencilMask = function () {
  11596. return this._stencilState.stencilMask;
  11597. };
  11598. Engine.prototype.setStencilMask = function (mask) {
  11599. this._stencilState.stencilMask = mask;
  11600. };
  11601. Engine.prototype.getStencilFunction = function () {
  11602. return this._stencilState.stencilFunc;
  11603. };
  11604. Engine.prototype.getStencilFunctionReference = function () {
  11605. return this._stencilState.stencilFuncRef;
  11606. };
  11607. Engine.prototype.getStencilFunctionMask = function () {
  11608. return this._stencilState.stencilFuncMask;
  11609. };
  11610. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11611. this._stencilState.stencilFunc = stencilFunc;
  11612. };
  11613. Engine.prototype.setStencilFunctionReference = function (reference) {
  11614. this._stencilState.stencilFuncRef = reference;
  11615. };
  11616. Engine.prototype.setStencilFunctionMask = function (mask) {
  11617. this._stencilState.stencilFuncMask = mask;
  11618. };
  11619. Engine.prototype.getStencilOperationFail = function () {
  11620. return this._stencilState.stencilOpStencilFail;
  11621. };
  11622. Engine.prototype.getStencilOperationDepthFail = function () {
  11623. return this._stencilState.stencilOpDepthFail;
  11624. };
  11625. Engine.prototype.getStencilOperationPass = function () {
  11626. return this._stencilState.stencilOpStencilDepthPass;
  11627. };
  11628. Engine.prototype.setStencilOperationFail = function (operation) {
  11629. this._stencilState.stencilOpStencilFail = operation;
  11630. };
  11631. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11632. this._stencilState.stencilOpDepthFail = operation;
  11633. };
  11634. Engine.prototype.setStencilOperationPass = function (operation) {
  11635. this._stencilState.stencilOpStencilDepthPass = operation;
  11636. };
  11637. Engine.prototype.setDitheringState = function (value) {
  11638. if (value) {
  11639. this._gl.enable(this._gl.DITHER);
  11640. }
  11641. else {
  11642. this._gl.disable(this._gl.DITHER);
  11643. }
  11644. };
  11645. Engine.prototype.setRasterizerState = function (value) {
  11646. if (value) {
  11647. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11648. }
  11649. else {
  11650. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11651. }
  11652. };
  11653. /**
  11654. * stop executing a render loop function and remove it from the execution array
  11655. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11656. */
  11657. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11658. if (!renderFunction) {
  11659. this._activeRenderLoops = [];
  11660. return;
  11661. }
  11662. var index = this._activeRenderLoops.indexOf(renderFunction);
  11663. if (index >= 0) {
  11664. this._activeRenderLoops.splice(index, 1);
  11665. }
  11666. };
  11667. Engine.prototype._renderLoop = function () {
  11668. if (!this._contextWasLost) {
  11669. var shouldRender = true;
  11670. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11671. shouldRender = false;
  11672. }
  11673. if (shouldRender) {
  11674. // Start new frame
  11675. this.beginFrame();
  11676. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11677. var renderFunction = this._activeRenderLoops[index];
  11678. renderFunction();
  11679. }
  11680. // Present
  11681. this.endFrame();
  11682. }
  11683. }
  11684. if (this._activeRenderLoops.length > 0) {
  11685. // Register new frame
  11686. var requester = null;
  11687. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11688. requester = this._vrDisplay;
  11689. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11690. }
  11691. else {
  11692. this._renderingQueueLaunched = false;
  11693. }
  11694. };
  11695. /**
  11696. * Register and execute a render loop. The engine can have more than one render function.
  11697. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11698. * @example
  11699. * engine.runRenderLoop(function () {
  11700. * scene.render()
  11701. * })
  11702. */
  11703. Engine.prototype.runRenderLoop = function (renderFunction) {
  11704. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11705. return;
  11706. }
  11707. this._activeRenderLoops.push(renderFunction);
  11708. if (!this._renderingQueueLaunched) {
  11709. this._renderingQueueLaunched = true;
  11710. this._bindedRenderFunction = this._renderLoop.bind(this);
  11711. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11712. }
  11713. };
  11714. /**
  11715. * Toggle full screen mode.
  11716. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11717. * @param {any} options - an options object to be sent to the requestFullscreen function
  11718. */
  11719. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11720. if (this.isFullscreen) {
  11721. BABYLON.Tools.ExitFullscreen();
  11722. }
  11723. else {
  11724. this._pointerLockRequested = requestPointerLock;
  11725. if (this._renderingCanvas) {
  11726. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11727. }
  11728. }
  11729. };
  11730. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11731. if (stencil === void 0) { stencil = false; }
  11732. this.applyStates();
  11733. var mode = 0;
  11734. if (backBuffer && color) {
  11735. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11736. mode |= this._gl.COLOR_BUFFER_BIT;
  11737. }
  11738. if (depth) {
  11739. this._gl.clearDepth(1.0);
  11740. mode |= this._gl.DEPTH_BUFFER_BIT;
  11741. }
  11742. if (stencil) {
  11743. this._gl.clearStencil(0);
  11744. mode |= this._gl.STENCIL_BUFFER_BIT;
  11745. }
  11746. this._gl.clear(mode);
  11747. };
  11748. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11749. var gl = this._gl;
  11750. // Save state
  11751. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11752. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11753. // Change state
  11754. gl.enable(gl.SCISSOR_TEST);
  11755. gl.scissor(x, y, width, height);
  11756. // Clear
  11757. this.clear(clearColor, true, true, true);
  11758. // Restore state
  11759. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11760. if (curScissor === true) {
  11761. gl.enable(gl.SCISSOR_TEST);
  11762. }
  11763. else {
  11764. gl.disable(gl.SCISSOR_TEST);
  11765. }
  11766. };
  11767. /**
  11768. * Set the WebGL's viewport
  11769. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11770. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11771. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11772. */
  11773. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11774. var width = requiredWidth || this.getRenderWidth();
  11775. var height = requiredHeight || this.getRenderHeight();
  11776. var x = viewport.x || 0;
  11777. var y = viewport.y || 0;
  11778. this._cachedViewport = viewport;
  11779. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11780. };
  11781. /**
  11782. * Directly set the WebGL Viewport
  11783. * The x, y, width & height are directly passed to the WebGL call
  11784. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  11785. */
  11786. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11787. var currentViewport = this._cachedViewport;
  11788. this._cachedViewport = null;
  11789. this._gl.viewport(x, y, width, height);
  11790. return currentViewport;
  11791. };
  11792. Engine.prototype.beginFrame = function () {
  11793. this.onBeginFrameObservable.notifyObservers(this);
  11794. this._measureFps();
  11795. };
  11796. Engine.prototype.endFrame = function () {
  11797. //force a flush in case we are using a bad OS.
  11798. if (this._badOS) {
  11799. this.flushFramebuffer();
  11800. }
  11801. //submit frame to the vr device, if enabled
  11802. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11803. // TODO: We should only submit the frame if we read frameData successfully.
  11804. this._vrDisplay.submitFrame();
  11805. }
  11806. this.onEndFrameObservable.notifyObservers(this);
  11807. };
  11808. /**
  11809. * resize the view according to the canvas' size.
  11810. * @example
  11811. * window.addEventListener("resize", function () {
  11812. * engine.resize();
  11813. * });
  11814. */
  11815. Engine.prototype.resize = function () {
  11816. // We're not resizing the size of the canvas while in VR mode & presenting
  11817. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11818. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11819. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11820. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11821. }
  11822. };
  11823. /**
  11824. * force a specific size of the canvas
  11825. * @param {number} width - the new canvas' width
  11826. * @param {number} height - the new canvas' height
  11827. */
  11828. Engine.prototype.setSize = function (width, height) {
  11829. if (!this._renderingCanvas) {
  11830. return;
  11831. }
  11832. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11833. return;
  11834. }
  11835. this._renderingCanvas.width = width;
  11836. this._renderingCanvas.height = height;
  11837. for (var index = 0; index < this.scenes.length; index++) {
  11838. var scene = this.scenes[index];
  11839. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11840. var cam = scene.cameras[camIndex];
  11841. cam._currentRenderId = 0;
  11842. }
  11843. }
  11844. if (this.onResizeObservable.hasObservers) {
  11845. this.onResizeObservable.notifyObservers(this);
  11846. }
  11847. };
  11848. // WebVR functions
  11849. Engine.prototype.isVRDevicePresent = function () {
  11850. return !!this._vrDisplay;
  11851. };
  11852. Engine.prototype.getVRDevice = function () {
  11853. return this._vrDisplay;
  11854. };
  11855. /**
  11856. * Initializes a webVR display and starts listening to display change events.
  11857. * The onVRDisplayChangedObservable will be notified upon these changes.
  11858. * @returns The onVRDisplayChangedObservable.
  11859. */
  11860. Engine.prototype.initWebVR = function () {
  11861. this.initWebVRAsync();
  11862. return this.onVRDisplayChangedObservable;
  11863. };
  11864. /**
  11865. * Initializes a webVR display and starts listening to display change events.
  11866. * The onVRDisplayChangedObservable will be notified upon these changes.
  11867. * @returns A promise containing a VRDisplay and if vr is supported.
  11868. */
  11869. Engine.prototype.initWebVRAsync = function () {
  11870. var _this = this;
  11871. var notifyObservers = function () {
  11872. var eventArgs = {
  11873. vrDisplay: _this._vrDisplay,
  11874. vrSupported: _this._vrSupported
  11875. };
  11876. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11877. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11878. };
  11879. if (!this._onVrDisplayConnect) {
  11880. this._onVrDisplayConnect = function (event) {
  11881. _this._vrDisplay = event.display;
  11882. notifyObservers();
  11883. };
  11884. this._onVrDisplayDisconnect = function () {
  11885. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11886. _this._vrDisplay = undefined;
  11887. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11888. notifyObservers();
  11889. };
  11890. this._onVrDisplayPresentChange = function () {
  11891. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11892. };
  11893. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11894. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11895. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11896. }
  11897. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11898. this._webVRInitPromise.then(notifyObservers);
  11899. return this._webVRInitPromise;
  11900. };
  11901. Engine.prototype.enableVR = function () {
  11902. var _this = this;
  11903. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11904. var onResolved = function () {
  11905. _this.onVRRequestPresentComplete.notifyObservers(true);
  11906. _this._onVRFullScreenTriggered();
  11907. };
  11908. var onRejected = function () {
  11909. _this.onVRRequestPresentComplete.notifyObservers(false);
  11910. };
  11911. this.onVRRequestPresentStart.notifyObservers(this);
  11912. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11913. }
  11914. };
  11915. Engine.prototype.disableVR = function () {
  11916. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11917. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11918. }
  11919. };
  11920. Engine.prototype._getVRDisplaysAsync = function () {
  11921. var _this = this;
  11922. return new Promise(function (res, rej) {
  11923. if (navigator.getVRDisplays) {
  11924. navigator.getVRDisplays().then(function (devices) {
  11925. _this._vrSupported = true;
  11926. // note that devices may actually be an empty array. This is fine;
  11927. // we expect this._vrDisplay to be undefined in this case.
  11928. _this._vrDisplay = devices[0];
  11929. res({
  11930. vrDisplay: _this._vrDisplay,
  11931. vrSupported: _this._vrSupported
  11932. });
  11933. });
  11934. }
  11935. else {
  11936. _this._vrDisplay = undefined;
  11937. _this._vrSupported = false;
  11938. res({
  11939. vrDisplay: _this._vrDisplay,
  11940. vrSupported: _this._vrSupported
  11941. });
  11942. }
  11943. });
  11944. };
  11945. /**
  11946. * Binds the frame buffer to the specified texture.
  11947. * @param texture The texture to render to or null for the default canvas
  11948. * @param faceIndex The face of the texture to render to in case of cube texture
  11949. * @param requiredWidth The width of the target to render to
  11950. * @param requiredHeight The height of the target to render to
  11951. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11952. * @param depthStencilTexture The depth stencil texture to use to render
  11953. */
  11954. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11955. if (this._currentRenderTarget) {
  11956. this.unBindFramebuffer(this._currentRenderTarget);
  11957. }
  11958. this._currentRenderTarget = texture;
  11959. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11960. var gl = this._gl;
  11961. if (texture.isCube) {
  11962. if (faceIndex === undefined) {
  11963. faceIndex = 0;
  11964. }
  11965. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11966. if (depthStencilTexture) {
  11967. if (depthStencilTexture._generateStencilBuffer) {
  11968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11969. }
  11970. else {
  11971. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11972. }
  11973. }
  11974. }
  11975. if (this._cachedViewport && !forceFullscreenViewport) {
  11976. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11977. }
  11978. else {
  11979. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11980. }
  11981. this.wipeCaches();
  11982. };
  11983. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11984. if (this._currentFramebuffer !== framebuffer) {
  11985. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11986. this._currentFramebuffer = framebuffer;
  11987. }
  11988. };
  11989. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11990. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11991. this._currentRenderTarget = null;
  11992. // If MSAA, we need to bitblt back to main texture
  11993. var gl = this._gl;
  11994. if (texture._MSAAFramebuffer) {
  11995. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11996. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11997. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11998. }
  11999. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12000. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12001. gl.generateMipmap(gl.TEXTURE_2D);
  12002. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12003. }
  12004. if (onBeforeUnbind) {
  12005. if (texture._MSAAFramebuffer) {
  12006. // Bind the correct framebuffer
  12007. this.bindUnboundFramebuffer(texture._framebuffer);
  12008. }
  12009. onBeforeUnbind();
  12010. }
  12011. this.bindUnboundFramebuffer(null);
  12012. };
  12013. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12014. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12015. this._currentRenderTarget = null;
  12016. // If MSAA, we need to bitblt back to main texture
  12017. var gl = this._gl;
  12018. if (textures[0]._MSAAFramebuffer) {
  12019. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12020. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12021. var attachments = textures[0]._attachments;
  12022. if (!attachments) {
  12023. attachments = new Array(textures.length);
  12024. textures[0]._attachments = attachments;
  12025. }
  12026. for (var i = 0; i < textures.length; i++) {
  12027. var texture = textures[i];
  12028. for (var j = 0; j < attachments.length; j++) {
  12029. attachments[j] = gl.NONE;
  12030. }
  12031. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12032. gl.readBuffer(attachments[i]);
  12033. gl.drawBuffers(attachments);
  12034. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12035. }
  12036. for (var i = 0; i < attachments.length; i++) {
  12037. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12038. }
  12039. gl.drawBuffers(attachments);
  12040. }
  12041. for (var i = 0; i < textures.length; i++) {
  12042. var texture = textures[i];
  12043. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12044. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12045. gl.generateMipmap(gl.TEXTURE_2D);
  12046. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12047. }
  12048. }
  12049. if (onBeforeUnbind) {
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. // Bind the correct framebuffer
  12052. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12053. }
  12054. onBeforeUnbind();
  12055. }
  12056. this.bindUnboundFramebuffer(null);
  12057. };
  12058. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12059. if (texture.generateMipMaps) {
  12060. var gl = this._gl;
  12061. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12062. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12063. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12064. }
  12065. };
  12066. Engine.prototype.flushFramebuffer = function () {
  12067. this._gl.flush();
  12068. };
  12069. Engine.prototype.restoreDefaultFramebuffer = function () {
  12070. if (this._currentRenderTarget) {
  12071. this.unBindFramebuffer(this._currentRenderTarget);
  12072. }
  12073. else {
  12074. this.bindUnboundFramebuffer(null);
  12075. }
  12076. if (this._cachedViewport) {
  12077. this.setViewport(this._cachedViewport);
  12078. }
  12079. this.wipeCaches();
  12080. };
  12081. // UBOs
  12082. Engine.prototype.createUniformBuffer = function (elements) {
  12083. var ubo = this._gl.createBuffer();
  12084. if (!ubo) {
  12085. throw new Error("Unable to create uniform buffer");
  12086. }
  12087. this.bindUniformBuffer(ubo);
  12088. if (elements instanceof Float32Array) {
  12089. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12090. }
  12091. else {
  12092. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12093. }
  12094. this.bindUniformBuffer(null);
  12095. ubo.references = 1;
  12096. return ubo;
  12097. };
  12098. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12099. var ubo = this._gl.createBuffer();
  12100. if (!ubo) {
  12101. throw new Error("Unable to create dynamic uniform buffer");
  12102. }
  12103. this.bindUniformBuffer(ubo);
  12104. if (elements instanceof Float32Array) {
  12105. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12106. }
  12107. else {
  12108. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12109. }
  12110. this.bindUniformBuffer(null);
  12111. ubo.references = 1;
  12112. return ubo;
  12113. };
  12114. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12115. this.bindUniformBuffer(uniformBuffer);
  12116. if (offset === undefined) {
  12117. offset = 0;
  12118. }
  12119. if (count === undefined) {
  12120. if (elements instanceof Float32Array) {
  12121. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12122. }
  12123. else {
  12124. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12125. }
  12126. }
  12127. else {
  12128. if (elements instanceof Float32Array) {
  12129. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12130. }
  12131. else {
  12132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12133. }
  12134. }
  12135. this.bindUniformBuffer(null);
  12136. };
  12137. // VBOs
  12138. Engine.prototype._resetVertexBufferBinding = function () {
  12139. this.bindArrayBuffer(null);
  12140. this._cachedVertexBuffers = null;
  12141. };
  12142. Engine.prototype.createVertexBuffer = function (vertices) {
  12143. var vbo = this._gl.createBuffer();
  12144. if (!vbo) {
  12145. throw new Error("Unable to create vertex buffer");
  12146. }
  12147. this.bindArrayBuffer(vbo);
  12148. if (vertices instanceof Float32Array) {
  12149. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12150. }
  12151. else {
  12152. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12153. }
  12154. this._resetVertexBufferBinding();
  12155. vbo.references = 1;
  12156. return vbo;
  12157. };
  12158. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12159. var vbo = this._gl.createBuffer();
  12160. if (!vbo) {
  12161. throw new Error("Unable to create dynamic vertex buffer");
  12162. }
  12163. this.bindArrayBuffer(vbo);
  12164. if (vertices instanceof Float32Array) {
  12165. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12166. }
  12167. else {
  12168. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12169. }
  12170. this._resetVertexBufferBinding();
  12171. vbo.references = 1;
  12172. return vbo;
  12173. };
  12174. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12175. if (offset === void 0) { offset = 0; }
  12176. // Force cache update
  12177. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12178. this.bindIndexBuffer(indexBuffer);
  12179. var arrayBuffer;
  12180. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12181. arrayBuffer = indices;
  12182. }
  12183. else {
  12184. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12185. }
  12186. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12187. this._resetIndexBufferBinding();
  12188. };
  12189. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12190. this.bindArrayBuffer(vertexBuffer);
  12191. if (offset === undefined) {
  12192. offset = 0;
  12193. }
  12194. if (count === undefined) {
  12195. if (vertices instanceof Float32Array) {
  12196. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12197. }
  12198. else {
  12199. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12200. }
  12201. }
  12202. else {
  12203. if (vertices instanceof Float32Array) {
  12204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12205. }
  12206. else {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12208. }
  12209. }
  12210. this._resetVertexBufferBinding();
  12211. };
  12212. Engine.prototype._resetIndexBufferBinding = function () {
  12213. this.bindIndexBuffer(null);
  12214. this._cachedIndexBuffer = null;
  12215. };
  12216. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12217. var vbo = this._gl.createBuffer();
  12218. if (!vbo) {
  12219. throw new Error("Unable to create index buffer");
  12220. }
  12221. this.bindIndexBuffer(vbo);
  12222. // Check for 32 bits indices
  12223. var arrayBuffer;
  12224. var need32Bits = false;
  12225. if (indices instanceof Uint16Array) {
  12226. arrayBuffer = indices;
  12227. }
  12228. else {
  12229. //check 32 bit support
  12230. if (this._caps.uintIndices) {
  12231. if (indices instanceof Uint32Array) {
  12232. arrayBuffer = indices;
  12233. need32Bits = true;
  12234. }
  12235. else {
  12236. //number[] or Int32Array, check if 32 bit is necessary
  12237. for (var index = 0; index < indices.length; index++) {
  12238. if (indices[index] > 65535) {
  12239. need32Bits = true;
  12240. break;
  12241. }
  12242. }
  12243. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12244. }
  12245. }
  12246. else {
  12247. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12248. arrayBuffer = new Uint16Array(indices);
  12249. }
  12250. }
  12251. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12252. this._resetIndexBufferBinding();
  12253. vbo.references = 1;
  12254. vbo.is32Bits = need32Bits;
  12255. return vbo;
  12256. };
  12257. Engine.prototype.bindArrayBuffer = function (buffer) {
  12258. if (!this._vaoRecordInProgress) {
  12259. this._unbindVertexArrayObject();
  12260. }
  12261. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12262. };
  12263. Engine.prototype.bindUniformBuffer = function (buffer) {
  12264. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12265. };
  12266. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12267. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12268. };
  12269. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12270. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12271. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12272. };
  12273. ;
  12274. Engine.prototype.bindIndexBuffer = function (buffer) {
  12275. if (!this._vaoRecordInProgress) {
  12276. this._unbindVertexArrayObject();
  12277. }
  12278. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12279. };
  12280. Engine.prototype.bindBuffer = function (buffer, target) {
  12281. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12282. this._gl.bindBuffer(target, buffer);
  12283. this._currentBoundBuffer[target] = buffer;
  12284. }
  12285. };
  12286. Engine.prototype.updateArrayBuffer = function (data) {
  12287. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12288. };
  12289. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12290. var pointer = this._currentBufferPointers[indx];
  12291. var changed = false;
  12292. if (!pointer.active) {
  12293. changed = true;
  12294. pointer.active = true;
  12295. pointer.index = indx;
  12296. pointer.size = size;
  12297. pointer.type = type;
  12298. pointer.normalized = normalized;
  12299. pointer.stride = stride;
  12300. pointer.offset = offset;
  12301. pointer.buffer = buffer;
  12302. }
  12303. else {
  12304. if (pointer.buffer !== buffer) {
  12305. pointer.buffer = buffer;
  12306. changed = true;
  12307. }
  12308. if (pointer.size !== size) {
  12309. pointer.size = size;
  12310. changed = true;
  12311. }
  12312. if (pointer.type !== type) {
  12313. pointer.type = type;
  12314. changed = true;
  12315. }
  12316. if (pointer.normalized !== normalized) {
  12317. pointer.normalized = normalized;
  12318. changed = true;
  12319. }
  12320. if (pointer.stride !== stride) {
  12321. pointer.stride = stride;
  12322. changed = true;
  12323. }
  12324. if (pointer.offset !== offset) {
  12325. pointer.offset = offset;
  12326. changed = true;
  12327. }
  12328. }
  12329. if (changed || this._vaoRecordInProgress) {
  12330. this.bindArrayBuffer(buffer);
  12331. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12332. }
  12333. };
  12334. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12335. if (indexBuffer == null) {
  12336. return;
  12337. }
  12338. if (this._cachedIndexBuffer !== indexBuffer) {
  12339. this._cachedIndexBuffer = indexBuffer;
  12340. this.bindIndexBuffer(indexBuffer);
  12341. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12342. }
  12343. };
  12344. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12345. var attributes = effect.getAttributesNames();
  12346. if (!this._vaoRecordInProgress) {
  12347. this._unbindVertexArrayObject();
  12348. }
  12349. this.unbindAllAttributes();
  12350. for (var index = 0; index < attributes.length; index++) {
  12351. var order = effect.getAttributeLocation(index);
  12352. if (order >= 0) {
  12353. var vertexBuffer = vertexBuffers[attributes[index]];
  12354. if (!vertexBuffer) {
  12355. continue;
  12356. }
  12357. this._gl.enableVertexAttribArray(order);
  12358. if (!this._vaoRecordInProgress) {
  12359. this._vertexAttribArraysEnabled[order] = true;
  12360. }
  12361. var buffer = vertexBuffer.getBuffer();
  12362. if (buffer) {
  12363. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12364. if (vertexBuffer.getIsInstanced()) {
  12365. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12366. if (!this._vaoRecordInProgress) {
  12367. this._currentInstanceLocations.push(order);
  12368. this._currentInstanceBuffers.push(buffer);
  12369. }
  12370. }
  12371. }
  12372. }
  12373. }
  12374. };
  12375. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12376. var vao = this._gl.createVertexArray();
  12377. this._vaoRecordInProgress = true;
  12378. this._gl.bindVertexArray(vao);
  12379. this._mustWipeVertexAttributes = true;
  12380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12381. this.bindIndexBuffer(indexBuffer);
  12382. this._vaoRecordInProgress = false;
  12383. this._gl.bindVertexArray(null);
  12384. return vao;
  12385. };
  12386. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12387. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12388. this._cachedVertexArrayObject = vertexArrayObject;
  12389. this._gl.bindVertexArray(vertexArrayObject);
  12390. this._cachedVertexBuffers = null;
  12391. this._cachedIndexBuffer = null;
  12392. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12393. this._mustWipeVertexAttributes = true;
  12394. }
  12395. };
  12396. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12397. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12398. this._cachedVertexBuffers = vertexBuffer;
  12399. this._cachedEffectForVertexBuffers = effect;
  12400. var attributesCount = effect.getAttributesCount();
  12401. this._unbindVertexArrayObject();
  12402. this.unbindAllAttributes();
  12403. var offset = 0;
  12404. for (var index = 0; index < attributesCount; index++) {
  12405. if (index < vertexDeclaration.length) {
  12406. var order = effect.getAttributeLocation(index);
  12407. if (order >= 0) {
  12408. this._gl.enableVertexAttribArray(order);
  12409. this._vertexAttribArraysEnabled[order] = true;
  12410. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12411. }
  12412. offset += vertexDeclaration[index] * 4;
  12413. }
  12414. }
  12415. }
  12416. this._bindIndexBufferWithCache(indexBuffer);
  12417. };
  12418. Engine.prototype._unbindVertexArrayObject = function () {
  12419. if (!this._cachedVertexArrayObject) {
  12420. return;
  12421. }
  12422. this._cachedVertexArrayObject = null;
  12423. this._gl.bindVertexArray(null);
  12424. };
  12425. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12426. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12427. this._cachedVertexBuffers = vertexBuffers;
  12428. this._cachedEffectForVertexBuffers = effect;
  12429. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12430. }
  12431. this._bindIndexBufferWithCache(indexBuffer);
  12432. };
  12433. Engine.prototype.unbindInstanceAttributes = function () {
  12434. var boundBuffer;
  12435. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12436. var instancesBuffer = this._currentInstanceBuffers[i];
  12437. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12438. boundBuffer = instancesBuffer;
  12439. this.bindArrayBuffer(instancesBuffer);
  12440. }
  12441. var offsetLocation = this._currentInstanceLocations[i];
  12442. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12443. }
  12444. this._currentInstanceBuffers.length = 0;
  12445. this._currentInstanceLocations.length = 0;
  12446. };
  12447. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12448. this._gl.deleteVertexArray(vao);
  12449. };
  12450. Engine.prototype._releaseBuffer = function (buffer) {
  12451. buffer.references--;
  12452. if (buffer.references === 0) {
  12453. this._gl.deleteBuffer(buffer);
  12454. return true;
  12455. }
  12456. return false;
  12457. };
  12458. Engine.prototype.createInstancesBuffer = function (capacity) {
  12459. var buffer = this._gl.createBuffer();
  12460. if (!buffer) {
  12461. throw new Error("Unable to create instance buffer");
  12462. }
  12463. buffer.capacity = capacity;
  12464. this.bindArrayBuffer(buffer);
  12465. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12466. return buffer;
  12467. };
  12468. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12469. this._gl.deleteBuffer(buffer);
  12470. };
  12471. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12472. this.bindArrayBuffer(instancesBuffer);
  12473. if (data) {
  12474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12475. }
  12476. if (offsetLocations[0].index !== undefined) {
  12477. var stride = 0;
  12478. for (var i = 0; i < offsetLocations.length; i++) {
  12479. var ai = offsetLocations[i];
  12480. stride += ai.attributeSize * 4;
  12481. }
  12482. for (var i = 0; i < offsetLocations.length; i++) {
  12483. var ai = offsetLocations[i];
  12484. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12485. this._gl.enableVertexAttribArray(ai.index);
  12486. this._vertexAttribArraysEnabled[ai.index] = true;
  12487. }
  12488. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12489. this._gl.vertexAttribDivisor(ai.index, 1);
  12490. this._currentInstanceLocations.push(ai.index);
  12491. this._currentInstanceBuffers.push(instancesBuffer);
  12492. }
  12493. }
  12494. else {
  12495. for (var index = 0; index < 4; index++) {
  12496. var offsetLocation = offsetLocations[index];
  12497. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12498. this._gl.enableVertexAttribArray(offsetLocation);
  12499. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12500. }
  12501. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12502. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12503. this._currentInstanceLocations.push(offsetLocation);
  12504. this._currentInstanceBuffers.push(instancesBuffer);
  12505. }
  12506. }
  12507. };
  12508. Engine.prototype.applyStates = function () {
  12509. this._depthCullingState.apply(this._gl);
  12510. this._stencilState.apply(this._gl);
  12511. this._alphaState.apply(this._gl);
  12512. };
  12513. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12514. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12515. };
  12516. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12517. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12518. };
  12519. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12520. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12521. };
  12522. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12523. // Apply states
  12524. this.applyStates();
  12525. this._drawCalls.addCount(1, false);
  12526. // Render
  12527. var drawMode = this.DrawMode(fillMode);
  12528. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12529. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12530. if (instancesCount) {
  12531. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12532. }
  12533. else {
  12534. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12535. }
  12536. };
  12537. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12538. // Apply states
  12539. this.applyStates();
  12540. this._drawCalls.addCount(1, false);
  12541. var drawMode = this.DrawMode(fillMode);
  12542. if (instancesCount) {
  12543. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12544. }
  12545. else {
  12546. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12547. }
  12548. };
  12549. Engine.prototype.DrawMode = function (fillMode) {
  12550. switch (fillMode) {
  12551. // Triangle views
  12552. case BABYLON.Material.TriangleFillMode:
  12553. return this._gl.TRIANGLES;
  12554. case BABYLON.Material.PointFillMode:
  12555. return this._gl.POINTS;
  12556. case BABYLON.Material.WireFrameFillMode:
  12557. return this._gl.LINES;
  12558. // Draw modes
  12559. case BABYLON.Material.PointListDrawMode:
  12560. return this._gl.POINTS;
  12561. case BABYLON.Material.LineListDrawMode:
  12562. return this._gl.LINES;
  12563. case BABYLON.Material.LineLoopDrawMode:
  12564. return this._gl.LINE_LOOP;
  12565. case BABYLON.Material.LineStripDrawMode:
  12566. return this._gl.LINE_STRIP;
  12567. case BABYLON.Material.TriangleStripDrawMode:
  12568. return this._gl.TRIANGLE_STRIP;
  12569. case BABYLON.Material.TriangleFanDrawMode:
  12570. return this._gl.TRIANGLE_FAN;
  12571. default:
  12572. return this._gl.TRIANGLES;
  12573. }
  12574. };
  12575. // Shaders
  12576. Engine.prototype._releaseEffect = function (effect) {
  12577. if (this._compiledEffects[effect._key]) {
  12578. delete this._compiledEffects[effect._key];
  12579. this._deleteProgram(effect.getProgram());
  12580. }
  12581. };
  12582. Engine.prototype._deleteProgram = function (program) {
  12583. if (program) {
  12584. program.__SPECTOR_rebuildProgram = null;
  12585. if (program.transformFeedback) {
  12586. this.deleteTransformFeedback(program.transformFeedback);
  12587. program.transformFeedback = null;
  12588. }
  12589. this._gl.deleteProgram(program);
  12590. }
  12591. };
  12592. /**
  12593. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12594. * @param samplers An array of string used to represent textures
  12595. */
  12596. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12597. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12598. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12599. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12600. if (this._compiledEffects[name]) {
  12601. var compiledEffect = this._compiledEffects[name];
  12602. if (onCompiled && compiledEffect.isReady()) {
  12603. onCompiled(compiledEffect);
  12604. }
  12605. return compiledEffect;
  12606. }
  12607. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12608. effect._key = name;
  12609. this._compiledEffects[name] = effect;
  12610. return effect;
  12611. };
  12612. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12613. if (uniformsNames === void 0) { uniformsNames = []; }
  12614. if (samplers === void 0) { samplers = []; }
  12615. if (defines === void 0) { defines = ""; }
  12616. return this.createEffect({
  12617. vertex: "particles",
  12618. fragmentElement: fragmentName
  12619. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12620. };
  12621. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12622. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12623. context = context || this._gl;
  12624. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12625. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12626. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12627. };
  12628. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12629. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12630. context = context || this._gl;
  12631. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12632. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12633. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12634. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12635. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12636. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12637. return program;
  12638. };
  12639. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12640. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12641. var shaderProgram = context.createProgram();
  12642. if (!shaderProgram) {
  12643. throw new Error("Unable to create program");
  12644. }
  12645. context.attachShader(shaderProgram, vertexShader);
  12646. context.attachShader(shaderProgram, fragmentShader);
  12647. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12648. var transformFeedback = this.createTransformFeedback();
  12649. this.bindTransformFeedback(transformFeedback);
  12650. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12651. shaderProgram.transformFeedback = transformFeedback;
  12652. }
  12653. context.linkProgram(shaderProgram);
  12654. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12655. this.bindTransformFeedback(null);
  12656. }
  12657. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12658. if (!linked) {
  12659. context.validateProgram(shaderProgram);
  12660. var error = context.getProgramInfoLog(shaderProgram);
  12661. if (error) {
  12662. throw new Error(error);
  12663. }
  12664. }
  12665. context.deleteShader(vertexShader);
  12666. context.deleteShader(fragmentShader);
  12667. return shaderProgram;
  12668. };
  12669. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12670. var results = new Array();
  12671. for (var index = 0; index < uniformsNames.length; index++) {
  12672. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12673. }
  12674. return results;
  12675. };
  12676. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12677. var results = [];
  12678. for (var index = 0; index < attributesNames.length; index++) {
  12679. try {
  12680. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12681. }
  12682. catch (e) {
  12683. results.push(-1);
  12684. }
  12685. }
  12686. return results;
  12687. };
  12688. Engine.prototype.enableEffect = function (effect) {
  12689. if (!effect) {
  12690. return;
  12691. }
  12692. // Use program
  12693. this.bindSamplers(effect);
  12694. this._currentEffect = effect;
  12695. if (effect.onBind) {
  12696. effect.onBind(effect);
  12697. }
  12698. effect.onBindObservable.notifyObservers(effect);
  12699. };
  12700. Engine.prototype.setIntArray = function (uniform, array) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform1iv(uniform, array);
  12704. };
  12705. Engine.prototype.setIntArray2 = function (uniform, array) {
  12706. if (!uniform || array.length % 2 !== 0)
  12707. return;
  12708. this._gl.uniform2iv(uniform, array);
  12709. };
  12710. Engine.prototype.setIntArray3 = function (uniform, array) {
  12711. if (!uniform || array.length % 3 !== 0)
  12712. return;
  12713. this._gl.uniform3iv(uniform, array);
  12714. };
  12715. Engine.prototype.setIntArray4 = function (uniform, array) {
  12716. if (!uniform || array.length % 4 !== 0)
  12717. return;
  12718. this._gl.uniform4iv(uniform, array);
  12719. };
  12720. Engine.prototype.setFloatArray = function (uniform, array) {
  12721. if (!uniform)
  12722. return;
  12723. this._gl.uniform1fv(uniform, array);
  12724. };
  12725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12726. if (!uniform || array.length % 2 !== 0)
  12727. return;
  12728. this._gl.uniform2fv(uniform, array);
  12729. };
  12730. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12731. if (!uniform || array.length % 3 !== 0)
  12732. return;
  12733. this._gl.uniform3fv(uniform, array);
  12734. };
  12735. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12736. if (!uniform || array.length % 4 !== 0)
  12737. return;
  12738. this._gl.uniform4fv(uniform, array);
  12739. };
  12740. Engine.prototype.setArray = function (uniform, array) {
  12741. if (!uniform)
  12742. return;
  12743. this._gl.uniform1fv(uniform, array);
  12744. };
  12745. Engine.prototype.setArray2 = function (uniform, array) {
  12746. if (!uniform || array.length % 2 !== 0)
  12747. return;
  12748. this._gl.uniform2fv(uniform, array);
  12749. };
  12750. Engine.prototype.setArray3 = function (uniform, array) {
  12751. if (!uniform || array.length % 3 !== 0)
  12752. return;
  12753. this._gl.uniform3fv(uniform, array);
  12754. };
  12755. Engine.prototype.setArray4 = function (uniform, array) {
  12756. if (!uniform || array.length % 4 !== 0)
  12757. return;
  12758. this._gl.uniform4fv(uniform, array);
  12759. };
  12760. Engine.prototype.setMatrices = function (uniform, matrices) {
  12761. if (!uniform)
  12762. return;
  12763. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12764. };
  12765. Engine.prototype.setMatrix = function (uniform, matrix) {
  12766. if (!uniform)
  12767. return;
  12768. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12769. };
  12770. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12771. if (!uniform)
  12772. return;
  12773. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12774. };
  12775. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12776. if (!uniform)
  12777. return;
  12778. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12779. };
  12780. Engine.prototype.setInt = function (uniform, value) {
  12781. if (!uniform)
  12782. return;
  12783. this._gl.uniform1i(uniform, value);
  12784. };
  12785. Engine.prototype.setFloat = function (uniform, value) {
  12786. if (!uniform)
  12787. return;
  12788. this._gl.uniform1f(uniform, value);
  12789. };
  12790. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12791. if (!uniform)
  12792. return;
  12793. this._gl.uniform2f(uniform, x, y);
  12794. };
  12795. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12796. if (!uniform)
  12797. return;
  12798. this._gl.uniform3f(uniform, x, y, z);
  12799. };
  12800. Engine.prototype.setBool = function (uniform, bool) {
  12801. if (!uniform)
  12802. return;
  12803. this._gl.uniform1i(uniform, bool);
  12804. };
  12805. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12806. if (!uniform)
  12807. return;
  12808. this._gl.uniform4f(uniform, x, y, z, w);
  12809. };
  12810. Engine.prototype.setColor3 = function (uniform, color3) {
  12811. if (!uniform)
  12812. return;
  12813. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12814. };
  12815. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12816. if (!uniform)
  12817. return;
  12818. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12819. };
  12820. /**
  12821. * Sets a Color4 on a uniform variable
  12822. * @param uniform defines the uniform location
  12823. * @param color4 defines the value to be set
  12824. */
  12825. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12826. if (!uniform)
  12827. return;
  12828. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12829. };
  12830. // States
  12831. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12832. if (zOffset === void 0) { zOffset = 0; }
  12833. if (reverseSide === void 0) { reverseSide = false; }
  12834. // Culling
  12835. if (this._depthCullingState.cull !== culling || force) {
  12836. this._depthCullingState.cull = culling;
  12837. }
  12838. // Cull face
  12839. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12840. if (this._depthCullingState.cullFace !== cullFace || force) {
  12841. this._depthCullingState.cullFace = cullFace;
  12842. }
  12843. // Z offset
  12844. this.setZOffset(zOffset);
  12845. // Front face
  12846. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12847. if (this._depthCullingState.frontFace !== frontFace || force) {
  12848. this._depthCullingState.frontFace = frontFace;
  12849. }
  12850. };
  12851. Engine.prototype.setZOffset = function (value) {
  12852. this._depthCullingState.zOffset = value;
  12853. };
  12854. Engine.prototype.getZOffset = function () {
  12855. return this._depthCullingState.zOffset;
  12856. };
  12857. Engine.prototype.setDepthBuffer = function (enable) {
  12858. this._depthCullingState.depthTest = enable;
  12859. };
  12860. Engine.prototype.getDepthWrite = function () {
  12861. return this._depthCullingState.depthMask;
  12862. };
  12863. Engine.prototype.setDepthWrite = function (enable) {
  12864. this._depthCullingState.depthMask = enable;
  12865. };
  12866. Engine.prototype.setColorWrite = function (enable) {
  12867. this._gl.colorMask(enable, enable, enable, enable);
  12868. this._colorWrite = enable;
  12869. };
  12870. Engine.prototype.getColorWrite = function () {
  12871. return this._colorWrite;
  12872. };
  12873. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12874. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12875. };
  12876. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12877. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12878. if (this._alphaMode === mode) {
  12879. return;
  12880. }
  12881. switch (mode) {
  12882. case Engine.ALPHA_DISABLE:
  12883. this._alphaState.alphaBlend = false;
  12884. break;
  12885. case Engine.ALPHA_PREMULTIPLIED:
  12886. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12887. this._alphaState.alphaBlend = true;
  12888. break;
  12889. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12890. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12891. this._alphaState.alphaBlend = true;
  12892. break;
  12893. case Engine.ALPHA_COMBINE:
  12894. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12895. this._alphaState.alphaBlend = true;
  12896. break;
  12897. case Engine.ALPHA_ONEONE:
  12898. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12899. this._alphaState.alphaBlend = true;
  12900. break;
  12901. case Engine.ALPHA_ADD:
  12902. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12903. this._alphaState.alphaBlend = true;
  12904. break;
  12905. case Engine.ALPHA_SUBTRACT:
  12906. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12907. this._alphaState.alphaBlend = true;
  12908. break;
  12909. case Engine.ALPHA_MULTIPLY:
  12910. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12911. this._alphaState.alphaBlend = true;
  12912. break;
  12913. case Engine.ALPHA_MAXIMIZED:
  12914. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12915. this._alphaState.alphaBlend = true;
  12916. break;
  12917. case Engine.ALPHA_INTERPOLATE:
  12918. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12919. this._alphaState.alphaBlend = true;
  12920. break;
  12921. case Engine.ALPHA_SCREENMODE:
  12922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12923. this._alphaState.alphaBlend = true;
  12924. break;
  12925. }
  12926. if (!noDepthWriteChange) {
  12927. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12928. }
  12929. this._alphaMode = mode;
  12930. };
  12931. Engine.prototype.getAlphaMode = function () {
  12932. return this._alphaMode;
  12933. };
  12934. // Textures
  12935. Engine.prototype.wipeCaches = function (bruteForce) {
  12936. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12937. return;
  12938. }
  12939. this._currentEffect = null;
  12940. // 6/8/2017: deltakosh: Should not be required anymore.
  12941. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12942. if (bruteForce) {
  12943. this.resetTextureCache();
  12944. this._currentProgram = null;
  12945. this._stencilState.reset();
  12946. this._depthCullingState.reset();
  12947. this.setDepthFunctionToLessOrEqual();
  12948. this._alphaState.reset();
  12949. }
  12950. this._resetVertexBufferBinding();
  12951. this._cachedIndexBuffer = null;
  12952. this._cachedEffectForVertexBuffers = null;
  12953. this._unbindVertexArrayObject();
  12954. this.bindIndexBuffer(null);
  12955. };
  12956. /**
  12957. * Set the compressed texture format to use, based on the formats you have, and the formats
  12958. * supported by the hardware / browser.
  12959. *
  12960. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12961. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12962. * to API arguments needed to compressed textures. This puts the burden on the container
  12963. * generator to house the arcane code for determining these for current & future formats.
  12964. *
  12965. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12966. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12967. *
  12968. * Note: The result of this call is not taken into account when a texture is base64.
  12969. *
  12970. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12971. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12972. *
  12973. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12974. * @returns The extension selected.
  12975. */
  12976. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12977. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12978. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12979. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12980. return this._textureFormatInUse = this._texturesSupported[i];
  12981. }
  12982. }
  12983. }
  12984. // actively set format to nothing, to allow this to be called more than once
  12985. // and possibly fail the 2nd time
  12986. this._textureFormatInUse = null;
  12987. return null;
  12988. };
  12989. Engine.prototype._createTexture = function () {
  12990. var texture = this._gl.createTexture();
  12991. if (!texture) {
  12992. throw new Error("Unable to create texture");
  12993. }
  12994. return texture;
  12995. };
  12996. /**
  12997. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12998. * @param {string} urlArg- This contains one of the following:
  12999. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13000. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13001. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13002. *
  13003. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13004. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13005. * @param {Scene} scene- Needed for loading to the correct scene.
  13006. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13007. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13008. * @param {callback} onError- Optional callback to be called upon failure.
  13009. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13010. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13011. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13012. *
  13013. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13014. */
  13015. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13016. var _this = this;
  13017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13018. if (onLoad === void 0) { onLoad = null; }
  13019. if (onError === void 0) { onError = null; }
  13020. if (buffer === void 0) { buffer = null; }
  13021. if (fallBack === void 0) { fallBack = null; }
  13022. if (format === void 0) { format = null; }
  13023. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13024. var fromData = url.substr(0, 5) === "data:";
  13025. var fromBlob = url.substr(0, 5) === "blob:";
  13026. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13027. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13028. // establish the file extension, if possible
  13029. var lastDot = url.lastIndexOf('.');
  13030. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13031. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13032. var isTGA = (extension.indexOf(".tga") === 0);
  13033. // determine if a ktx file should be substituted
  13034. var isKTX = false;
  13035. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13036. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13037. isKTX = true;
  13038. }
  13039. if (scene) {
  13040. scene._addPendingData(texture);
  13041. }
  13042. texture.url = url;
  13043. texture.generateMipMaps = !noMipmap;
  13044. texture.samplingMode = samplingMode;
  13045. texture.invertY = invertY;
  13046. if (!this._doNotHandleContextLost) {
  13047. // Keep a link to the buffer only if we plan to handle context lost
  13048. texture._buffer = buffer;
  13049. }
  13050. var onLoadObserver = null;
  13051. if (onLoad && !fallBack) {
  13052. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13053. }
  13054. if (!fallBack)
  13055. this._internalTexturesCache.push(texture);
  13056. var onerror = function (message, exception) {
  13057. if (scene) {
  13058. scene._removePendingData(texture);
  13059. }
  13060. if (onLoadObserver) {
  13061. texture.onLoadedObservable.remove(onLoadObserver);
  13062. }
  13063. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13064. if (isKTX) {
  13065. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13066. }
  13067. else if (BABYLON.Tools.UseFallbackTexture) {
  13068. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13069. }
  13070. if (onError) {
  13071. onError(message || "Unknown error", exception);
  13072. }
  13073. };
  13074. var callback = null;
  13075. // processing for non-image formats
  13076. if (isKTX || isTGA || isDDS) {
  13077. if (isKTX) {
  13078. callback = function (data) {
  13079. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13080. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13081. ktx.uploadLevels(_this._gl, !noMipmap);
  13082. return false;
  13083. }, samplingMode);
  13084. };
  13085. }
  13086. else if (isTGA) {
  13087. callback = function (arrayBuffer) {
  13088. var data = new Uint8Array(arrayBuffer);
  13089. var header = BABYLON.TGATools.GetTGAHeader(data);
  13090. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13091. BABYLON.TGATools.UploadContent(_this._gl, data);
  13092. return false;
  13093. }, samplingMode);
  13094. };
  13095. }
  13096. else if (isDDS) {
  13097. callback = function (data) {
  13098. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13099. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13100. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13101. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13102. return false;
  13103. }, samplingMode);
  13104. };
  13105. }
  13106. if (!buffer) {
  13107. this._loadFile(url, function (data) {
  13108. if (callback) {
  13109. callback(data);
  13110. }
  13111. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13112. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13113. });
  13114. }
  13115. else {
  13116. if (callback) {
  13117. callback(buffer);
  13118. }
  13119. }
  13120. // image format processing
  13121. }
  13122. else {
  13123. var onload = function (img) {
  13124. if (fromBlob && !_this._doNotHandleContextLost) {
  13125. // We need to store the image if we need to rebuild the texture
  13126. // in case of a webgl context lost
  13127. texture._buffer = img;
  13128. }
  13129. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13130. var gl = _this._gl;
  13131. var isPot = (img.width === potWidth && img.height === potHeight);
  13132. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13133. if (isPot) {
  13134. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13135. return false;
  13136. }
  13137. // Using shaders to rescale because canvas.drawImage is lossy
  13138. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13139. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13140. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13145. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13146. _this._releaseTexture(source);
  13147. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13148. continuationCallback();
  13149. });
  13150. return true;
  13151. }, samplingMode);
  13152. };
  13153. if (!fromData || isBase64)
  13154. if (buffer instanceof HTMLImageElement) {
  13155. onload(buffer);
  13156. }
  13157. else {
  13158. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13159. }
  13160. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13161. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13162. else
  13163. onload(buffer);
  13164. }
  13165. return texture;
  13166. };
  13167. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13168. var _this = this;
  13169. var rtt = this.createRenderTargetTexture({
  13170. width: destination.width,
  13171. height: destination.height,
  13172. }, {
  13173. generateMipMaps: false,
  13174. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13175. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13176. generateDepthBuffer: false,
  13177. generateStencilBuffer: false
  13178. });
  13179. if (!this._rescalePostProcess) {
  13180. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13181. }
  13182. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13183. _this._rescalePostProcess.onApply = function (effect) {
  13184. effect._bindTexture("textureSampler", source);
  13185. };
  13186. var hostingScene = scene;
  13187. if (!hostingScene) {
  13188. hostingScene = _this.scenes[_this.scenes.length - 1];
  13189. }
  13190. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13191. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13192. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13193. _this.unBindFramebuffer(rtt);
  13194. _this._releaseTexture(rtt);
  13195. if (onComplete) {
  13196. onComplete();
  13197. }
  13198. });
  13199. };
  13200. Engine.prototype._getInternalFormat = function (format) {
  13201. var internalFormat = this._gl.RGBA;
  13202. switch (format) {
  13203. case Engine.TEXTUREFORMAT_ALPHA:
  13204. internalFormat = this._gl.ALPHA;
  13205. break;
  13206. case Engine.TEXTUREFORMAT_LUMINANCE:
  13207. internalFormat = this._gl.LUMINANCE;
  13208. break;
  13209. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13210. internalFormat = this._gl.LUMINANCE_ALPHA;
  13211. break;
  13212. case Engine.TEXTUREFORMAT_RGB:
  13213. case Engine.TEXTUREFORMAT_RGB32F:
  13214. internalFormat = this._gl.RGB;
  13215. break;
  13216. case Engine.TEXTUREFORMAT_RGBA:
  13217. case Engine.TEXTUREFORMAT_RGBA32F:
  13218. internalFormat = this._gl.RGBA;
  13219. break;
  13220. case Engine.TEXTUREFORMAT_R32F:
  13221. internalFormat = this._gl.RED;
  13222. break;
  13223. case Engine.TEXTUREFORMAT_RG32F:
  13224. internalFormat = this._gl.RG;
  13225. break;
  13226. }
  13227. return internalFormat;
  13228. };
  13229. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13230. if (compression === void 0) { compression = null; }
  13231. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13232. if (!texture) {
  13233. return;
  13234. }
  13235. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13236. var internalFormat = this._getInternalFormat(format);
  13237. var textureType = this._getWebGLTextureType(type);
  13238. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13239. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13240. if (!this._doNotHandleContextLost) {
  13241. texture._bufferView = data;
  13242. texture.format = format;
  13243. texture.type = type;
  13244. texture.invertY = invertY;
  13245. texture._compression = compression;
  13246. }
  13247. if (texture.width % 4 !== 0) {
  13248. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13249. }
  13250. if (compression && data) {
  13251. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13252. }
  13253. else {
  13254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13255. }
  13256. if (texture.generateMipMaps) {
  13257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13258. }
  13259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13260. // this.resetTextureCache();
  13261. texture.isReady = true;
  13262. };
  13263. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13264. if (compression === void 0) { compression = null; }
  13265. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13266. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13267. texture.baseWidth = width;
  13268. texture.baseHeight = height;
  13269. texture.width = width;
  13270. texture.height = height;
  13271. texture.format = format;
  13272. texture.generateMipMaps = generateMipMaps;
  13273. texture.samplingMode = samplingMode;
  13274. texture.invertY = invertY;
  13275. texture._compression = compression;
  13276. texture.type = type;
  13277. if (!this._doNotHandleContextLost) {
  13278. texture._bufferView = data;
  13279. }
  13280. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13281. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13282. // Filters
  13283. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13285. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13286. if (generateMipMaps) {
  13287. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13288. }
  13289. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13290. this._internalTexturesCache.push(texture);
  13291. return texture;
  13292. };
  13293. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13294. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13295. texture.baseWidth = width;
  13296. texture.baseHeight = height;
  13297. if (generateMipMaps) {
  13298. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13299. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13300. }
  13301. // this.resetTextureCache();
  13302. texture.width = width;
  13303. texture.height = height;
  13304. texture.isReady = false;
  13305. texture.generateMipMaps = generateMipMaps;
  13306. texture.samplingMode = samplingMode;
  13307. this.updateTextureSamplingMode(samplingMode, texture);
  13308. this._internalTexturesCache.push(texture);
  13309. return texture;
  13310. };
  13311. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13312. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13313. if (texture.isCube) {
  13314. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13315. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13316. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13318. }
  13319. else if (texture.is3D) {
  13320. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13321. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13322. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13323. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13324. }
  13325. else {
  13326. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13327. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13329. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13330. }
  13331. texture.samplingMode = samplingMode;
  13332. };
  13333. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13334. if (premulAlpha === void 0) { premulAlpha = false; }
  13335. if (!texture) {
  13336. return;
  13337. }
  13338. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13340. if (premulAlpha) {
  13341. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13342. }
  13343. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13345. if (texture.generateMipMaps) {
  13346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13347. }
  13348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13349. if (premulAlpha) {
  13350. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13351. }
  13352. texture.isReady = true;
  13353. };
  13354. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13355. if (!texture || texture._isDisabled) {
  13356. return;
  13357. }
  13358. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13359. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13360. try {
  13361. // Testing video texture support
  13362. if (this._videoTextureSupported === undefined) {
  13363. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13364. if (this._gl.getError() !== 0) {
  13365. this._videoTextureSupported = false;
  13366. }
  13367. else {
  13368. this._videoTextureSupported = true;
  13369. }
  13370. }
  13371. // Copy video through the current working canvas if video texture is not supported
  13372. if (!this._videoTextureSupported) {
  13373. if (!texture._workingCanvas) {
  13374. texture._workingCanvas = document.createElement("canvas");
  13375. var context = texture._workingCanvas.getContext("2d");
  13376. if (!context) {
  13377. throw new Error("Unable to get 2d context");
  13378. }
  13379. texture._workingContext = context;
  13380. texture._workingCanvas.width = texture.width;
  13381. texture._workingCanvas.height = texture.height;
  13382. }
  13383. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13385. }
  13386. else {
  13387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13388. }
  13389. if (texture.generateMipMaps) {
  13390. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13391. }
  13392. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13393. // this.resetTextureCache();
  13394. texture.isReady = true;
  13395. }
  13396. catch (ex) {
  13397. // Something unexpected
  13398. // Let's disable the texture
  13399. texture._isDisabled = true;
  13400. }
  13401. };
  13402. /**
  13403. * Updates a depth texture Comparison Mode and Function.
  13404. * If the comparison Function is equal to 0, the mode will be set to none.
  13405. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13406. * @param texture The texture to set the comparison function for
  13407. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13408. */
  13409. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13410. if (this.webGLVersion === 1) {
  13411. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13412. return;
  13413. }
  13414. var gl = this._gl;
  13415. if (texture.isCube) {
  13416. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13417. if (comparisonFunction === 0) {
  13418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13420. }
  13421. else {
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13424. }
  13425. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13426. }
  13427. else {
  13428. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13429. if (comparisonFunction === 0) {
  13430. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13432. }
  13433. else {
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13436. }
  13437. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13438. }
  13439. texture._comparisonFunction = comparisonFunction;
  13440. };
  13441. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13442. var width = size.width || size;
  13443. var height = size.height || size;
  13444. internalTexture.baseWidth = width;
  13445. internalTexture.baseHeight = height;
  13446. internalTexture.width = width;
  13447. internalTexture.height = height;
  13448. internalTexture.isReady = true;
  13449. internalTexture.samples = 1;
  13450. internalTexture.generateMipMaps = false;
  13451. internalTexture._generateDepthBuffer = true;
  13452. internalTexture._generateStencilBuffer = generateStencil;
  13453. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13454. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13455. internalTexture._comparisonFunction = comparisonFunction;
  13456. var gl = this._gl;
  13457. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13458. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13459. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13460. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13461. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13462. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13463. if (comparisonFunction === 0) {
  13464. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13465. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13466. }
  13467. else {
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13469. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13470. }
  13471. };
  13472. /**
  13473. * Creates a depth stencil texture.
  13474. * This is only available in WebGL 2 or with the depth texture extension available.
  13475. * @param size The size of face edge in the texture.
  13476. * @param options The options defining the texture.
  13477. * @returns The texture
  13478. */
  13479. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13480. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13481. if (!this._caps.depthTextureExtension) {
  13482. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13483. return internalTexture;
  13484. }
  13485. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13486. var gl = this._gl;
  13487. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13488. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13489. if (this.webGLVersion > 1) {
  13490. if (internalOptions.generateStencil) {
  13491. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13492. }
  13493. else {
  13494. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13495. }
  13496. }
  13497. else {
  13498. if (internalOptions.generateStencil) {
  13499. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13500. }
  13501. else {
  13502. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13503. }
  13504. }
  13505. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13506. return internalTexture;
  13507. };
  13508. /**
  13509. * Creates a depth stencil cube texture.
  13510. * This is only available in WebGL 2.
  13511. * @param size The size of face edge in the cube texture.
  13512. * @param options The options defining the cube texture.
  13513. * @returns The cube texture
  13514. */
  13515. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13516. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13517. internalTexture.isCube = true;
  13518. if (this.webGLVersion === 1) {
  13519. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13520. return internalTexture;
  13521. }
  13522. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13523. var gl = this._gl;
  13524. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13525. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13526. // Create the depth/stencil buffer
  13527. for (var face = 0; face < 6; face++) {
  13528. if (internalOptions.generateStencil) {
  13529. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13530. }
  13531. else {
  13532. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13533. }
  13534. }
  13535. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13536. return internalTexture;
  13537. };
  13538. /**
  13539. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13540. * @param renderTarget The render target to set the frame buffer for
  13541. */
  13542. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13543. // Create the framebuffer
  13544. var internalTexture = renderTarget.getInternalTexture();
  13545. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13546. return;
  13547. }
  13548. var gl = this._gl;
  13549. var depthStencilTexture = renderTarget.depthStencilTexture;
  13550. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13551. if (depthStencilTexture.isCube) {
  13552. if (depthStencilTexture._generateStencilBuffer) {
  13553. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13554. }
  13555. else {
  13556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13557. }
  13558. }
  13559. else {
  13560. if (depthStencilTexture._generateStencilBuffer) {
  13561. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13562. }
  13563. else {
  13564. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13565. }
  13566. }
  13567. this.bindUnboundFramebuffer(null);
  13568. };
  13569. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13570. var fullOptions = new RenderTargetCreationOptions();
  13571. if (options !== undefined && typeof options === "object") {
  13572. fullOptions.generateMipMaps = options.generateMipMaps;
  13573. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13574. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13575. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13576. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13577. }
  13578. else {
  13579. fullOptions.generateMipMaps = options;
  13580. fullOptions.generateDepthBuffer = true;
  13581. fullOptions.generateStencilBuffer = false;
  13582. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13583. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13584. }
  13585. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13586. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13587. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13588. }
  13589. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13590. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13591. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13592. }
  13593. var gl = this._gl;
  13594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13595. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13596. var width = size.width || size;
  13597. var height = size.height || size;
  13598. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13599. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13600. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13601. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13602. }
  13603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13607. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13608. // Create the framebuffer
  13609. var framebuffer = gl.createFramebuffer();
  13610. this.bindUnboundFramebuffer(framebuffer);
  13611. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13612. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13613. if (fullOptions.generateMipMaps) {
  13614. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13615. }
  13616. // Unbind
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13618. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13619. this.bindUnboundFramebuffer(null);
  13620. texture._framebuffer = framebuffer;
  13621. texture.baseWidth = width;
  13622. texture.baseHeight = height;
  13623. texture.width = width;
  13624. texture.height = height;
  13625. texture.isReady = true;
  13626. texture.samples = 1;
  13627. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13628. texture.samplingMode = fullOptions.samplingMode;
  13629. texture.type = fullOptions.type;
  13630. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13631. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13632. // this.resetTextureCache();
  13633. this._internalTexturesCache.push(texture);
  13634. return texture;
  13635. };
  13636. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13637. var generateMipMaps = false;
  13638. var generateDepthBuffer = true;
  13639. var generateStencilBuffer = false;
  13640. var generateDepthTexture = false;
  13641. var textureCount = 1;
  13642. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13643. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13644. var types = [], samplingModes = [];
  13645. if (options !== undefined) {
  13646. generateMipMaps = options.generateMipMaps;
  13647. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13648. generateStencilBuffer = options.generateStencilBuffer;
  13649. generateDepthTexture = options.generateDepthTexture;
  13650. textureCount = options.textureCount || 1;
  13651. if (options.types) {
  13652. types = options.types;
  13653. }
  13654. if (options.samplingModes) {
  13655. samplingModes = options.samplingModes;
  13656. }
  13657. }
  13658. var gl = this._gl;
  13659. // Create the framebuffer
  13660. var framebuffer = gl.createFramebuffer();
  13661. this.bindUnboundFramebuffer(framebuffer);
  13662. var width = size.width || size;
  13663. var height = size.height || size;
  13664. var textures = [];
  13665. var attachments = [];
  13666. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13667. for (var i = 0; i < textureCount; i++) {
  13668. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13669. var type = types[i] || defaultType;
  13670. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13671. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13672. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13673. }
  13674. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13675. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13676. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13677. }
  13678. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13679. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13680. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13681. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13682. }
  13683. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13684. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13685. textures.push(texture);
  13686. attachments.push(attachment);
  13687. gl.activeTexture(gl["TEXTURE" + i]);
  13688. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13693. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13694. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13695. if (generateMipMaps) {
  13696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13697. }
  13698. // Unbind
  13699. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13700. texture._framebuffer = framebuffer;
  13701. texture._depthStencilBuffer = depthStencilBuffer;
  13702. texture.baseWidth = width;
  13703. texture.baseHeight = height;
  13704. texture.width = width;
  13705. texture.height = height;
  13706. texture.isReady = true;
  13707. texture.samples = 1;
  13708. texture.generateMipMaps = generateMipMaps;
  13709. texture.samplingMode = samplingMode;
  13710. texture.type = type;
  13711. texture._generateDepthBuffer = generateDepthBuffer;
  13712. texture._generateStencilBuffer = generateStencilBuffer;
  13713. texture._attachments = attachments;
  13714. this._internalTexturesCache.push(texture);
  13715. }
  13716. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13717. // Depth texture
  13718. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13719. gl.activeTexture(gl.TEXTURE0);
  13720. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13725. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  13726. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13727. depthTexture._framebuffer = framebuffer;
  13728. depthTexture.baseWidth = width;
  13729. depthTexture.baseHeight = height;
  13730. depthTexture.width = width;
  13731. depthTexture.height = height;
  13732. depthTexture.isReady = true;
  13733. depthTexture.samples = 1;
  13734. depthTexture.generateMipMaps = generateMipMaps;
  13735. depthTexture.samplingMode = gl.NEAREST;
  13736. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13737. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13738. textures.push(depthTexture);
  13739. this._internalTexturesCache.push(depthTexture);
  13740. }
  13741. gl.drawBuffers(attachments);
  13742. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13743. this.bindUnboundFramebuffer(null);
  13744. this.resetTextureCache();
  13745. return textures;
  13746. };
  13747. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13748. if (samples === void 0) { samples = 1; }
  13749. var depthStencilBuffer = null;
  13750. var gl = this._gl;
  13751. // Create the depth/stencil buffer
  13752. if (generateStencilBuffer) {
  13753. depthStencilBuffer = gl.createRenderbuffer();
  13754. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13755. if (samples > 1) {
  13756. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13757. }
  13758. else {
  13759. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13760. }
  13761. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13762. }
  13763. else if (generateDepthBuffer) {
  13764. depthStencilBuffer = gl.createRenderbuffer();
  13765. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13766. if (samples > 1) {
  13767. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13768. }
  13769. else {
  13770. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13771. }
  13772. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13773. }
  13774. return depthStencilBuffer;
  13775. };
  13776. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13777. if (this.webGLVersion < 2 || !texture) {
  13778. return 1;
  13779. }
  13780. if (texture.samples === samples) {
  13781. return samples;
  13782. }
  13783. var gl = this._gl;
  13784. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13785. // Dispose previous render buffers
  13786. if (texture._depthStencilBuffer) {
  13787. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13788. texture._depthStencilBuffer = null;
  13789. }
  13790. if (texture._MSAAFramebuffer) {
  13791. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13792. texture._MSAAFramebuffer = null;
  13793. }
  13794. if (texture._MSAARenderBuffer) {
  13795. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13796. texture._MSAARenderBuffer = null;
  13797. }
  13798. if (samples > 1) {
  13799. var framebuffer = gl.createFramebuffer();
  13800. if (!framebuffer) {
  13801. throw new Error("Unable to create multi sampled framebuffer");
  13802. }
  13803. texture._MSAAFramebuffer = framebuffer;
  13804. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13805. var colorRenderbuffer = gl.createRenderbuffer();
  13806. if (!colorRenderbuffer) {
  13807. throw new Error("Unable to create multi sampled framebuffer");
  13808. }
  13809. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13810. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13811. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13812. texture._MSAARenderBuffer = colorRenderbuffer;
  13813. }
  13814. else {
  13815. this.bindUnboundFramebuffer(texture._framebuffer);
  13816. }
  13817. texture.samples = samples;
  13818. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13819. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13820. this.bindUnboundFramebuffer(null);
  13821. return samples;
  13822. };
  13823. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13824. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13825. return 1;
  13826. }
  13827. if (textures[0].samples === samples) {
  13828. return samples;
  13829. }
  13830. var gl = this._gl;
  13831. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13832. // Dispose previous render buffers
  13833. if (textures[0]._depthStencilBuffer) {
  13834. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13835. textures[0]._depthStencilBuffer = null;
  13836. }
  13837. if (textures[0]._MSAAFramebuffer) {
  13838. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13839. textures[0]._MSAAFramebuffer = null;
  13840. }
  13841. for (var i = 0; i < textures.length; i++) {
  13842. if (textures[i]._MSAARenderBuffer) {
  13843. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13844. textures[i]._MSAARenderBuffer = null;
  13845. }
  13846. }
  13847. if (samples > 1) {
  13848. var framebuffer = gl.createFramebuffer();
  13849. if (!framebuffer) {
  13850. throw new Error("Unable to create multi sampled framebuffer");
  13851. }
  13852. this.bindUnboundFramebuffer(framebuffer);
  13853. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13854. var attachments = [];
  13855. for (var i = 0; i < textures.length; i++) {
  13856. var texture = textures[i];
  13857. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13858. var colorRenderbuffer = gl.createRenderbuffer();
  13859. if (!colorRenderbuffer) {
  13860. throw new Error("Unable to create multi sampled framebuffer");
  13861. }
  13862. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13863. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13864. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13865. texture._MSAAFramebuffer = framebuffer;
  13866. texture._MSAARenderBuffer = colorRenderbuffer;
  13867. texture.samples = samples;
  13868. texture._depthStencilBuffer = depthStencilBuffer;
  13869. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13870. attachments.push(attachment);
  13871. }
  13872. gl.drawBuffers(attachments);
  13873. }
  13874. else {
  13875. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13876. }
  13877. this.bindUnboundFramebuffer(null);
  13878. return samples;
  13879. };
  13880. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13881. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13882. };
  13883. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13884. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13885. };
  13886. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13887. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13888. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13890. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13891. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13892. }
  13893. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13894. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13895. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13896. }
  13897. var gl = this._gl;
  13898. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13900. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13901. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13902. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13903. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13904. }
  13905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13909. for (var face = 0; face < 6; face++) {
  13910. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13911. }
  13912. // Create the framebuffer
  13913. var framebuffer = gl.createFramebuffer();
  13914. this.bindUnboundFramebuffer(framebuffer);
  13915. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13916. // MipMaps
  13917. if (fullOptions.generateMipMaps) {
  13918. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13919. }
  13920. // Unbind
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13922. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13923. this.bindUnboundFramebuffer(null);
  13924. texture._framebuffer = framebuffer;
  13925. texture.width = size;
  13926. texture.height = size;
  13927. texture.isReady = true;
  13928. texture.isCube = true;
  13929. texture.samples = 1;
  13930. texture.generateMipMaps = fullOptions.generateMipMaps;
  13931. texture.samplingMode = fullOptions.samplingMode;
  13932. texture.type = fullOptions.type;
  13933. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13934. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13935. this._internalTexturesCache.push(texture);
  13936. return texture;
  13937. };
  13938. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13939. var _this = this;
  13940. if (onLoad === void 0) { onLoad = null; }
  13941. if (onError === void 0) { onError = null; }
  13942. if (forcedExtension === void 0) { forcedExtension = null; }
  13943. var callback = function (loadData) {
  13944. if (!loadData) {
  13945. if (onLoad) {
  13946. onLoad(null);
  13947. }
  13948. return;
  13949. }
  13950. var texture = loadData.texture;
  13951. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13952. texture._lodGenerationScale = scale;
  13953. texture._lodGenerationOffset = offset;
  13954. if (_this._caps.textureLOD) {
  13955. // Do not add extra process if texture lod is supported.
  13956. if (onLoad) {
  13957. onLoad(texture);
  13958. }
  13959. return;
  13960. }
  13961. var mipSlices = 3;
  13962. var gl = _this._gl;
  13963. var width = loadData.width;
  13964. if (!width) {
  13965. return;
  13966. }
  13967. var textures = [];
  13968. for (var i = 0; i < mipSlices; i++) {
  13969. //compute LOD from even spacing in smoothness (matching shader calculation)
  13970. var smoothness = i / (mipSlices - 1);
  13971. var roughness = 1 - smoothness;
  13972. var minLODIndex = offset; // roughness = 0
  13973. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13974. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13975. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13976. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13977. glTextureFromLod.isCube = true;
  13978. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13983. if (loadData.isDDS) {
  13984. var info = loadData.info;
  13985. var data = loadData.data;
  13986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13987. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13988. }
  13989. else {
  13990. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13991. }
  13992. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13993. // Wrap in a base texture for easy binding.
  13994. var lodTexture = new BABYLON.BaseTexture(scene);
  13995. lodTexture.isCube = true;
  13996. lodTexture._texture = glTextureFromLod;
  13997. glTextureFromLod.isReady = true;
  13998. textures.push(lodTexture);
  13999. }
  14000. texture._lodTextureHigh = textures[2];
  14001. texture._lodTextureMid = textures[1];
  14002. texture._lodTextureLow = textures[0];
  14003. if (onLoad) {
  14004. onLoad(texture);
  14005. }
  14006. };
  14007. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14008. };
  14009. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14010. var _this = this;
  14011. if (onLoad === void 0) { onLoad = null; }
  14012. if (onError === void 0) { onError = null; }
  14013. if (forcedExtension === void 0) { forcedExtension = null; }
  14014. var gl = this._gl;
  14015. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14016. texture.isCube = true;
  14017. texture.url = rootUrl;
  14018. texture.generateMipMaps = !noMipmap;
  14019. if (!this._doNotHandleContextLost) {
  14020. texture._extension = forcedExtension;
  14021. texture._files = files;
  14022. }
  14023. var isKTX = false;
  14024. var isDDS = false;
  14025. var lastDot = rootUrl.lastIndexOf('.');
  14026. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14027. if (this._textureFormatInUse) {
  14028. extension = this._textureFormatInUse;
  14029. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14030. isKTX = true;
  14031. }
  14032. else {
  14033. isDDS = (extension === ".dds");
  14034. }
  14035. var onerror = function (request, exception) {
  14036. if (onError && request) {
  14037. onError(request.status + " " + request.statusText, exception);
  14038. }
  14039. };
  14040. if (isKTX) {
  14041. this._loadFile(rootUrl, function (data) {
  14042. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14043. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14044. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14045. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14046. ktx.uploadLevels(_this._gl, !noMipmap);
  14047. _this.setCubeMapTextureParams(gl, loadMipmap);
  14048. texture.width = ktx.pixelWidth;
  14049. texture.height = ktx.pixelHeight;
  14050. texture.isReady = true;
  14051. }, undefined, undefined, true, onerror);
  14052. }
  14053. else if (isDDS) {
  14054. if (files && files.length === 6) {
  14055. this._cascadeLoadFiles(scene, function (imgs) {
  14056. var info;
  14057. var loadMipmap = false;
  14058. var width = 0;
  14059. for (var index = 0; index < imgs.length; index++) {
  14060. var data = imgs[index];
  14061. info = BABYLON.DDSTools.GetDDSInfo(data);
  14062. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14064. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14065. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14066. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14067. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14068. }
  14069. texture.width = info.width;
  14070. texture.height = info.height;
  14071. texture.type = info.textureType;
  14072. width = info.width;
  14073. }
  14074. _this.setCubeMapTextureParams(gl, loadMipmap);
  14075. texture.isReady = true;
  14076. if (onLoad) {
  14077. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14078. }
  14079. }, files, onError);
  14080. }
  14081. else {
  14082. this._loadFile(rootUrl, function (data) {
  14083. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. _this.setCubeMapTextureParams(gl, loadMipmap);
  14092. texture.width = info.width;
  14093. texture.height = info.height;
  14094. texture.isReady = true;
  14095. texture.type = info.textureType;
  14096. if (onLoad) {
  14097. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14098. }
  14099. }, undefined, undefined, true, onerror);
  14100. }
  14101. }
  14102. else {
  14103. if (!files) {
  14104. throw new Error("Cannot load cubemap because files were not defined");
  14105. }
  14106. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14107. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14108. var height = width;
  14109. _this._prepareWorkingCanvas();
  14110. if (!_this._workingCanvas || !_this._workingContext) {
  14111. return;
  14112. }
  14113. _this._workingCanvas.width = width;
  14114. _this._workingCanvas.height = height;
  14115. var faces = [
  14116. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14117. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14118. ];
  14119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14120. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14121. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14122. for (var index = 0; index < faces.length; index++) {
  14123. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14124. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14125. }
  14126. if (!noMipmap) {
  14127. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14128. }
  14129. _this.setCubeMapTextureParams(gl, !noMipmap);
  14130. texture.width = width;
  14131. texture.height = height;
  14132. texture.isReady = true;
  14133. if (format) {
  14134. texture.format = format;
  14135. }
  14136. texture.onLoadedObservable.notifyObservers(texture);
  14137. texture.onLoadedObservable.clear();
  14138. if (onLoad) {
  14139. onLoad();
  14140. }
  14141. }, files, onError);
  14142. }
  14143. this._internalTexturesCache.push(texture);
  14144. return texture;
  14145. };
  14146. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14152. // this.resetTextureCache();
  14153. };
  14154. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14155. if (compression === void 0) { compression = null; }
  14156. if (level === void 0) { level = 0; }
  14157. texture._bufferViewArray = data;
  14158. texture.format = format;
  14159. texture.type = type;
  14160. texture.invertY = invertY;
  14161. texture._compression = compression;
  14162. var gl = this._gl;
  14163. var textureType = this._getWebGLTextureType(type);
  14164. var internalFormat = this._getInternalFormat(format);
  14165. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14166. var needConversion = false;
  14167. if (internalFormat === gl.RGB) {
  14168. internalFormat = gl.RGBA;
  14169. needConversion = true;
  14170. }
  14171. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14173. if (texture.width % 4 !== 0) {
  14174. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14175. }
  14176. // Data are known to be in +X +Y +Z -X -Y -Z
  14177. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14178. var faceData = data[faceIndex];
  14179. if (compression) {
  14180. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14181. }
  14182. else {
  14183. if (needConversion) {
  14184. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14185. }
  14186. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14187. }
  14188. }
  14189. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14190. if (isPot && texture.generateMipMaps && level === 0) {
  14191. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14194. // this.resetTextureCache();
  14195. texture.isReady = true;
  14196. };
  14197. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14198. if (compression === void 0) { compression = null; }
  14199. var gl = this._gl;
  14200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14201. texture.isCube = true;
  14202. texture.generateMipMaps = generateMipMaps;
  14203. texture.format = format;
  14204. texture.type = type;
  14205. if (!this._doNotHandleContextLost) {
  14206. texture._bufferViewArray = data;
  14207. }
  14208. var textureType = this._getWebGLTextureType(type);
  14209. var internalFormat = this._getInternalFormat(format);
  14210. if (internalFormat === gl.RGB) {
  14211. internalFormat = gl.RGBA;
  14212. }
  14213. var width = size;
  14214. var height = width;
  14215. texture.width = width;
  14216. texture.height = height;
  14217. // Double check on POT to generate Mips.
  14218. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14219. if (!isPot) {
  14220. generateMipMaps = false;
  14221. }
  14222. // Upload data if needed. The texture won't be ready until then.
  14223. if (data) {
  14224. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14225. }
  14226. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14227. // Filters
  14228. if (data && generateMipMaps) {
  14229. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14230. }
  14231. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14234. }
  14235. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14238. }
  14239. else {
  14240. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14241. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14242. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14243. }
  14244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14247. return texture;
  14248. };
  14249. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14250. var _this = this;
  14251. if (onLoad === void 0) { onLoad = null; }
  14252. if (onError === void 0) { onError = null; }
  14253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14254. if (invertY === void 0) { invertY = false; }
  14255. var gl = this._gl;
  14256. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14257. scene._addPendingData(texture);
  14258. texture.url = url;
  14259. this._internalTexturesCache.push(texture);
  14260. var onerror = function (request, exception) {
  14261. scene._removePendingData(texture);
  14262. if (onError && request) {
  14263. onError(request.status + " " + request.statusText, exception);
  14264. }
  14265. };
  14266. var internalCallback = function (data) {
  14267. var width = texture.width;
  14268. var faceDataArrays = callback(data);
  14269. if (!faceDataArrays) {
  14270. return;
  14271. }
  14272. if (mipmmapGenerator) {
  14273. var textureType = _this._getWebGLTextureType(type);
  14274. var internalFormat = _this._getInternalFormat(format);
  14275. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14276. var needConversion = false;
  14277. if (internalFormat === gl.RGB) {
  14278. internalFormat = gl.RGBA;
  14279. needConversion = true;
  14280. }
  14281. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14282. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14283. var mipData = mipmmapGenerator(faceDataArrays);
  14284. for (var level = 0; level < mipData.length; level++) {
  14285. var mipSize = width >> level;
  14286. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14287. var mipFaceData = mipData[level][faceIndex];
  14288. if (needConversion) {
  14289. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14290. }
  14291. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14292. }
  14293. }
  14294. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14295. }
  14296. else {
  14297. texture.generateMipMaps = !noMipmap;
  14298. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14299. }
  14300. texture.isReady = true;
  14301. // this.resetTextureCache();
  14302. scene._removePendingData(texture);
  14303. if (onLoad) {
  14304. onLoad();
  14305. }
  14306. };
  14307. this._loadFile(url, function (data) {
  14308. internalCallback(data);
  14309. }, undefined, scene.database, true, onerror);
  14310. return texture;
  14311. };
  14312. ;
  14313. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14314. if (compression === void 0) { compression = null; }
  14315. var internalFormat = this._getInternalFormat(format);
  14316. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14317. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14318. if (!this._doNotHandleContextLost) {
  14319. texture._bufferView = data;
  14320. texture.format = format;
  14321. texture.invertY = invertY;
  14322. texture._compression = compression;
  14323. }
  14324. if (texture.width % 4 !== 0) {
  14325. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14326. }
  14327. if (compression && data) {
  14328. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14329. }
  14330. else {
  14331. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14332. }
  14333. if (texture.generateMipMaps) {
  14334. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14335. }
  14336. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14337. // this.resetTextureCache();
  14338. texture.isReady = true;
  14339. };
  14340. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14341. if (compression === void 0) { compression = null; }
  14342. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14343. texture.baseWidth = width;
  14344. texture.baseHeight = height;
  14345. texture.baseDepth = depth;
  14346. texture.width = width;
  14347. texture.height = height;
  14348. texture.depth = depth;
  14349. texture.format = format;
  14350. texture.generateMipMaps = generateMipMaps;
  14351. texture.samplingMode = samplingMode;
  14352. texture.is3D = true;
  14353. if (!this._doNotHandleContextLost) {
  14354. texture._bufferView = data;
  14355. }
  14356. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14358. // Filters
  14359. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14360. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14361. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14362. if (generateMipMaps) {
  14363. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14364. }
  14365. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14366. this._internalTexturesCache.push(texture);
  14367. return texture;
  14368. };
  14369. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14370. var gl = this._gl;
  14371. if (!gl) {
  14372. return;
  14373. }
  14374. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14377. if (!noMipmap && !isCompressed) {
  14378. gl.generateMipmap(gl.TEXTURE_2D);
  14379. }
  14380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14381. // this.resetTextureCache();
  14382. if (scene) {
  14383. scene._removePendingData(texture);
  14384. }
  14385. texture.onLoadedObservable.notifyObservers(texture);
  14386. texture.onLoadedObservable.clear();
  14387. };
  14388. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14389. var _this = this;
  14390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14391. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14392. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14393. var gl = this._gl;
  14394. if (!gl) {
  14395. return;
  14396. }
  14397. if (!texture._webGLTexture) {
  14398. // this.resetTextureCache();
  14399. if (scene) {
  14400. scene._removePendingData(texture);
  14401. }
  14402. return;
  14403. }
  14404. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14405. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14406. texture.baseWidth = width;
  14407. texture.baseHeight = height;
  14408. texture.width = potWidth;
  14409. texture.height = potHeight;
  14410. texture.isReady = true;
  14411. if (processFunction(potWidth, potHeight, function () {
  14412. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14413. })) {
  14414. // Returning as texture needs extra async steps
  14415. return;
  14416. }
  14417. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14418. };
  14419. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14420. // Create new RGBA data container.
  14421. var rgbaData;
  14422. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14423. rgbaData = new Float32Array(width * height * 4);
  14424. }
  14425. else {
  14426. rgbaData = new Uint32Array(width * height * 4);
  14427. }
  14428. // Convert each pixel.
  14429. for (var x = 0; x < width; x++) {
  14430. for (var y = 0; y < height; y++) {
  14431. var index = (y * width + x) * 3;
  14432. var newIndex = (y * width + x) * 4;
  14433. // Map Old Value to new value.
  14434. rgbaData[newIndex + 0] = rgbData[index + 0];
  14435. rgbaData[newIndex + 1] = rgbData[index + 1];
  14436. rgbaData[newIndex + 2] = rgbData[index + 2];
  14437. // Add fully opaque alpha channel.
  14438. rgbaData[newIndex + 3] = 1;
  14439. }
  14440. }
  14441. return rgbaData;
  14442. };
  14443. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14444. var gl = this._gl;
  14445. if (texture._framebuffer) {
  14446. gl.deleteFramebuffer(texture._framebuffer);
  14447. texture._framebuffer = null;
  14448. }
  14449. if (texture._depthStencilBuffer) {
  14450. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14451. texture._depthStencilBuffer = null;
  14452. }
  14453. if (texture._MSAAFramebuffer) {
  14454. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14455. texture._MSAAFramebuffer = null;
  14456. }
  14457. if (texture._MSAARenderBuffer) {
  14458. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14459. texture._MSAARenderBuffer = null;
  14460. }
  14461. };
  14462. Engine.prototype._releaseTexture = function (texture) {
  14463. var gl = this._gl;
  14464. this._releaseFramebufferObjects(texture);
  14465. gl.deleteTexture(texture._webGLTexture);
  14466. // Unbind channels
  14467. this.unbindAllTextures();
  14468. var index = this._internalTexturesCache.indexOf(texture);
  14469. if (index !== -1) {
  14470. this._internalTexturesCache.splice(index, 1);
  14471. }
  14472. // Integrated fixed lod samplers.
  14473. if (texture._lodTextureHigh) {
  14474. texture._lodTextureHigh.dispose();
  14475. }
  14476. if (texture._lodTextureMid) {
  14477. texture._lodTextureMid.dispose();
  14478. }
  14479. if (texture._lodTextureLow) {
  14480. texture._lodTextureLow.dispose();
  14481. }
  14482. };
  14483. Engine.prototype.setProgram = function (program) {
  14484. if (this._currentProgram !== program) {
  14485. this._gl.useProgram(program);
  14486. this._currentProgram = program;
  14487. }
  14488. };
  14489. Engine.prototype.bindSamplers = function (effect) {
  14490. this.setProgram(effect.getProgram());
  14491. var samplers = effect.getSamplers();
  14492. for (var index = 0; index < samplers.length; index++) {
  14493. var uniform = effect.getUniform(samplers[index]);
  14494. if (uniform) {
  14495. this._boundUniforms[index] = uniform;
  14496. }
  14497. }
  14498. this._currentEffect = null;
  14499. };
  14500. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14501. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14502. return;
  14503. }
  14504. // Remove
  14505. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14506. // Bind last to it
  14507. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14508. // Bind to dummy
  14509. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14510. };
  14511. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14512. if (!internalTexture) {
  14513. return -1;
  14514. }
  14515. internalTexture._initialSlot = channel;
  14516. if (this.disableTextureBindingOptimization) {
  14517. if (channel !== internalTexture._designatedSlot) {
  14518. this._textureCollisions.addCount(1, false);
  14519. }
  14520. }
  14521. else {
  14522. if (channel !== internalTexture._designatedSlot) {
  14523. if (internalTexture._designatedSlot > -1) {
  14524. return internalTexture._designatedSlot;
  14525. }
  14526. else {
  14527. // No slot for this texture, let's pick a new one (if we find a free slot)
  14528. if (this._nextFreeTextureSlots.length) {
  14529. return this._nextFreeTextureSlots[0];
  14530. }
  14531. // We need to recycle the oldest bound texture, sorry.
  14532. this._textureCollisions.addCount(1, false);
  14533. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14534. }
  14535. }
  14536. }
  14537. return channel;
  14538. };
  14539. Engine.prototype._linkTrackers = function (previous, next) {
  14540. previous.next = next;
  14541. next.previous = previous;
  14542. };
  14543. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14544. var currentSlot = internalTexture._designatedSlot;
  14545. if (currentSlot === -1) {
  14546. return -1;
  14547. }
  14548. internalTexture._designatedSlot = -1;
  14549. if (this.disableTextureBindingOptimization) {
  14550. return -1;
  14551. }
  14552. // Remove from bound list
  14553. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14554. // Free the slot
  14555. this._boundTexturesCache[currentSlot] = null;
  14556. this._nextFreeTextureSlots.push(currentSlot);
  14557. return currentSlot;
  14558. };
  14559. Engine.prototype._activateCurrentTexture = function () {
  14560. if (this._currentTextureChannel !== this._activeChannel) {
  14561. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14562. this._currentTextureChannel = this._activeChannel;
  14563. }
  14564. };
  14565. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14566. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14567. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14568. this._activeChannel = texture._designatedSlot;
  14569. }
  14570. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14571. var isTextureForRendering = texture && texture._initialSlot > -1;
  14572. if (currentTextureBound !== texture) {
  14573. if (currentTextureBound) {
  14574. this._removeDesignatedSlot(currentTextureBound);
  14575. }
  14576. this._activateCurrentTexture();
  14577. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14578. this._boundTexturesCache[this._activeChannel] = texture;
  14579. if (texture) {
  14580. if (!this.disableTextureBindingOptimization) {
  14581. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14582. if (slotIndex > -1) {
  14583. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14584. }
  14585. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14586. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14587. }
  14588. texture._designatedSlot = this._activeChannel;
  14589. }
  14590. }
  14591. else if (forTextureDataUpdate) {
  14592. this._activateCurrentTexture();
  14593. }
  14594. if (isTextureForRendering && !forTextureDataUpdate) {
  14595. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14596. }
  14597. };
  14598. Engine.prototype._bindTexture = function (channel, texture) {
  14599. if (channel < 0) {
  14600. return;
  14601. }
  14602. if (texture) {
  14603. channel = this._getCorrectTextureChannel(channel, texture);
  14604. }
  14605. this._activeChannel = channel;
  14606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14607. };
  14608. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14609. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14610. };
  14611. Engine.prototype.unbindAllTextures = function () {
  14612. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14613. this._activeChannel = channel;
  14614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14615. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14616. if (this.webGLVersion > 1) {
  14617. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14618. }
  14619. }
  14620. };
  14621. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14622. if (channel < 0) {
  14623. return;
  14624. }
  14625. if (uniform) {
  14626. this._boundUniforms[channel] = uniform;
  14627. }
  14628. this._setTexture(channel, texture);
  14629. };
  14630. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14631. var uniform = this._boundUniforms[sourceSlot];
  14632. if (uniform._currentState === destination) {
  14633. return;
  14634. }
  14635. this._gl.uniform1i(uniform, destination);
  14636. uniform._currentState = destination;
  14637. };
  14638. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14639. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14640. // Not ready?
  14641. if (!texture) {
  14642. if (this._boundTexturesCache[channel] != null) {
  14643. this._activeChannel = channel;
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14645. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14646. if (this.webGLVersion > 1) {
  14647. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14648. }
  14649. }
  14650. return false;
  14651. }
  14652. // Video
  14653. if (texture.video) {
  14654. this._activeChannel = channel;
  14655. texture.update();
  14656. }
  14657. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14658. texture.delayLoad();
  14659. return false;
  14660. }
  14661. var internalTexture;
  14662. if (texture.isReady()) {
  14663. internalTexture = texture.getInternalTexture();
  14664. }
  14665. else if (texture.isCube) {
  14666. internalTexture = this.emptyCubeTexture;
  14667. }
  14668. else if (texture.is3D) {
  14669. internalTexture = this.emptyTexture3D;
  14670. }
  14671. else {
  14672. internalTexture = this.emptyTexture;
  14673. }
  14674. if (!isPartOfTextureArray) {
  14675. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14676. }
  14677. if (this._boundTexturesCache[channel] === internalTexture) {
  14678. this._moveBoundTextureOnTop(internalTexture);
  14679. if (!isPartOfTextureArray) {
  14680. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14681. }
  14682. return false;
  14683. }
  14684. this._activeChannel = channel;
  14685. if (internalTexture && internalTexture.is3D) {
  14686. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14687. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14688. internalTexture._cachedWrapU = texture.wrapU;
  14689. switch (texture.wrapU) {
  14690. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14691. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14692. break;
  14693. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14694. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14695. break;
  14696. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14697. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14698. break;
  14699. }
  14700. }
  14701. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14702. internalTexture._cachedWrapV = texture.wrapV;
  14703. switch (texture.wrapV) {
  14704. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14705. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14706. break;
  14707. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14708. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14709. break;
  14710. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14711. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14712. break;
  14713. }
  14714. }
  14715. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14716. internalTexture._cachedWrapR = texture.wrapR;
  14717. switch (texture.wrapR) {
  14718. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14719. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14720. break;
  14721. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14722. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14723. break;
  14724. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14725. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14726. break;
  14727. }
  14728. }
  14729. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14730. }
  14731. else if (internalTexture && internalTexture.isCube) {
  14732. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14733. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14734. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14735. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14736. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14737. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14738. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14739. }
  14740. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14741. }
  14742. else {
  14743. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14744. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14745. internalTexture._cachedWrapU = texture.wrapU;
  14746. switch (texture.wrapU) {
  14747. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14748. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14749. break;
  14750. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14751. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14752. break;
  14753. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14754. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14755. break;
  14756. }
  14757. }
  14758. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14759. internalTexture._cachedWrapV = texture.wrapV;
  14760. switch (texture.wrapV) {
  14761. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14762. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14763. break;
  14764. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14765. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14766. break;
  14767. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14768. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14769. break;
  14770. }
  14771. }
  14772. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14773. }
  14774. return true;
  14775. };
  14776. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14777. if (channel < 0 || !uniform) {
  14778. return;
  14779. }
  14780. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14781. this._textureUnits = new Int32Array(textures.length);
  14782. }
  14783. for (var i = 0; i < textures.length; i++) {
  14784. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14785. }
  14786. this._gl.uniform1iv(uniform, this._textureUnits);
  14787. for (var index = 0; index < textures.length; index++) {
  14788. this._setTexture(this._textureUnits[index], textures[index], true);
  14789. }
  14790. };
  14791. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14792. var internalTexture = texture.getInternalTexture();
  14793. if (!internalTexture) {
  14794. return;
  14795. }
  14796. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14797. var value = texture.anisotropicFilteringLevel;
  14798. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14799. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14800. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14801. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14802. }
  14803. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14804. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14805. internalTexture._cachedAnisotropicFilteringLevel = value;
  14806. }
  14807. };
  14808. Engine.prototype.readPixels = function (x, y, width, height) {
  14809. var data = new Uint8Array(height * width * 4);
  14810. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14811. return data;
  14812. };
  14813. /**
  14814. * Add an externaly attached data from its key.
  14815. * This method call will fail and return false, if such key already exists.
  14816. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14817. * @param key the unique key that identifies the data
  14818. * @param data the data object to associate to the key for this Engine instance
  14819. * @return true if no such key were already present and the data was added successfully, false otherwise
  14820. */
  14821. Engine.prototype.addExternalData = function (key, data) {
  14822. if (!this._externalData) {
  14823. this._externalData = new BABYLON.StringDictionary();
  14824. }
  14825. return this._externalData.add(key, data);
  14826. };
  14827. /**
  14828. * Get an externaly attached data from its key
  14829. * @param key the unique key that identifies the data
  14830. * @return the associated data, if present (can be null), or undefined if not present
  14831. */
  14832. Engine.prototype.getExternalData = function (key) {
  14833. if (!this._externalData) {
  14834. this._externalData = new BABYLON.StringDictionary();
  14835. }
  14836. return this._externalData.get(key);
  14837. };
  14838. /**
  14839. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14840. * @param key the unique key that identifies the data
  14841. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14842. * @return the associated data, can be null if the factory returned null.
  14843. */
  14844. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14845. if (!this._externalData) {
  14846. this._externalData = new BABYLON.StringDictionary();
  14847. }
  14848. return this._externalData.getOrAddWithFactory(key, factory);
  14849. };
  14850. /**
  14851. * Remove an externaly attached data from the Engine instance
  14852. * @param key the unique key that identifies the data
  14853. * @return true if the data was successfully removed, false if it doesn't exist
  14854. */
  14855. Engine.prototype.removeExternalData = function (key) {
  14856. if (!this._externalData) {
  14857. this._externalData = new BABYLON.StringDictionary();
  14858. }
  14859. return this._externalData.remove(key);
  14860. };
  14861. Engine.prototype.unbindAllAttributes = function () {
  14862. if (this._mustWipeVertexAttributes) {
  14863. this._mustWipeVertexAttributes = false;
  14864. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14865. this._gl.disableVertexAttribArray(i);
  14866. this._vertexAttribArraysEnabled[i] = false;
  14867. this._currentBufferPointers[i].active = false;
  14868. }
  14869. return;
  14870. }
  14871. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14872. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14873. continue;
  14874. }
  14875. this._gl.disableVertexAttribArray(i);
  14876. this._vertexAttribArraysEnabled[i] = false;
  14877. this._currentBufferPointers[i].active = false;
  14878. }
  14879. };
  14880. Engine.prototype.releaseEffects = function () {
  14881. for (var name in this._compiledEffects) {
  14882. this._deleteProgram(this._compiledEffects[name]._program);
  14883. }
  14884. this._compiledEffects = {};
  14885. };
  14886. // Dispose
  14887. Engine.prototype.dispose = function () {
  14888. this.hideLoadingUI();
  14889. this.stopRenderLoop();
  14890. // Release postProcesses
  14891. while (this.postProcesses.length) {
  14892. this.postProcesses[0].dispose();
  14893. }
  14894. // Empty texture
  14895. if (this._emptyTexture) {
  14896. this._releaseTexture(this._emptyTexture);
  14897. this._emptyTexture = null;
  14898. }
  14899. if (this._emptyCubeTexture) {
  14900. this._releaseTexture(this._emptyCubeTexture);
  14901. this._emptyCubeTexture = null;
  14902. }
  14903. // Rescale PP
  14904. if (this._rescalePostProcess) {
  14905. this._rescalePostProcess.dispose();
  14906. }
  14907. // Release scenes
  14908. while (this.scenes.length) {
  14909. this.scenes[0].dispose();
  14910. }
  14911. // Release audio engine
  14912. if (Engine.audioEngine) {
  14913. Engine.audioEngine.dispose();
  14914. }
  14915. // Release effects
  14916. this.releaseEffects();
  14917. // Unbind
  14918. this.unbindAllAttributes();
  14919. if (this._dummyFramebuffer) {
  14920. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14921. }
  14922. //WebVR
  14923. this.disableVR();
  14924. // Events
  14925. if (BABYLON.Tools.IsWindowObjectExist()) {
  14926. window.removeEventListener("blur", this._onBlur);
  14927. window.removeEventListener("focus", this._onFocus);
  14928. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14929. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14930. if (this._renderingCanvas) {
  14931. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14932. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14933. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14934. if (!this._doNotHandleContextLost) {
  14935. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14936. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14937. }
  14938. }
  14939. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14940. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14941. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14942. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14943. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14944. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14945. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14946. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14947. if (this._onVrDisplayConnect) {
  14948. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14949. if (this._onVrDisplayDisconnect) {
  14950. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14951. }
  14952. if (this._onVrDisplayPresentChange) {
  14953. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14954. }
  14955. this._onVrDisplayConnect = null;
  14956. this._onVrDisplayDisconnect = null;
  14957. }
  14958. }
  14959. // Remove from Instances
  14960. var index = Engine.Instances.indexOf(this);
  14961. if (index >= 0) {
  14962. Engine.Instances.splice(index, 1);
  14963. }
  14964. this._workingCanvas = null;
  14965. this._workingContext = null;
  14966. this._currentBufferPointers = [];
  14967. this._renderingCanvas = null;
  14968. this._currentProgram = null;
  14969. this.onResizeObservable.clear();
  14970. this.onCanvasBlurObservable.clear();
  14971. this.onCanvasFocusObservable.clear();
  14972. this.onCanvasPointerOutObservable.clear();
  14973. this.onBeginFrameObservable.clear();
  14974. this.onEndFrameObservable.clear();
  14975. BABYLON.Effect.ResetCache();
  14976. // Abort active requests
  14977. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14978. var request = _a[_i];
  14979. request.abort();
  14980. }
  14981. };
  14982. // Loading screen
  14983. Engine.prototype.displayLoadingUI = function () {
  14984. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14985. return;
  14986. }
  14987. var loadingScreen = this.loadingScreen;
  14988. if (loadingScreen) {
  14989. loadingScreen.displayLoadingUI();
  14990. }
  14991. };
  14992. Engine.prototype.hideLoadingUI = function () {
  14993. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14994. return;
  14995. }
  14996. var loadingScreen = this.loadingScreen;
  14997. if (loadingScreen) {
  14998. loadingScreen.hideLoadingUI();
  14999. }
  15000. };
  15001. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15002. get: function () {
  15003. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15004. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15005. return this._loadingScreen;
  15006. },
  15007. set: function (loadingScreen) {
  15008. this._loadingScreen = loadingScreen;
  15009. },
  15010. enumerable: true,
  15011. configurable: true
  15012. });
  15013. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15014. set: function (text) {
  15015. this.loadingScreen.loadingUIText = text;
  15016. },
  15017. enumerable: true,
  15018. configurable: true
  15019. });
  15020. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15021. set: function (color) {
  15022. this.loadingScreen.loadingUIBackgroundColor = color;
  15023. },
  15024. enumerable: true,
  15025. configurable: true
  15026. });
  15027. Engine.prototype.attachContextLostEvent = function (callback) {
  15028. if (this._renderingCanvas) {
  15029. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15030. }
  15031. };
  15032. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15033. if (this._renderingCanvas) {
  15034. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15035. }
  15036. };
  15037. Engine.prototype.getVertexShaderSource = function (program) {
  15038. var shaders = this._gl.getAttachedShaders(program);
  15039. if (!shaders) {
  15040. return null;
  15041. }
  15042. return this._gl.getShaderSource(shaders[0]);
  15043. };
  15044. Engine.prototype.getFragmentShaderSource = function (program) {
  15045. var shaders = this._gl.getAttachedShaders(program);
  15046. if (!shaders) {
  15047. return null;
  15048. }
  15049. return this._gl.getShaderSource(shaders[1]);
  15050. };
  15051. Engine.prototype.getError = function () {
  15052. return this._gl.getError();
  15053. };
  15054. // FPS
  15055. Engine.prototype.getFps = function () {
  15056. return this._fps;
  15057. };
  15058. Engine.prototype.getDeltaTime = function () {
  15059. return this._deltaTime;
  15060. };
  15061. Engine.prototype._measureFps = function () {
  15062. this._performanceMonitor.sampleFrame();
  15063. this._fps = this._performanceMonitor.averageFPS;
  15064. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15065. };
  15066. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15067. if (faceIndex === void 0) { faceIndex = -1; }
  15068. var gl = this._gl;
  15069. if (!this._dummyFramebuffer) {
  15070. var dummy = gl.createFramebuffer();
  15071. if (!dummy) {
  15072. throw new Error("Unable to create dummy framebuffer");
  15073. }
  15074. this._dummyFramebuffer = dummy;
  15075. }
  15076. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15077. if (faceIndex > -1) {
  15078. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15079. }
  15080. else {
  15081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15082. }
  15083. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15084. var buffer;
  15085. switch (readType) {
  15086. case gl.UNSIGNED_BYTE:
  15087. buffer = new Uint8Array(4 * width * height);
  15088. readType = gl.UNSIGNED_BYTE;
  15089. break;
  15090. default:
  15091. buffer = new Float32Array(4 * width * height);
  15092. readType = gl.FLOAT;
  15093. break;
  15094. }
  15095. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15096. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15097. return buffer;
  15098. };
  15099. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15100. if (this._webGLVersion > 1) {
  15101. return this._caps.colorBufferFloat;
  15102. }
  15103. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15104. };
  15105. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15106. if (this._webGLVersion > 1) {
  15107. return this._caps.colorBufferFloat;
  15108. }
  15109. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15110. };
  15111. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15112. Engine.prototype._canRenderToFramebuffer = function (type) {
  15113. var gl = this._gl;
  15114. //clear existing errors
  15115. while (gl.getError() !== gl.NO_ERROR) { }
  15116. var successful = true;
  15117. var texture = gl.createTexture();
  15118. gl.bindTexture(gl.TEXTURE_2D, texture);
  15119. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15122. var fb = gl.createFramebuffer();
  15123. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15125. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15126. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15127. successful = successful && (gl.getError() === gl.NO_ERROR);
  15128. //try render by clearing frame buffer's color buffer
  15129. if (successful) {
  15130. gl.clear(gl.COLOR_BUFFER_BIT);
  15131. successful = successful && (gl.getError() === gl.NO_ERROR);
  15132. }
  15133. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15134. if (successful) {
  15135. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15136. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15137. var readFormat = gl.RGBA;
  15138. var readType = gl.UNSIGNED_BYTE;
  15139. var buffer = new Uint8Array(4);
  15140. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15141. successful = successful && (gl.getError() === gl.NO_ERROR);
  15142. }
  15143. //clean up
  15144. gl.deleteTexture(texture);
  15145. gl.deleteFramebuffer(fb);
  15146. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15147. //clear accumulated errors
  15148. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15149. return successful;
  15150. };
  15151. Engine.prototype._getWebGLTextureType = function (type) {
  15152. if (type === Engine.TEXTURETYPE_FLOAT) {
  15153. return this._gl.FLOAT;
  15154. }
  15155. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15156. // Add Half Float Constant.
  15157. return this._gl.HALF_FLOAT_OES;
  15158. }
  15159. return this._gl.UNSIGNED_BYTE;
  15160. };
  15161. ;
  15162. /** @ignore */
  15163. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15164. if (this._webGLVersion === 1) {
  15165. return this._gl.RGBA;
  15166. }
  15167. if (type === Engine.TEXTURETYPE_FLOAT) {
  15168. if (format) {
  15169. switch (format) {
  15170. case Engine.TEXTUREFORMAT_R32F:
  15171. return this._gl.R32F;
  15172. case Engine.TEXTUREFORMAT_RG32F:
  15173. return this._gl.RG32F;
  15174. case Engine.TEXTUREFORMAT_RGB32F:
  15175. return this._gl.RGB32F;
  15176. }
  15177. }
  15178. return this._gl.RGBA32F;
  15179. }
  15180. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15181. return this._gl.RGBA16F;
  15182. }
  15183. return this._gl.RGBA;
  15184. };
  15185. ;
  15186. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15187. if (type === Engine.TEXTURETYPE_FLOAT) {
  15188. return this._gl.RGBA32F;
  15189. }
  15190. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15191. return this._gl.RGBA16F;
  15192. }
  15193. return this._gl.RGBA8;
  15194. };
  15195. ;
  15196. Engine.prototype.createQuery = function () {
  15197. return this._gl.createQuery();
  15198. };
  15199. Engine.prototype.deleteQuery = function (query) {
  15200. this._gl.deleteQuery(query);
  15201. return this;
  15202. };
  15203. Engine.prototype.isQueryResultAvailable = function (query) {
  15204. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15205. };
  15206. Engine.prototype.getQueryResult = function (query) {
  15207. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15208. };
  15209. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15210. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15211. this._gl.beginQuery(glAlgorithm, query);
  15212. return this;
  15213. };
  15214. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15215. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15216. this._gl.endQuery(glAlgorithm);
  15217. return this;
  15218. };
  15219. /* Time queries */
  15220. Engine.prototype._createTimeQuery = function () {
  15221. var timerQuery = this._caps.timerQuery;
  15222. if (timerQuery.createQueryEXT) {
  15223. return timerQuery.createQueryEXT();
  15224. }
  15225. return this.createQuery();
  15226. };
  15227. Engine.prototype._deleteTimeQuery = function (query) {
  15228. var timerQuery = this._caps.timerQuery;
  15229. if (timerQuery.deleteQueryEXT) {
  15230. timerQuery.deleteQueryEXT(query);
  15231. return;
  15232. }
  15233. this.deleteQuery(query);
  15234. };
  15235. Engine.prototype._getTimeQueryResult = function (query) {
  15236. var timerQuery = this._caps.timerQuery;
  15237. if (timerQuery.getQueryObjectEXT) {
  15238. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15239. }
  15240. return this.getQueryResult(query);
  15241. };
  15242. Engine.prototype._getTimeQueryAvailability = function (query) {
  15243. var timerQuery = this._caps.timerQuery;
  15244. if (timerQuery.getQueryObjectEXT) {
  15245. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15246. }
  15247. return this.isQueryResultAvailable(query);
  15248. };
  15249. Engine.prototype.startTimeQuery = function () {
  15250. var timerQuery = this._caps.timerQuery;
  15251. if (!timerQuery) {
  15252. return null;
  15253. }
  15254. var token = new BABYLON._TimeToken();
  15255. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15256. if (this._caps.canUseTimestampForTimerQuery) {
  15257. token._startTimeQuery = this._createTimeQuery();
  15258. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15259. }
  15260. else {
  15261. if (this._currentNonTimestampToken) {
  15262. return this._currentNonTimestampToken;
  15263. }
  15264. token._timeElapsedQuery = this._createTimeQuery();
  15265. if (timerQuery.beginQueryEXT) {
  15266. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15267. }
  15268. else {
  15269. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15270. }
  15271. this._currentNonTimestampToken = token;
  15272. }
  15273. return token;
  15274. };
  15275. Engine.prototype.endTimeQuery = function (token) {
  15276. var timerQuery = this._caps.timerQuery;
  15277. if (!timerQuery || !token) {
  15278. return -1;
  15279. }
  15280. if (this._caps.canUseTimestampForTimerQuery) {
  15281. if (!token._startTimeQuery) {
  15282. return -1;
  15283. }
  15284. if (!token._endTimeQuery) {
  15285. token._endTimeQuery = this._createTimeQuery();
  15286. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15287. }
  15288. }
  15289. else if (!token._timeElapsedQueryEnded) {
  15290. if (!token._timeElapsedQuery) {
  15291. return -1;
  15292. }
  15293. if (timerQuery.endQueryEXT) {
  15294. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15295. }
  15296. else {
  15297. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15298. }
  15299. token._timeElapsedQueryEnded = true;
  15300. }
  15301. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15302. var available = false;
  15303. if (token._endTimeQuery) {
  15304. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15305. }
  15306. else if (token._timeElapsedQuery) {
  15307. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15308. }
  15309. if (available && !disjoint) {
  15310. var result = 0;
  15311. if (this._caps.canUseTimestampForTimerQuery) {
  15312. if (!token._startTimeQuery || !token._endTimeQuery) {
  15313. return -1;
  15314. }
  15315. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15316. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15317. result = timeEnd - timeStart;
  15318. this._deleteTimeQuery(token._startTimeQuery);
  15319. this._deleteTimeQuery(token._endTimeQuery);
  15320. token._startTimeQuery = null;
  15321. token._endTimeQuery = null;
  15322. }
  15323. else {
  15324. if (!token._timeElapsedQuery) {
  15325. return -1;
  15326. }
  15327. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15328. this._deleteTimeQuery(token._timeElapsedQuery);
  15329. token._timeElapsedQuery = null;
  15330. token._timeElapsedQueryEnded = false;
  15331. this._currentNonTimestampToken = null;
  15332. }
  15333. return result;
  15334. }
  15335. return -1;
  15336. };
  15337. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15338. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15339. };
  15340. // Transform feedback
  15341. Engine.prototype.createTransformFeedback = function () {
  15342. return this._gl.createTransformFeedback();
  15343. };
  15344. Engine.prototype.deleteTransformFeedback = function (value) {
  15345. this._gl.deleteTransformFeedback(value);
  15346. };
  15347. Engine.prototype.bindTransformFeedback = function (value) {
  15348. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15349. };
  15350. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15351. if (usePoints === void 0) { usePoints = true; }
  15352. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15353. };
  15354. Engine.prototype.endTransformFeedback = function () {
  15355. this._gl.endTransformFeedback();
  15356. };
  15357. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15358. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15359. };
  15360. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15361. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15362. };
  15363. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15364. var _this = this;
  15365. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15366. this._activeRequests.push(request);
  15367. request.onCompleteObservable.add(function (request) {
  15368. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15369. });
  15370. return request;
  15371. };
  15372. /** @ignore */
  15373. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15374. var _this = this;
  15375. return new Promise(function (resolve, reject) {
  15376. _this._loadFile(url, function (data) {
  15377. resolve(data);
  15378. }, undefined, database, useArrayBuffer, function (request, exception) {
  15379. reject(exception);
  15380. });
  15381. });
  15382. };
  15383. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15384. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15385. var onload = function (data) {
  15386. loadedFiles[index] = data;
  15387. loadedFiles._internalCount++;
  15388. if (loadedFiles._internalCount === 6) {
  15389. onfinish(loadedFiles);
  15390. }
  15391. };
  15392. var onerror = function (request, exception) {
  15393. if (onErrorCallBack && request) {
  15394. onErrorCallBack(request.status + " " + request.statusText, exception);
  15395. }
  15396. };
  15397. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15398. };
  15399. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15400. if (onError === void 0) { onError = null; }
  15401. var loadedFiles = [];
  15402. loadedFiles._internalCount = 0;
  15403. for (var index = 0; index < 6; index++) {
  15404. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15405. }
  15406. };
  15407. // Statics
  15408. Engine.isSupported = function () {
  15409. try {
  15410. var tempcanvas = document.createElement("canvas");
  15411. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15412. return gl != null && !!window.WebGLRenderingContext;
  15413. }
  15414. catch (e) {
  15415. return false;
  15416. }
  15417. };
  15418. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15419. Engine.ExceptionList = [
  15420. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15421. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15422. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15423. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15424. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15425. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15426. ];
  15427. Engine.Instances = new Array();
  15428. // Const statics
  15429. Engine._ALPHA_DISABLE = 0;
  15430. Engine._ALPHA_ADD = 1;
  15431. Engine._ALPHA_COMBINE = 2;
  15432. Engine._ALPHA_SUBTRACT = 3;
  15433. Engine._ALPHA_MULTIPLY = 4;
  15434. Engine._ALPHA_MAXIMIZED = 5;
  15435. Engine._ALPHA_ONEONE = 6;
  15436. Engine._ALPHA_PREMULTIPLIED = 7;
  15437. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15438. Engine._ALPHA_INTERPOLATE = 9;
  15439. Engine._ALPHA_SCREENMODE = 10;
  15440. Engine._DELAYLOADSTATE_NONE = 0;
  15441. Engine._DELAYLOADSTATE_LOADED = 1;
  15442. Engine._DELAYLOADSTATE_LOADING = 2;
  15443. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15444. Engine._TEXTUREFORMAT_ALPHA = 0;
  15445. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15446. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15447. Engine._TEXTUREFORMAT_RGB = 4;
  15448. Engine._TEXTUREFORMAT_RGBA = 5;
  15449. Engine._TEXTUREFORMAT_R32F = 6;
  15450. Engine._TEXTUREFORMAT_RG32F = 7;
  15451. Engine._TEXTUREFORMAT_RGB32F = 8;
  15452. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15453. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15454. Engine._TEXTURETYPE_FLOAT = 1;
  15455. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15456. // Depht or Stencil test Constants.
  15457. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15458. 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.
  15459. 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.
  15460. 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.
  15461. 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.
  15462. 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.
  15463. 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.
  15464. 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.
  15465. // Stencil Actions Constants.
  15466. Engine._KEEP = 0x1E00;
  15467. Engine._REPLACE = 0x1E01;
  15468. Engine._INCR = 0x1E02;
  15469. Engine._DECR = 0x1E03;
  15470. Engine._INVERT = 0x150A;
  15471. Engine._INCR_WRAP = 0x8507;
  15472. Engine._DECR_WRAP = 0x8508;
  15473. // Texture rescaling mode
  15474. Engine._SCALEMODE_FLOOR = 1;
  15475. Engine._SCALEMODE_NEAREST = 2;
  15476. Engine._SCALEMODE_CEILING = 3;
  15477. // Updatable statics so stick with vars here
  15478. Engine.CollisionsEpsilon = 0.001;
  15479. Engine.CodeRepository = "src/";
  15480. Engine.ShadersRepository = "src/Shaders/";
  15481. return Engine;
  15482. }());
  15483. BABYLON.Engine = Engine;
  15484. })(BABYLON || (BABYLON = {}));
  15485. //# sourceMappingURL=babylon.engine.js.map
  15486. var BABYLON;
  15487. (function (BABYLON) {
  15488. /**
  15489. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15490. */
  15491. var Node = /** @class */ (function () {
  15492. /**
  15493. * Creates a new Node
  15494. * @param {string} name - the name and id to be given to this node
  15495. * @param {BABYLON.Scene} the scene this node will be added to
  15496. */
  15497. function Node(name, scene) {
  15498. if (scene === void 0) { scene = null; }
  15499. /**
  15500. * Gets or sets a string used to store user defined state for the node
  15501. */
  15502. this.state = "";
  15503. /**
  15504. * Gets or sets an object used to store user defined information for the node
  15505. */
  15506. this.metadata = null;
  15507. /**
  15508. * Gets or sets a boolean used to define if the node must be serialized
  15509. */
  15510. this.doNotSerialize = false;
  15511. /** @ignore */
  15512. this._isDisposed = false;
  15513. /**
  15514. * Gets a list of {BABYLON.Animation} associated with the node
  15515. */
  15516. this.animations = new Array();
  15517. this._ranges = {};
  15518. this._isEnabled = true;
  15519. this._isReady = true;
  15520. /** @ignore */
  15521. this._currentRenderId = -1;
  15522. this._parentRenderId = -1;
  15523. this._animationPropertiesOverride = null;
  15524. /**
  15525. * An event triggered when the mesh is disposed
  15526. * @type {BABYLON.Observable}
  15527. */
  15528. this.onDisposeObservable = new BABYLON.Observable();
  15529. // Behaviors
  15530. this._behaviors = new Array();
  15531. this.name = name;
  15532. this.id = name;
  15533. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15534. this.uniqueId = this._scene.getUniqueId();
  15535. this._initCache();
  15536. }
  15537. /**
  15538. * Gets a boolean indicating if the node has been disposed
  15539. * @returns true if the node was disposed
  15540. */
  15541. Node.prototype.isDisposed = function () {
  15542. return this._isDisposed;
  15543. };
  15544. Object.defineProperty(Node.prototype, "parent", {
  15545. get: function () {
  15546. return this._parentNode;
  15547. },
  15548. /**
  15549. * Gets or sets the parent of the node
  15550. */
  15551. set: function (parent) {
  15552. if (this._parentNode === parent) {
  15553. return;
  15554. }
  15555. // Remove self from list of children of parent
  15556. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15557. var index = this._parentNode._children.indexOf(this);
  15558. if (index !== -1) {
  15559. this._parentNode._children.splice(index, 1);
  15560. }
  15561. }
  15562. // Store new parent
  15563. this._parentNode = parent;
  15564. // Add as child to new parent
  15565. if (this._parentNode) {
  15566. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15567. this._parentNode._children = new Array();
  15568. }
  15569. this._parentNode._children.push(this);
  15570. }
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15576. /**
  15577. * Gets or sets the animation properties override
  15578. */
  15579. get: function () {
  15580. return this._animationPropertiesOverride;
  15581. },
  15582. set: function (value) {
  15583. this._animationPropertiesOverride = value;
  15584. },
  15585. enumerable: true,
  15586. configurable: true
  15587. });
  15588. /**
  15589. * Gets a string idenfifying the name of the class
  15590. * @returns "Node" string
  15591. */
  15592. Node.prototype.getClassName = function () {
  15593. return "Node";
  15594. };
  15595. Object.defineProperty(Node.prototype, "onDispose", {
  15596. /**
  15597. * Sets a callback that will be raised when the node will be disposed
  15598. */
  15599. set: function (callback) {
  15600. if (this._onDisposeObserver) {
  15601. this.onDisposeObservable.remove(this._onDisposeObserver);
  15602. }
  15603. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15604. },
  15605. enumerable: true,
  15606. configurable: true
  15607. });
  15608. /**
  15609. * Gets the scene of the node
  15610. * @returns a {BABYLON.Scene}
  15611. */
  15612. Node.prototype.getScene = function () {
  15613. return this._scene;
  15614. };
  15615. /**
  15616. * Gets the engine of the node
  15617. * @returns a {BABYLON.Engine}
  15618. */
  15619. Node.prototype.getEngine = function () {
  15620. return this._scene.getEngine();
  15621. };
  15622. /**
  15623. * Attach a behavior to the node
  15624. * @see http://doc.babylonjs.com/features/behaviour
  15625. * @param behavior defines the behavior to attach
  15626. * @returns the current Node
  15627. */
  15628. Node.prototype.addBehavior = function (behavior) {
  15629. var _this = this;
  15630. var index = this._behaviors.indexOf(behavior);
  15631. if (index !== -1) {
  15632. return this;
  15633. }
  15634. behavior.init();
  15635. if (this._scene.isLoading) {
  15636. // We defer the attach when the scene will be loaded
  15637. var observer = this._scene.onDataLoadedObservable.add(function () {
  15638. behavior.attach(_this);
  15639. setTimeout(function () {
  15640. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15641. _this._scene.onDataLoadedObservable.remove(observer);
  15642. }, 0);
  15643. });
  15644. }
  15645. else {
  15646. behavior.attach(this);
  15647. }
  15648. this._behaviors.push(behavior);
  15649. return this;
  15650. };
  15651. /**
  15652. * Remove an attached behavior
  15653. * @see http://doc.babylonjs.com/features/behaviour
  15654. * @param behavior defines the behavior to attach
  15655. * @returns the current Node
  15656. */
  15657. Node.prototype.removeBehavior = function (behavior) {
  15658. var index = this._behaviors.indexOf(behavior);
  15659. if (index === -1) {
  15660. return this;
  15661. }
  15662. this._behaviors[index].detach();
  15663. this._behaviors.splice(index, 1);
  15664. return this;
  15665. };
  15666. Object.defineProperty(Node.prototype, "behaviors", {
  15667. /**
  15668. * Gets the list of attached behaviors
  15669. * @see http://doc.babylonjs.com/features/behaviour
  15670. */
  15671. get: function () {
  15672. return this._behaviors;
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. /**
  15678. * Gets an attached behavior by name
  15679. * @param name defines the name of the behavior to look for
  15680. * @see http://doc.babylonjs.com/features/behaviour
  15681. * @returns null if behavior was not found else the requested behavior
  15682. */
  15683. Node.prototype.getBehaviorByName = function (name) {
  15684. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15685. var behavior = _a[_i];
  15686. if (behavior.name === name) {
  15687. return behavior;
  15688. }
  15689. }
  15690. return null;
  15691. };
  15692. /**
  15693. * Returns the world matrix of the node
  15694. * @returns a matrix containing the node's world matrix
  15695. */
  15696. Node.prototype.getWorldMatrix = function () {
  15697. return BABYLON.Matrix.Identity();
  15698. };
  15699. // override it in derived class if you add new variables to the cache
  15700. // and call the parent class method
  15701. /** @ignore */
  15702. Node.prototype._initCache = function () {
  15703. this._cache = {};
  15704. this._cache.parent = undefined;
  15705. };
  15706. /** @ignore */
  15707. Node.prototype.updateCache = function (force) {
  15708. if (!force && this.isSynchronized())
  15709. return;
  15710. this._cache.parent = this.parent;
  15711. this._updateCache();
  15712. };
  15713. // override it in derived class if you add new variables to the cache
  15714. // and call the parent class method if !ignoreParentClass
  15715. /** @ignore */
  15716. Node.prototype._updateCache = function (ignoreParentClass) {
  15717. };
  15718. // override it in derived class if you add new variables to the cache
  15719. /** @ignore */
  15720. Node.prototype._isSynchronized = function () {
  15721. return true;
  15722. };
  15723. /** @ignore */
  15724. Node.prototype._markSyncedWithParent = function () {
  15725. if (this.parent) {
  15726. this._parentRenderId = this.parent._currentRenderId;
  15727. }
  15728. };
  15729. /** @ignore */
  15730. Node.prototype.isSynchronizedWithParent = function () {
  15731. if (!this.parent) {
  15732. return true;
  15733. }
  15734. if (this._parentRenderId !== this.parent._currentRenderId) {
  15735. return false;
  15736. }
  15737. return this.parent.isSynchronized();
  15738. };
  15739. /** @ignore */
  15740. Node.prototype.isSynchronized = function (updateCache) {
  15741. var check = this.hasNewParent();
  15742. check = check || !this.isSynchronizedWithParent();
  15743. check = check || !this._isSynchronized();
  15744. if (updateCache)
  15745. this.updateCache(true);
  15746. return !check;
  15747. };
  15748. /** @ignore */
  15749. Node.prototype.hasNewParent = function (update) {
  15750. if (this._cache.parent === this.parent)
  15751. return false;
  15752. if (update)
  15753. this._cache.parent = this.parent;
  15754. return true;
  15755. };
  15756. /**
  15757. * Is this node ready to be used/rendered
  15758. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15759. * @return true if the node is ready
  15760. */
  15761. Node.prototype.isReady = function (completeCheck) {
  15762. if (completeCheck === void 0) { completeCheck = false; }
  15763. return this._isReady;
  15764. };
  15765. /**
  15766. * Is this node enabled?
  15767. * 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
  15768. * @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
  15769. * @return whether this node (and its parent) is enabled
  15770. * @see setEnabled
  15771. */
  15772. Node.prototype.isEnabled = function (checkAncestors) {
  15773. if (checkAncestors === void 0) { checkAncestors = true; }
  15774. if (checkAncestors === false) {
  15775. return this._isEnabled;
  15776. }
  15777. if (this._isEnabled === false) {
  15778. return false;
  15779. }
  15780. if (this.parent !== undefined && this.parent !== null) {
  15781. return this.parent.isEnabled(checkAncestors);
  15782. }
  15783. return true;
  15784. };
  15785. /**
  15786. * Set the enabled state of this node
  15787. * @param value defines the new enabled state
  15788. * @see isEnabled
  15789. */
  15790. Node.prototype.setEnabled = function (value) {
  15791. this._isEnabled = value;
  15792. };
  15793. /**
  15794. * Is this node a descendant of the given node?
  15795. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15796. * @param ancestor defines the parent node to inspect
  15797. * @see parent
  15798. * @returns a boolean indicating if this node is a descendant of the given node
  15799. */
  15800. Node.prototype.isDescendantOf = function (ancestor) {
  15801. if (this.parent) {
  15802. if (this.parent === ancestor) {
  15803. return true;
  15804. }
  15805. return this.parent.isDescendantOf(ancestor);
  15806. }
  15807. return false;
  15808. };
  15809. /** @ignore */
  15810. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15811. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15812. if (!this._children) {
  15813. return;
  15814. }
  15815. for (var index = 0; index < this._children.length; index++) {
  15816. var item = this._children[index];
  15817. if (!predicate || predicate(item)) {
  15818. results.push(item);
  15819. }
  15820. if (!directDescendantsOnly) {
  15821. item._getDescendants(results, false, predicate);
  15822. }
  15823. }
  15824. };
  15825. /**
  15826. * Will return all nodes that have this node as ascendant
  15827. * @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
  15828. * @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
  15829. * @return all children nodes of all types
  15830. */
  15831. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15832. var results = new Array();
  15833. this._getDescendants(results, directDescendantsOnly, predicate);
  15834. return results;
  15835. };
  15836. /**
  15837. * Get all child-meshes of this node
  15838. * @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
  15839. * @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
  15840. * @returns an array of {BABYLON.AbstractMesh}
  15841. */
  15842. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15843. var results = [];
  15844. this._getDescendants(results, directDescendantsOnly, function (node) {
  15845. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15846. });
  15847. return results;
  15848. };
  15849. /**
  15850. * Get all child-transformNodes of this node
  15851. * @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
  15852. * @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
  15853. * @returns an array of {BABYLON.TransformNode}
  15854. */
  15855. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15856. var results = [];
  15857. this._getDescendants(results, directDescendantsOnly, function (node) {
  15858. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15859. });
  15860. return results;
  15861. };
  15862. /**
  15863. * Get all direct children of this node
  15864. * @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
  15865. * @returns an array of {BABYLON.Node}
  15866. */
  15867. Node.prototype.getChildren = function (predicate) {
  15868. return this.getDescendants(true, predicate);
  15869. };
  15870. /** @ignore */
  15871. Node.prototype._setReady = function (state) {
  15872. if (state === this._isReady) {
  15873. return;
  15874. }
  15875. if (!state) {
  15876. this._isReady = false;
  15877. return;
  15878. }
  15879. this._isReady = true;
  15880. if (this.onReady) {
  15881. this.onReady(this);
  15882. }
  15883. };
  15884. /**
  15885. * Get an animation by name
  15886. * @param name defines the name of the animation to look for
  15887. * @returns null if not found else the requested animation
  15888. */
  15889. Node.prototype.getAnimationByName = function (name) {
  15890. for (var i = 0; i < this.animations.length; i++) {
  15891. var animation = this.animations[i];
  15892. if (animation.name === name) {
  15893. return animation;
  15894. }
  15895. }
  15896. return null;
  15897. };
  15898. /**
  15899. * Creates an animation range for this node
  15900. * @param name defines the name of the range
  15901. * @param from defines the starting key
  15902. * @param to defines the end key
  15903. */
  15904. Node.prototype.createAnimationRange = function (name, from, to) {
  15905. // check name not already in use
  15906. if (!this._ranges[name]) {
  15907. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15908. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15909. if (this.animations[i]) {
  15910. this.animations[i].createRange(name, from, to);
  15911. }
  15912. }
  15913. }
  15914. };
  15915. /**
  15916. * Delete a specific animation range
  15917. * @param name defines the name of the range to delete
  15918. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15919. */
  15920. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15921. if (deleteFrames === void 0) { deleteFrames = true; }
  15922. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15923. if (this.animations[i]) {
  15924. this.animations[i].deleteRange(name, deleteFrames);
  15925. }
  15926. }
  15927. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15928. };
  15929. /**
  15930. * Get an animation range by name
  15931. * @param name defines the name of the animation range to look for
  15932. * @returns null if not found else the requested animation range
  15933. */
  15934. Node.prototype.getAnimationRange = function (name) {
  15935. return this._ranges[name];
  15936. };
  15937. /**
  15938. * Will start the animation sequence
  15939. * @param name defines the range frames for animation sequence
  15940. * @param loop defines if the animation should loop (false by default)
  15941. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15942. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15943. * @returns the object created for this animation. If range does not exist, it will return null
  15944. */
  15945. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15946. var range = this.getAnimationRange(name);
  15947. if (!range) {
  15948. return null;
  15949. }
  15950. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15951. };
  15952. /**
  15953. * Serialize animation ranges into a JSON compatible object
  15954. * @returns serialization object
  15955. */
  15956. Node.prototype.serializeAnimationRanges = function () {
  15957. var serializationRanges = [];
  15958. for (var name in this._ranges) {
  15959. var localRange = this._ranges[name];
  15960. if (!localRange) {
  15961. continue;
  15962. }
  15963. var range = {};
  15964. range.name = name;
  15965. range.from = localRange.from;
  15966. range.to = localRange.to;
  15967. serializationRanges.push(range);
  15968. }
  15969. return serializationRanges;
  15970. };
  15971. /**
  15972. * Computes the world matrix of the node
  15973. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15974. * @returns the world matrix
  15975. */
  15976. Node.prototype.computeWorldMatrix = function (force) {
  15977. return BABYLON.Matrix.Identity();
  15978. };
  15979. /**
  15980. * Releases resources associated with this node.
  15981. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15982. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15983. */
  15984. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15985. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15986. if (!doNotRecurse) {
  15987. var nodes = this.getDescendants(true);
  15988. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15989. var node = nodes_1[_i];
  15990. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15991. }
  15992. }
  15993. else {
  15994. var transformNodes = this.getChildTransformNodes(true);
  15995. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15996. var transformNode = transformNodes_1[_a];
  15997. transformNode.parent = null;
  15998. transformNode.computeWorldMatrix(true);
  15999. }
  16000. }
  16001. this.parent = null;
  16002. // Callback
  16003. this.onDisposeObservable.notifyObservers(this);
  16004. this.onDisposeObservable.clear();
  16005. // Behaviors
  16006. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16007. var behavior = _c[_b];
  16008. behavior.detach();
  16009. }
  16010. this._behaviors = [];
  16011. this._isDisposed = true;
  16012. };
  16013. /**
  16014. * Parse animation range data from a serialization object and store them into a given node
  16015. * @param node defines where to store the animation ranges
  16016. * @param parsedNode defines the serialization object to read data from
  16017. * @param scene defines the hosting scene
  16018. */
  16019. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16020. if (parsedNode.ranges) {
  16021. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16022. var data = parsedNode.ranges[index];
  16023. node.createAnimationRange(data.name, data.from, data.to);
  16024. }
  16025. }
  16026. };
  16027. __decorate([
  16028. BABYLON.serialize()
  16029. ], Node.prototype, "name", void 0);
  16030. __decorate([
  16031. BABYLON.serialize()
  16032. ], Node.prototype, "id", void 0);
  16033. __decorate([
  16034. BABYLON.serialize()
  16035. ], Node.prototype, "uniqueId", void 0);
  16036. __decorate([
  16037. BABYLON.serialize()
  16038. ], Node.prototype, "state", void 0);
  16039. __decorate([
  16040. BABYLON.serialize()
  16041. ], Node.prototype, "metadata", void 0);
  16042. return Node;
  16043. }());
  16044. BABYLON.Node = Node;
  16045. })(BABYLON || (BABYLON = {}));
  16046. //# sourceMappingURL=babylon.node.js.map
  16047. var BABYLON;
  16048. (function (BABYLON) {
  16049. var BoundingSphere = /** @class */ (function () {
  16050. function BoundingSphere(minimum, maximum) {
  16051. this.minimum = minimum;
  16052. this.maximum = maximum;
  16053. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16054. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16055. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16056. this.radius = distance * 0.5;
  16057. this.centerWorld = BABYLON.Vector3.Zero();
  16058. this._update(BABYLON.Matrix.Identity());
  16059. }
  16060. // Methods
  16061. BoundingSphere.prototype._update = function (world) {
  16062. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16063. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16064. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16065. };
  16066. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16067. for (var i = 0; i < 6; i++) {
  16068. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16069. return false;
  16070. }
  16071. return true;
  16072. };
  16073. BoundingSphere.prototype.intersectsPoint = function (point) {
  16074. var x = this.centerWorld.x - point.x;
  16075. var y = this.centerWorld.y - point.y;
  16076. var z = this.centerWorld.z - point.z;
  16077. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16078. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16079. return false;
  16080. return true;
  16081. };
  16082. // Statics
  16083. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16084. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16085. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16086. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16087. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16088. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16089. return false;
  16090. return true;
  16091. };
  16092. return BoundingSphere;
  16093. }());
  16094. BABYLON.BoundingSphere = BoundingSphere;
  16095. })(BABYLON || (BABYLON = {}));
  16096. //# sourceMappingURL=babylon.boundingSphere.js.map
  16097. var BABYLON;
  16098. (function (BABYLON) {
  16099. var BoundingBox = /** @class */ (function () {
  16100. function BoundingBox(minimum, maximum) {
  16101. this.minimum = minimum;
  16102. this.maximum = maximum;
  16103. this.vectors = new Array();
  16104. this.vectorsWorld = new Array();
  16105. // Bounding vectors
  16106. this.vectors.push(this.minimum.clone());
  16107. this.vectors.push(this.maximum.clone());
  16108. this.vectors.push(this.minimum.clone());
  16109. this.vectors[2].x = this.maximum.x;
  16110. this.vectors.push(this.minimum.clone());
  16111. this.vectors[3].y = this.maximum.y;
  16112. this.vectors.push(this.minimum.clone());
  16113. this.vectors[4].z = this.maximum.z;
  16114. this.vectors.push(this.maximum.clone());
  16115. this.vectors[5].z = this.minimum.z;
  16116. this.vectors.push(this.maximum.clone());
  16117. this.vectors[6].x = this.minimum.x;
  16118. this.vectors.push(this.maximum.clone());
  16119. this.vectors[7].y = this.minimum.y;
  16120. // OBB
  16121. this.center = this.maximum.add(this.minimum).scale(0.5);
  16122. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16123. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16124. // World
  16125. for (var index = 0; index < this.vectors.length; index++) {
  16126. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16127. }
  16128. this.minimumWorld = BABYLON.Vector3.Zero();
  16129. this.maximumWorld = BABYLON.Vector3.Zero();
  16130. this.centerWorld = BABYLON.Vector3.Zero();
  16131. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16132. this._update(BABYLON.Matrix.Identity());
  16133. }
  16134. // Methods
  16135. BoundingBox.prototype.getWorldMatrix = function () {
  16136. return this._worldMatrix;
  16137. };
  16138. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16139. this._worldMatrix.copyFrom(matrix);
  16140. return this;
  16141. };
  16142. BoundingBox.prototype._update = function (world) {
  16143. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16144. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16145. for (var index = 0; index < this.vectors.length; index++) {
  16146. var v = this.vectorsWorld[index];
  16147. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16148. if (v.x < this.minimumWorld.x)
  16149. this.minimumWorld.x = v.x;
  16150. if (v.y < this.minimumWorld.y)
  16151. this.minimumWorld.y = v.y;
  16152. if (v.z < this.minimumWorld.z)
  16153. this.minimumWorld.z = v.z;
  16154. if (v.x > this.maximumWorld.x)
  16155. this.maximumWorld.x = v.x;
  16156. if (v.y > this.maximumWorld.y)
  16157. this.maximumWorld.y = v.y;
  16158. if (v.z > this.maximumWorld.z)
  16159. this.maximumWorld.z = v.z;
  16160. }
  16161. // Extend
  16162. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16163. this.extendSizeWorld.scaleInPlace(0.5);
  16164. // OBB
  16165. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16166. this.centerWorld.scaleInPlace(0.5);
  16167. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16168. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16169. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16170. this._worldMatrix = world;
  16171. };
  16172. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16173. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16174. };
  16175. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16176. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16177. };
  16178. BoundingBox.prototype.intersectsPoint = function (point) {
  16179. var delta = -BABYLON.Epsilon;
  16180. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16181. return false;
  16182. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16183. return false;
  16184. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16185. return false;
  16186. return true;
  16187. };
  16188. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16189. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16190. };
  16191. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16192. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16193. return false;
  16194. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16195. return false;
  16196. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16197. return false;
  16198. return true;
  16199. };
  16200. // Statics
  16201. BoundingBox.Intersects = function (box0, box1) {
  16202. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16203. return false;
  16204. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16205. return false;
  16206. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16207. return false;
  16208. return true;
  16209. };
  16210. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16211. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16212. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16213. return (num <= (sphereRadius * sphereRadius));
  16214. };
  16215. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16216. for (var p = 0; p < 6; p++) {
  16217. for (var i = 0; i < 8; i++) {
  16218. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16219. return false;
  16220. }
  16221. }
  16222. }
  16223. return true;
  16224. };
  16225. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16226. for (var p = 0; p < 6; p++) {
  16227. var inCount = 8;
  16228. for (var i = 0; i < 8; i++) {
  16229. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16230. --inCount;
  16231. }
  16232. else {
  16233. break;
  16234. }
  16235. }
  16236. if (inCount === 0)
  16237. return false;
  16238. }
  16239. return true;
  16240. };
  16241. return BoundingBox;
  16242. }());
  16243. BABYLON.BoundingBox = BoundingBox;
  16244. })(BABYLON || (BABYLON = {}));
  16245. //# sourceMappingURL=babylon.boundingBox.js.map
  16246. var BABYLON;
  16247. (function (BABYLON) {
  16248. var computeBoxExtents = function (axis, box) {
  16249. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16250. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16251. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16252. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16253. var r = r0 + r1 + r2;
  16254. return {
  16255. min: p - r,
  16256. max: p + r
  16257. };
  16258. };
  16259. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16260. var axisOverlap = function (axis, box0, box1) {
  16261. var result0 = computeBoxExtents(axis, box0);
  16262. var result1 = computeBoxExtents(axis, box1);
  16263. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16264. };
  16265. var BoundingInfo = /** @class */ (function () {
  16266. function BoundingInfo(minimum, maximum) {
  16267. this.minimum = minimum;
  16268. this.maximum = maximum;
  16269. this._isLocked = false;
  16270. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16271. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16272. }
  16273. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16274. get: function () {
  16275. return this._isLocked;
  16276. },
  16277. set: function (value) {
  16278. this._isLocked = value;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. // Methods
  16284. BoundingInfo.prototype.update = function (world) {
  16285. if (this._isLocked) {
  16286. return;
  16287. }
  16288. this.boundingBox._update(world);
  16289. this.boundingSphere._update(world);
  16290. };
  16291. /**
  16292. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16293. * @param center New center of the bounding info
  16294. * @param extend New extend of the bounding info
  16295. */
  16296. BoundingInfo.prototype.centerOn = function (center, extend) {
  16297. this.minimum = center.subtract(extend);
  16298. this.maximum = center.add(extend);
  16299. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16300. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16301. return this;
  16302. };
  16303. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16304. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16305. return false;
  16306. return this.boundingBox.isInFrustum(frustumPlanes);
  16307. };
  16308. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16309. /**
  16310. * Gets the world distance between the min and max points of the bounding box
  16311. */
  16312. get: function () {
  16313. var boundingBox = this.boundingBox;
  16314. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16315. return size.length();
  16316. },
  16317. enumerable: true,
  16318. configurable: true
  16319. });
  16320. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16321. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16322. };
  16323. BoundingInfo.prototype._checkCollision = function (collider) {
  16324. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16325. };
  16326. BoundingInfo.prototype.intersectsPoint = function (point) {
  16327. if (!this.boundingSphere.centerWorld) {
  16328. return false;
  16329. }
  16330. if (!this.boundingSphere.intersectsPoint(point)) {
  16331. return false;
  16332. }
  16333. if (!this.boundingBox.intersectsPoint(point)) {
  16334. return false;
  16335. }
  16336. return true;
  16337. };
  16338. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16339. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16340. return false;
  16341. }
  16342. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16343. return false;
  16344. }
  16345. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16346. return false;
  16347. }
  16348. if (!precise) {
  16349. return true;
  16350. }
  16351. var box0 = this.boundingBox;
  16352. var box1 = boundingInfo.boundingBox;
  16353. if (!axisOverlap(box0.directions[0], box0, box1))
  16354. return false;
  16355. if (!axisOverlap(box0.directions[1], box0, box1))
  16356. return false;
  16357. if (!axisOverlap(box0.directions[2], box0, box1))
  16358. return false;
  16359. if (!axisOverlap(box1.directions[0], box0, box1))
  16360. return false;
  16361. if (!axisOverlap(box1.directions[1], box0, box1))
  16362. return false;
  16363. if (!axisOverlap(box1.directions[2], box0, box1))
  16364. return false;
  16365. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16366. return false;
  16367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16368. return false;
  16369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16370. return false;
  16371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16372. return false;
  16373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16374. return false;
  16375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16376. return false;
  16377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16378. return false;
  16379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16380. return false;
  16381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16382. return false;
  16383. return true;
  16384. };
  16385. return BoundingInfo;
  16386. }());
  16387. BABYLON.BoundingInfo = BoundingInfo;
  16388. })(BABYLON || (BABYLON = {}));
  16389. //# sourceMappingURL=babylon.boundingInfo.js.map
  16390. var BABYLON;
  16391. (function (BABYLON) {
  16392. var TransformNode = /** @class */ (function (_super) {
  16393. __extends(TransformNode, _super);
  16394. function TransformNode(name, scene, isPure) {
  16395. if (scene === void 0) { scene = null; }
  16396. if (isPure === void 0) { isPure = true; }
  16397. var _this = _super.call(this, name, scene) || this;
  16398. // Properties
  16399. _this._rotation = BABYLON.Vector3.Zero();
  16400. _this._scaling = BABYLON.Vector3.One();
  16401. _this._isDirty = false;
  16402. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16403. _this.scalingDeterminant = 1;
  16404. _this.infiniteDistance = false;
  16405. _this.position = BABYLON.Vector3.Zero();
  16406. _this._localWorld = BABYLON.Matrix.Zero();
  16407. _this._worldMatrix = BABYLON.Matrix.Zero();
  16408. _this._worldMatrixDeterminant = 0;
  16409. _this._absolutePosition = BABYLON.Vector3.Zero();
  16410. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16411. _this._postMultiplyPivotMatrix = false;
  16412. _this._isWorldMatrixFrozen = false;
  16413. /**
  16414. * An event triggered after the world matrix is updated
  16415. * @type {BABYLON.Observable}
  16416. */
  16417. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16418. _this._nonUniformScaling = false;
  16419. if (isPure) {
  16420. _this.getScene().addTransformNode(_this);
  16421. }
  16422. return _this;
  16423. }
  16424. /**
  16425. * Gets a string idenfifying the name of the class
  16426. * @returns "TransformNode" string
  16427. */
  16428. TransformNode.prototype.getClassName = function () {
  16429. return "TransformNode";
  16430. };
  16431. Object.defineProperty(TransformNode.prototype, "rotation", {
  16432. /**
  16433. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16434. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16435. * Default : (0.0, 0.0, 0.0)
  16436. */
  16437. get: function () {
  16438. return this._rotation;
  16439. },
  16440. set: function (newRotation) {
  16441. this._rotation = newRotation;
  16442. },
  16443. enumerable: true,
  16444. configurable: true
  16445. });
  16446. Object.defineProperty(TransformNode.prototype, "scaling", {
  16447. /**
  16448. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16449. * Default : (1.0, 1.0, 1.0)
  16450. */
  16451. get: function () {
  16452. return this._scaling;
  16453. },
  16454. /**
  16455. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16456. * Default : (1.0, 1.0, 1.0)
  16457. */
  16458. set: function (newScaling) {
  16459. this._scaling = newScaling;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16465. /**
  16466. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16467. * It's null by default.
  16468. * 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)
  16469. */
  16470. get: function () {
  16471. return this._rotationQuaternion;
  16472. },
  16473. set: function (quaternion) {
  16474. this._rotationQuaternion = quaternion;
  16475. //reset the rotation vector.
  16476. if (quaternion && this.rotation.length()) {
  16477. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16478. }
  16479. },
  16480. enumerable: true,
  16481. configurable: true
  16482. });
  16483. /**
  16484. * Returns the latest update of the World matrix
  16485. * Returns a Matrix.
  16486. */
  16487. TransformNode.prototype.getWorldMatrix = function () {
  16488. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16489. this.computeWorldMatrix();
  16490. }
  16491. return this._worldMatrix;
  16492. };
  16493. /**
  16494. * Returns the latest update of the World matrix determinant.
  16495. */
  16496. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16497. return this._worldMatrixDeterminant;
  16498. };
  16499. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16500. /**
  16501. * Returns directly the latest state of the mesh World matrix.
  16502. * A Matrix is returned.
  16503. */
  16504. get: function () {
  16505. return this._worldMatrix;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. /**
  16511. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16512. * Returns the AbstractMesh.
  16513. */
  16514. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16515. this._poseMatrix.copyFrom(matrix);
  16516. return this;
  16517. };
  16518. /**
  16519. * Returns the mesh Pose matrix.
  16520. * Returned object : Matrix
  16521. */
  16522. TransformNode.prototype.getPoseMatrix = function () {
  16523. return this._poseMatrix;
  16524. };
  16525. TransformNode.prototype._isSynchronized = function () {
  16526. if (this._isDirty) {
  16527. return false;
  16528. }
  16529. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16530. return false;
  16531. if (this._cache.pivotMatrixUpdated) {
  16532. return false;
  16533. }
  16534. if (this.infiniteDistance) {
  16535. return false;
  16536. }
  16537. if (!this._cache.position.equals(this.position))
  16538. return false;
  16539. if (this.rotationQuaternion) {
  16540. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16541. return false;
  16542. }
  16543. if (!this._cache.rotation.equals(this.rotation))
  16544. return false;
  16545. if (!this._cache.scaling.equals(this.scaling))
  16546. return false;
  16547. return true;
  16548. };
  16549. TransformNode.prototype._initCache = function () {
  16550. _super.prototype._initCache.call(this);
  16551. this._cache.localMatrixUpdated = false;
  16552. this._cache.position = BABYLON.Vector3.Zero();
  16553. this._cache.scaling = BABYLON.Vector3.Zero();
  16554. this._cache.rotation = BABYLON.Vector3.Zero();
  16555. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16556. this._cache.billboardMode = -1;
  16557. };
  16558. TransformNode.prototype.markAsDirty = function (property) {
  16559. if (property === "rotation") {
  16560. this.rotationQuaternion = null;
  16561. }
  16562. this._currentRenderId = Number.MAX_VALUE;
  16563. this._isDirty = true;
  16564. return this;
  16565. };
  16566. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16567. /**
  16568. * Returns the current mesh absolute position.
  16569. * Retuns a Vector3.
  16570. */
  16571. get: function () {
  16572. return this._absolutePosition;
  16573. },
  16574. enumerable: true,
  16575. configurable: true
  16576. });
  16577. /**
  16578. * Sets a new matrix to apply before all other transformation
  16579. * @param matrix defines the transform matrix
  16580. * @returns the current TransformNode
  16581. */
  16582. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16583. return this.setPivotMatrix(matrix, false);
  16584. };
  16585. /**
  16586. * Sets a new pivot matrix to the current node
  16587. * @param matrix defines the new pivot matrix to use
  16588. * @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
  16589. * @returns the current TransformNode
  16590. */
  16591. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16592. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16593. this._pivotMatrix = matrix.clone();
  16594. this._cache.pivotMatrixUpdated = true;
  16595. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16596. if (this._postMultiplyPivotMatrix) {
  16597. if (!this._pivotMatrixInverse) {
  16598. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16599. }
  16600. else {
  16601. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16602. }
  16603. }
  16604. return this;
  16605. };
  16606. /**
  16607. * Returns the mesh pivot matrix.
  16608. * Default : Identity.
  16609. * A Matrix is returned.
  16610. */
  16611. TransformNode.prototype.getPivotMatrix = function () {
  16612. return this._pivotMatrix;
  16613. };
  16614. /**
  16615. * Prevents the World matrix to be computed any longer.
  16616. * Returns the AbstractMesh.
  16617. */
  16618. TransformNode.prototype.freezeWorldMatrix = function () {
  16619. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16620. this.computeWorldMatrix(true);
  16621. this._isWorldMatrixFrozen = true;
  16622. return this;
  16623. };
  16624. /**
  16625. * Allows back the World matrix computation.
  16626. * Returns the AbstractMesh.
  16627. */
  16628. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16629. this._isWorldMatrixFrozen = false;
  16630. this.computeWorldMatrix(true);
  16631. return this;
  16632. };
  16633. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16634. /**
  16635. * True if the World matrix has been frozen.
  16636. * Returns a boolean.
  16637. */
  16638. get: function () {
  16639. return this._isWorldMatrixFrozen;
  16640. },
  16641. enumerable: true,
  16642. configurable: true
  16643. });
  16644. /**
  16645. * Retuns the mesh absolute position in the World.
  16646. * Returns a Vector3.
  16647. */
  16648. TransformNode.prototype.getAbsolutePosition = function () {
  16649. this.computeWorldMatrix();
  16650. return this._absolutePosition;
  16651. };
  16652. /**
  16653. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16654. * Returns the AbstractMesh.
  16655. */
  16656. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16657. if (!absolutePosition) {
  16658. return this;
  16659. }
  16660. var absolutePositionX;
  16661. var absolutePositionY;
  16662. var absolutePositionZ;
  16663. if (absolutePosition.x === undefined) {
  16664. if (arguments.length < 3) {
  16665. return this;
  16666. }
  16667. absolutePositionX = arguments[0];
  16668. absolutePositionY = arguments[1];
  16669. absolutePositionZ = arguments[2];
  16670. }
  16671. else {
  16672. absolutePositionX = absolutePosition.x;
  16673. absolutePositionY = absolutePosition.y;
  16674. absolutePositionZ = absolutePosition.z;
  16675. }
  16676. if (this.parent) {
  16677. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16678. invertParentWorldMatrix.invert();
  16679. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16680. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16681. }
  16682. else {
  16683. this.position.x = absolutePositionX;
  16684. this.position.y = absolutePositionY;
  16685. this.position.z = absolutePositionZ;
  16686. }
  16687. return this;
  16688. };
  16689. /**
  16690. * Sets the mesh position in its local space.
  16691. * Returns the AbstractMesh.
  16692. */
  16693. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16694. this.computeWorldMatrix();
  16695. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16696. return this;
  16697. };
  16698. /**
  16699. * Returns the mesh position in the local space from the current World matrix values.
  16700. * Returns a new Vector3.
  16701. */
  16702. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16703. this.computeWorldMatrix();
  16704. var invLocalWorldMatrix = this._localWorld.clone();
  16705. invLocalWorldMatrix.invert();
  16706. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16707. };
  16708. /**
  16709. * Translates the mesh along the passed Vector3 in its local space.
  16710. * Returns the AbstractMesh.
  16711. */
  16712. TransformNode.prototype.locallyTranslate = function (vector3) {
  16713. this.computeWorldMatrix(true);
  16714. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16715. return this;
  16716. };
  16717. /**
  16718. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16719. * @param targetPoint the position (must be in same space as current mesh) to look at
  16720. * @param yawCor optional yaw (y-axis) correction in radians
  16721. * @param pitchCor optional pitch (x-axis) correction in radians
  16722. * @param rollCor optional roll (z-axis) correction in radians
  16723. * @param space the choosen space of the target
  16724. * @returns the TransformNode.
  16725. */
  16726. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16727. if (yawCor === void 0) { yawCor = 0; }
  16728. if (pitchCor === void 0) { pitchCor = 0; }
  16729. if (rollCor === void 0) { rollCor = 0; }
  16730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16731. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16732. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16733. targetPoint.subtractToRef(pos, dv);
  16734. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16735. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16736. var pitch = Math.atan2(dv.y, len);
  16737. if (this.rotationQuaternion) {
  16738. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16739. }
  16740. else {
  16741. this.rotation.x = pitch + pitchCor;
  16742. this.rotation.y = yaw + yawCor;
  16743. this.rotation.z = rollCor;
  16744. }
  16745. return this;
  16746. };
  16747. /**
  16748. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16749. * This Vector3 is expressed in the World space.
  16750. */
  16751. TransformNode.prototype.getDirection = function (localAxis) {
  16752. var result = BABYLON.Vector3.Zero();
  16753. this.getDirectionToRef(localAxis, result);
  16754. return result;
  16755. };
  16756. /**
  16757. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16758. * localAxis is expressed in the mesh local space.
  16759. * result is computed in the Wordl space from the mesh World matrix.
  16760. * Returns the AbstractMesh.
  16761. */
  16762. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16763. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16764. return this;
  16765. };
  16766. /**
  16767. * Sets a new pivot point to the current node
  16768. * @param point defines the new pivot point to use
  16769. * @param space defines if the point is in world or local space (local by default)
  16770. * @returns the current TransformNode
  16771. */
  16772. TransformNode.prototype.setPivotPoint = function (point, space) {
  16773. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16774. if (this.getScene().getRenderId() == 0) {
  16775. this.computeWorldMatrix(true);
  16776. }
  16777. var wm = this.getWorldMatrix();
  16778. if (space == BABYLON.Space.WORLD) {
  16779. var tmat = BABYLON.Tmp.Matrix[0];
  16780. wm.invertToRef(tmat);
  16781. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16782. }
  16783. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16784. };
  16785. /**
  16786. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16787. */
  16788. TransformNode.prototype.getPivotPoint = function () {
  16789. var point = BABYLON.Vector3.Zero();
  16790. this.getPivotPointToRef(point);
  16791. return point;
  16792. };
  16793. /**
  16794. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16795. * Returns the AbstractMesh.
  16796. */
  16797. TransformNode.prototype.getPivotPointToRef = function (result) {
  16798. result.x = -this._pivotMatrix.m[12];
  16799. result.y = -this._pivotMatrix.m[13];
  16800. result.z = -this._pivotMatrix.m[14];
  16801. return this;
  16802. };
  16803. /**
  16804. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16805. */
  16806. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16807. var point = BABYLON.Vector3.Zero();
  16808. this.getAbsolutePivotPointToRef(point);
  16809. return point;
  16810. };
  16811. /**
  16812. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16813. * Returns the AbstractMesh.
  16814. */
  16815. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16816. result.x = this._pivotMatrix.m[12];
  16817. result.y = this._pivotMatrix.m[13];
  16818. result.z = this._pivotMatrix.m[14];
  16819. this.getPivotPointToRef(result);
  16820. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16821. return this;
  16822. };
  16823. /**
  16824. * Defines the passed node as the parent of the current node.
  16825. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16826. * Returns the TransformNode.
  16827. */
  16828. TransformNode.prototype.setParent = function (node) {
  16829. if (node === null) {
  16830. var rotation = BABYLON.Tmp.Quaternion[0];
  16831. var position = BABYLON.Tmp.Vector3[0];
  16832. var scale = BABYLON.Tmp.Vector3[1];
  16833. if (this.parent && this.parent.computeWorldMatrix) {
  16834. this.parent.computeWorldMatrix(true);
  16835. }
  16836. this.computeWorldMatrix(true);
  16837. this.getWorldMatrix().decompose(scale, rotation, position);
  16838. if (this.rotationQuaternion) {
  16839. this.rotationQuaternion.copyFrom(rotation);
  16840. }
  16841. else {
  16842. rotation.toEulerAnglesToRef(this.rotation);
  16843. }
  16844. this.scaling.x = scale.x;
  16845. this.scaling.y = scale.y;
  16846. this.scaling.z = scale.z;
  16847. this.position.x = position.x;
  16848. this.position.y = position.y;
  16849. this.position.z = position.z;
  16850. }
  16851. else {
  16852. var rotation = BABYLON.Tmp.Quaternion[0];
  16853. var position = BABYLON.Tmp.Vector3[0];
  16854. var scale = BABYLON.Tmp.Vector3[1];
  16855. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16856. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16857. this.computeWorldMatrix(true);
  16858. node.computeWorldMatrix(true);
  16859. node.getWorldMatrix().invertToRef(invParentMatrix);
  16860. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16861. diffMatrix.decompose(scale, rotation, position);
  16862. if (this.rotationQuaternion) {
  16863. this.rotationQuaternion.copyFrom(rotation);
  16864. }
  16865. else {
  16866. rotation.toEulerAnglesToRef(this.rotation);
  16867. }
  16868. this.position.x = position.x;
  16869. this.position.y = position.y;
  16870. this.position.z = position.z;
  16871. this.scaling.x = scale.x;
  16872. this.scaling.y = scale.y;
  16873. this.scaling.z = scale.z;
  16874. }
  16875. this.parent = node;
  16876. return this;
  16877. };
  16878. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16879. get: function () {
  16880. return this._nonUniformScaling;
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16886. if (this._nonUniformScaling === value) {
  16887. return false;
  16888. }
  16889. this._nonUniformScaling = true;
  16890. return true;
  16891. };
  16892. /**
  16893. * Attach the current TransformNode to another TransformNode associated with a bone
  16894. * @param bone Bone affecting the TransformNode
  16895. * @param affectedTransformNode TransformNode associated with the bone
  16896. */
  16897. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16898. this._transformToBoneReferal = affectedTransformNode;
  16899. this.parent = bone;
  16900. if (bone.getWorldMatrix().determinant() < 0) {
  16901. this.scalingDeterminant *= -1;
  16902. }
  16903. return this;
  16904. };
  16905. TransformNode.prototype.detachFromBone = function () {
  16906. if (!this.parent) {
  16907. return this;
  16908. }
  16909. if (this.parent.getWorldMatrix().determinant() < 0) {
  16910. this.scalingDeterminant *= -1;
  16911. }
  16912. this._transformToBoneReferal = null;
  16913. this.parent = null;
  16914. return this;
  16915. };
  16916. /**
  16917. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16918. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16919. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16920. * The passed axis is also normalized.
  16921. * Returns the AbstractMesh.
  16922. */
  16923. TransformNode.prototype.rotate = function (axis, amount, space) {
  16924. axis.normalize();
  16925. if (!this.rotationQuaternion) {
  16926. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16927. this.rotation = BABYLON.Vector3.Zero();
  16928. }
  16929. var rotationQuaternion;
  16930. if (!space || space === BABYLON.Space.LOCAL) {
  16931. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16932. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16933. }
  16934. else {
  16935. if (this.parent) {
  16936. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16937. invertParentWorldMatrix.invert();
  16938. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16939. }
  16940. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16941. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16942. }
  16943. return this;
  16944. };
  16945. /**
  16946. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16947. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16948. * The passed axis is also normalized.
  16949. * Returns the AbstractMesh.
  16950. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16951. */
  16952. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16953. axis.normalize();
  16954. if (!this.rotationQuaternion) {
  16955. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16956. this.rotation.copyFromFloats(0, 0, 0);
  16957. }
  16958. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16959. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16960. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16961. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16962. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16963. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16964. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16965. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16966. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16967. return this;
  16968. };
  16969. /**
  16970. * Translates the mesh along the axis vector for the passed distance in the given space.
  16971. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16972. * Returns the AbstractMesh.
  16973. */
  16974. TransformNode.prototype.translate = function (axis, distance, space) {
  16975. var displacementVector = axis.scale(distance);
  16976. if (!space || space === BABYLON.Space.LOCAL) {
  16977. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16978. this.setPositionWithLocalVector(tempV3);
  16979. }
  16980. else {
  16981. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16982. }
  16983. return this;
  16984. };
  16985. /**
  16986. * Adds a rotation step to the mesh current rotation.
  16987. * x, y, z are Euler angles expressed in radians.
  16988. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16989. * This means this rotation is made in the mesh local space only.
  16990. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16991. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16992. * ```javascript
  16993. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16994. * ```
  16995. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16996. * 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.
  16997. * Returns the AbstractMesh.
  16998. */
  16999. TransformNode.prototype.addRotation = function (x, y, z) {
  17000. var rotationQuaternion;
  17001. if (this.rotationQuaternion) {
  17002. rotationQuaternion = this.rotationQuaternion;
  17003. }
  17004. else {
  17005. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17006. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17007. }
  17008. var accumulation = BABYLON.Tmp.Quaternion[0];
  17009. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17010. rotationQuaternion.multiplyInPlace(accumulation);
  17011. if (!this.rotationQuaternion) {
  17012. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17013. }
  17014. return this;
  17015. };
  17016. /**
  17017. * Computes the mesh World matrix and returns it.
  17018. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17019. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17020. * If the parameter `force`is set to `true`, the actual computation is done.
  17021. * Returns the mesh World Matrix.
  17022. */
  17023. TransformNode.prototype.computeWorldMatrix = function (force) {
  17024. if (this._isWorldMatrixFrozen) {
  17025. return this._worldMatrix;
  17026. }
  17027. if (!force && this.isSynchronized(true)) {
  17028. return this._worldMatrix;
  17029. }
  17030. this._cache.position.copyFrom(this.position);
  17031. this._cache.scaling.copyFrom(this.scaling);
  17032. this._cache.pivotMatrixUpdated = false;
  17033. this._cache.billboardMode = this.billboardMode;
  17034. this._currentRenderId = this.getScene().getRenderId();
  17035. this._isDirty = false;
  17036. // Scaling
  17037. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17038. // Rotation
  17039. //rotate, if quaternion is set and rotation was used
  17040. if (this.rotationQuaternion) {
  17041. var len = this.rotation.length();
  17042. if (len) {
  17043. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17044. this.rotation.copyFromFloats(0, 0, 0);
  17045. }
  17046. }
  17047. if (this.rotationQuaternion) {
  17048. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17049. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17050. }
  17051. else {
  17052. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17053. this._cache.rotation.copyFrom(this.rotation);
  17054. }
  17055. // Translation
  17056. var camera = this.getScene().activeCamera;
  17057. if (this.infiniteDistance && !this.parent && camera) {
  17058. var cameraWorldMatrix = camera.getWorldMatrix();
  17059. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17060. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17061. }
  17062. else {
  17063. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17064. }
  17065. // Composing transformations
  17066. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17067. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17068. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17069. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17070. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17071. // Need to decompose each rotation here
  17072. var currentPosition = BABYLON.Tmp.Vector3[3];
  17073. if (this.parent && this.parent.getWorldMatrix) {
  17074. if (this._transformToBoneReferal) {
  17075. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17076. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17077. }
  17078. else {
  17079. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17080. }
  17081. }
  17082. else {
  17083. currentPosition.copyFrom(this.position);
  17084. }
  17085. currentPosition.subtractInPlace(camera.globalPosition);
  17086. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17087. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17088. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17089. }
  17090. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17091. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17092. }
  17093. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17094. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17095. }
  17096. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17097. }
  17098. else {
  17099. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17100. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17101. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17102. }
  17103. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17104. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17105. }
  17106. // Local world
  17107. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17108. // Parent
  17109. if (this.parent && this.parent.getWorldMatrix) {
  17110. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17111. if (this._transformToBoneReferal) {
  17112. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17113. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17114. }
  17115. else {
  17116. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17117. }
  17118. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17119. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17120. this._worldMatrix.copyFrom(this._localWorld);
  17121. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17122. }
  17123. else {
  17124. if (this._transformToBoneReferal) {
  17125. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17126. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17127. }
  17128. else {
  17129. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17130. }
  17131. }
  17132. this._markSyncedWithParent();
  17133. }
  17134. else {
  17135. this._worldMatrix.copyFrom(this._localWorld);
  17136. }
  17137. // Post multiply inverse of pivotMatrix
  17138. if (this._postMultiplyPivotMatrix) {
  17139. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17140. }
  17141. // Normal matrix
  17142. if (this.scaling.isNonUniform) {
  17143. this._updateNonUniformScalingState(true);
  17144. }
  17145. else if (this.parent && this.parent._nonUniformScaling) {
  17146. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17147. }
  17148. else {
  17149. this._updateNonUniformScalingState(false);
  17150. }
  17151. this._afterComputeWorldMatrix();
  17152. // Absolute position
  17153. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17154. // Callbacks
  17155. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17156. if (!this._poseMatrix) {
  17157. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17158. }
  17159. // Cache the determinant
  17160. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17161. return this._worldMatrix;
  17162. };
  17163. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17164. };
  17165. /**
  17166. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17167. * @param func: callback function to add
  17168. *
  17169. * Returns the TransformNode.
  17170. */
  17171. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17172. this.onAfterWorldMatrixUpdateObservable.add(func);
  17173. return this;
  17174. };
  17175. /**
  17176. * Removes a registered callback function.
  17177. * Returns the TransformNode.
  17178. */
  17179. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17180. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17181. return this;
  17182. };
  17183. /**
  17184. * Clone the current transform node
  17185. * Returns the new transform node
  17186. * @param name Name of the new clone
  17187. * @param newParent New parent for the clone
  17188. * @param doNotCloneChildren Do not clone children hierarchy
  17189. */
  17190. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17191. var _this = this;
  17192. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17193. result.name = name;
  17194. result.id = name;
  17195. if (newParent) {
  17196. result.parent = newParent;
  17197. }
  17198. if (!doNotCloneChildren) {
  17199. // Children
  17200. var directDescendants = this.getDescendants(true);
  17201. for (var index = 0; index < directDescendants.length; index++) {
  17202. var child = directDescendants[index];
  17203. if (child.clone) {
  17204. child.clone(name + "." + child.name, result);
  17205. }
  17206. }
  17207. }
  17208. return result;
  17209. };
  17210. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17211. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17212. serializationObject.type = this.getClassName();
  17213. // Parent
  17214. if (this.parent) {
  17215. serializationObject.parentId = this.parent.id;
  17216. }
  17217. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17218. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17219. }
  17220. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17221. serializationObject.isEnabled = this.isEnabled();
  17222. // Parent
  17223. if (this.parent) {
  17224. serializationObject.parentId = this.parent.id;
  17225. }
  17226. return serializationObject;
  17227. };
  17228. // Statics
  17229. /**
  17230. * Returns a new TransformNode object parsed from the source provided.
  17231. * The parameter `parsedMesh` is the source.
  17232. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17233. */
  17234. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17235. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17236. if (BABYLON.Tags) {
  17237. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17238. }
  17239. if (parsedTransformNode.localMatrix) {
  17240. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17241. }
  17242. else if (parsedTransformNode.pivotMatrix) {
  17243. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17244. }
  17245. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17246. // Parent
  17247. if (parsedTransformNode.parentId) {
  17248. transformNode._waitingParentId = parsedTransformNode.parentId;
  17249. }
  17250. return transformNode;
  17251. };
  17252. /**
  17253. * Releases resources associated with this transform node.
  17254. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17255. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17256. */
  17257. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17258. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17259. // Animations
  17260. this.getScene().stopAnimation(this);
  17261. // Remove from scene
  17262. this.getScene().removeTransformNode(this);
  17263. this.onAfterWorldMatrixUpdateObservable.clear();
  17264. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17265. };
  17266. // Statics
  17267. TransformNode.BILLBOARDMODE_NONE = 0;
  17268. TransformNode.BILLBOARDMODE_X = 1;
  17269. TransformNode.BILLBOARDMODE_Y = 2;
  17270. TransformNode.BILLBOARDMODE_Z = 4;
  17271. TransformNode.BILLBOARDMODE_ALL = 7;
  17272. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17273. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17274. __decorate([
  17275. BABYLON.serializeAsVector3()
  17276. ], TransformNode.prototype, "_rotation", void 0);
  17277. __decorate([
  17278. BABYLON.serializeAsQuaternion()
  17279. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17280. __decorate([
  17281. BABYLON.serializeAsVector3()
  17282. ], TransformNode.prototype, "_scaling", void 0);
  17283. __decorate([
  17284. BABYLON.serialize()
  17285. ], TransformNode.prototype, "billboardMode", void 0);
  17286. __decorate([
  17287. BABYLON.serialize()
  17288. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17289. __decorate([
  17290. BABYLON.serialize()
  17291. ], TransformNode.prototype, "infiniteDistance", void 0);
  17292. __decorate([
  17293. BABYLON.serializeAsVector3()
  17294. ], TransformNode.prototype, "position", void 0);
  17295. return TransformNode;
  17296. }(BABYLON.Node));
  17297. BABYLON.TransformNode = TransformNode;
  17298. })(BABYLON || (BABYLON = {}));
  17299. //# sourceMappingURL=babylon.transformNode.js.map
  17300. var BABYLON;
  17301. (function (BABYLON) {
  17302. var AbstractMesh = /** @class */ (function (_super) {
  17303. __extends(AbstractMesh, _super);
  17304. // Constructor
  17305. function AbstractMesh(name, scene) {
  17306. if (scene === void 0) { scene = null; }
  17307. var _this = _super.call(this, name, scene, false) || this;
  17308. _this._facetNb = 0; // facet number
  17309. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17310. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17311. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17312. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17313. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17314. _this._subDiv = {
  17315. max: 1,
  17316. X: 1,
  17317. Y: 1,
  17318. Z: 1
  17319. };
  17320. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17321. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17322. // Events
  17323. /**
  17324. * An event triggered when this mesh collides with another one
  17325. * @type {BABYLON.Observable}
  17326. */
  17327. _this.onCollideObservable = new BABYLON.Observable();
  17328. /**
  17329. * An event triggered when the collision's position changes
  17330. * @type {BABYLON.Observable}
  17331. */
  17332. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17333. /**
  17334. * An event triggered when material is changed
  17335. * @type {BABYLON.Observable}
  17336. */
  17337. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17338. // Properties
  17339. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17340. /**
  17341. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17342. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17343. * or
  17344. * 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.
  17345. * for more info check WebGl documentations
  17346. */
  17347. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17348. /**
  17349. * 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:
  17350. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17351. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17352. * 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.
  17353. */
  17354. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17355. /**
  17356. * 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.
  17357. * The default value is -1 which means don't break the query and wait till the result.
  17358. */
  17359. _this.occlusionRetryCount = -1;
  17360. _this._occlusionInternalRetryCounter = 0;
  17361. _this._isOccluded = false;
  17362. _this._isOcclusionQueryInProgress = false;
  17363. _this._visibility = 1.0;
  17364. _this.alphaIndex = Number.MAX_VALUE;
  17365. _this.isVisible = true;
  17366. _this.isPickable = true;
  17367. _this.showBoundingBox = false;
  17368. _this.showSubMeshesBoundingBox = false;
  17369. _this.isBlocker = false;
  17370. _this.enablePointerMoveEvents = false;
  17371. _this.renderingGroupId = 0;
  17372. _this._receiveShadows = false;
  17373. _this.renderOutline = false;
  17374. _this.outlineColor = BABYLON.Color3.Red();
  17375. _this.outlineWidth = 0.02;
  17376. _this.renderOverlay = false;
  17377. _this.overlayColor = BABYLON.Color3.Red();
  17378. _this.overlayAlpha = 0.5;
  17379. _this._hasVertexAlpha = false;
  17380. _this._useVertexColors = true;
  17381. _this._computeBonesUsingShaders = true;
  17382. _this._numBoneInfluencers = 4;
  17383. _this._applyFog = true;
  17384. _this.useOctreeForRenderingSelection = true;
  17385. _this.useOctreeForPicking = true;
  17386. _this.useOctreeForCollisions = true;
  17387. _this._layerMask = 0x0FFFFFFF;
  17388. /**
  17389. * True if the mesh must be rendered in any case.
  17390. */
  17391. _this.alwaysSelectAsActiveMesh = false;
  17392. /**
  17393. * This scene's action manager
  17394. * @type {BABYLON.ActionManager}
  17395. */
  17396. _this.actionManager = null;
  17397. // Physics
  17398. _this.physicsImpostor = null;
  17399. // Collisions
  17400. _this._checkCollisions = false;
  17401. _this._collisionMask = -1;
  17402. _this._collisionGroup = -1;
  17403. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17404. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17405. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17406. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17407. // Edges
  17408. _this.edgesWidth = 1;
  17409. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17410. // Cache
  17411. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17412. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17413. _this._renderId = 0;
  17414. _this._intersectionsInProgress = new Array();
  17415. _this._unIndexed = false;
  17416. _this._lightSources = new Array();
  17417. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17418. if (collidedMesh === void 0) { collidedMesh = null; }
  17419. //TODO move this to the collision coordinator!
  17420. if (_this.getScene().workerCollisions)
  17421. newPosition.multiplyInPlace(_this._collider._radius);
  17422. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17423. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17424. _this.position.addInPlace(_this._diffPositionForCollisions);
  17425. }
  17426. if (collidedMesh) {
  17427. _this.onCollideObservable.notifyObservers(collidedMesh);
  17428. }
  17429. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17430. };
  17431. _this.getScene().addMesh(_this);
  17432. _this._resyncLightSources();
  17433. return _this;
  17434. }
  17435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17436. get: function () {
  17437. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17438. },
  17439. enumerable: true,
  17440. configurable: true
  17441. });
  17442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17443. get: function () {
  17444. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17445. },
  17446. enumerable: true,
  17447. configurable: true
  17448. });
  17449. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17450. get: function () {
  17451. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17457. get: function () {
  17458. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17459. },
  17460. enumerable: true,
  17461. configurable: true
  17462. });
  17463. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17464. get: function () {
  17465. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17471. /**
  17472. * Read-only : the number of facets in the mesh
  17473. */
  17474. get: function () {
  17475. return this._facetNb;
  17476. },
  17477. enumerable: true,
  17478. configurable: true
  17479. });
  17480. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17481. /**
  17482. * The number (integer) of subdivisions per axis in the partioning space
  17483. */
  17484. get: function () {
  17485. return this._partitioningSubdivisions;
  17486. },
  17487. set: function (nb) {
  17488. this._partitioningSubdivisions = nb;
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17494. /**
  17495. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17496. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17497. */
  17498. get: function () {
  17499. return this._partitioningBBoxRatio;
  17500. },
  17501. set: function (ratio) {
  17502. this._partitioningBBoxRatio = ratio;
  17503. },
  17504. enumerable: true,
  17505. configurable: true
  17506. });
  17507. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17508. /**
  17509. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17510. * Works only for updatable meshes.
  17511. * Doesn't work with multi-materials.
  17512. */
  17513. get: function () {
  17514. return this._facetDepthSort;
  17515. },
  17516. set: function (sort) {
  17517. this._facetDepthSort = sort;
  17518. },
  17519. enumerable: true,
  17520. configurable: true
  17521. });
  17522. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17523. /**
  17524. * The location (Vector3) where the facet depth sort must be computed from.
  17525. * By default, the active camera position.
  17526. * Used only when facet depth sort is enabled.
  17527. */
  17528. get: function () {
  17529. return this._facetDepthSortFrom;
  17530. },
  17531. set: function (location) {
  17532. this._facetDepthSortFrom = location;
  17533. },
  17534. enumerable: true,
  17535. configurable: true
  17536. });
  17537. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17538. /**
  17539. * Read-only boolean : is the feature facetData enabled ?
  17540. */
  17541. get: function () {
  17542. return this._facetDataEnabled;
  17543. },
  17544. enumerable: true,
  17545. configurable: true
  17546. });
  17547. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17548. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17549. return false;
  17550. }
  17551. this._markSubMeshesAsMiscDirty();
  17552. return true;
  17553. };
  17554. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17555. set: function (callback) {
  17556. if (this._onCollideObserver) {
  17557. this.onCollideObservable.remove(this._onCollideObserver);
  17558. }
  17559. this._onCollideObserver = this.onCollideObservable.add(callback);
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17565. set: function (callback) {
  17566. if (this._onCollisionPositionChangeObserver) {
  17567. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17568. }
  17569. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17575. /**
  17576. * 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.
  17577. */
  17578. get: function () {
  17579. return this._isOccluded;
  17580. },
  17581. set: function (value) {
  17582. this._isOccluded = value;
  17583. },
  17584. enumerable: true,
  17585. configurable: true
  17586. });
  17587. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17588. /**
  17589. * Flag to check the progress status of the query
  17590. */
  17591. get: function () {
  17592. return this._isOcclusionQueryInProgress;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17598. /**
  17599. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17600. */
  17601. get: function () {
  17602. return this._visibility;
  17603. },
  17604. /**
  17605. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17606. */
  17607. set: function (value) {
  17608. if (this._visibility === value) {
  17609. return;
  17610. }
  17611. this._visibility = value;
  17612. this._markSubMeshesAsMiscDirty();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. Object.defineProperty(AbstractMesh.prototype, "material", {
  17618. get: function () {
  17619. return this._material;
  17620. },
  17621. set: function (value) {
  17622. if (this._material === value) {
  17623. return;
  17624. }
  17625. this._material = value;
  17626. if (this.onMaterialChangedObservable.hasObservers) {
  17627. this.onMaterialChangedObservable.notifyObservers(this);
  17628. }
  17629. if (!this.subMeshes) {
  17630. return;
  17631. }
  17632. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17633. var subMesh = _a[_i];
  17634. subMesh.setEffect(null);
  17635. }
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17641. get: function () {
  17642. return this._receiveShadows;
  17643. },
  17644. set: function (value) {
  17645. if (this._receiveShadows === value) {
  17646. return;
  17647. }
  17648. this._receiveShadows = value;
  17649. this._markSubMeshesAsLightDirty();
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17655. get: function () {
  17656. return this._hasVertexAlpha;
  17657. },
  17658. set: function (value) {
  17659. if (this._hasVertexAlpha === value) {
  17660. return;
  17661. }
  17662. this._hasVertexAlpha = value;
  17663. this._markSubMeshesAsAttributesDirty();
  17664. this._markSubMeshesAsMiscDirty();
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17670. get: function () {
  17671. return this._useVertexColors;
  17672. },
  17673. set: function (value) {
  17674. if (this._useVertexColors === value) {
  17675. return;
  17676. }
  17677. this._useVertexColors = value;
  17678. this._markSubMeshesAsAttributesDirty();
  17679. },
  17680. enumerable: true,
  17681. configurable: true
  17682. });
  17683. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17684. get: function () {
  17685. return this._computeBonesUsingShaders;
  17686. },
  17687. set: function (value) {
  17688. if (this._computeBonesUsingShaders === value) {
  17689. return;
  17690. }
  17691. this._computeBonesUsingShaders = value;
  17692. this._markSubMeshesAsAttributesDirty();
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17698. get: function () {
  17699. return this._numBoneInfluencers;
  17700. },
  17701. set: function (value) {
  17702. if (this._numBoneInfluencers === value) {
  17703. return;
  17704. }
  17705. this._numBoneInfluencers = value;
  17706. this._markSubMeshesAsAttributesDirty();
  17707. },
  17708. enumerable: true,
  17709. configurable: true
  17710. });
  17711. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17712. get: function () {
  17713. return this._applyFog;
  17714. },
  17715. set: function (value) {
  17716. if (this._applyFog === value) {
  17717. return;
  17718. }
  17719. this._applyFog = value;
  17720. this._markSubMeshesAsMiscDirty();
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17726. get: function () {
  17727. return this._layerMask;
  17728. },
  17729. set: function (value) {
  17730. if (value === this._layerMask) {
  17731. return;
  17732. }
  17733. this._layerMask = value;
  17734. this._resyncLightSources();
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17740. get: function () {
  17741. return this._collisionMask;
  17742. },
  17743. set: function (mask) {
  17744. this._collisionMask = !isNaN(mask) ? mask : -1;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17750. get: function () {
  17751. return this._collisionGroup;
  17752. },
  17753. set: function (mask) {
  17754. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17760. get: function () {
  17761. return null;
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17767. get: function () {
  17768. return this._skeleton;
  17769. },
  17770. set: function (value) {
  17771. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17772. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17773. }
  17774. if (value && value.needInitialSkinMatrix) {
  17775. value._registerMeshWithPoseMatrix(this);
  17776. }
  17777. this._skeleton = value;
  17778. if (!this._skeleton) {
  17779. this._bonesTransformMatrices = null;
  17780. }
  17781. this._markSubMeshesAsAttributesDirty();
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. /**
  17787. * Returns the string "AbstractMesh"
  17788. */
  17789. AbstractMesh.prototype.getClassName = function () {
  17790. return "AbstractMesh";
  17791. };
  17792. /**
  17793. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17794. */
  17795. AbstractMesh.prototype.toString = function (fullDetails) {
  17796. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17797. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17798. if (this._skeleton) {
  17799. ret += ", skeleton: " + this._skeleton.name;
  17800. }
  17801. if (fullDetails) {
  17802. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17803. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17804. }
  17805. return ret;
  17806. };
  17807. AbstractMesh.prototype._rebuild = function () {
  17808. if (this._occlusionQuery) {
  17809. this._occlusionQuery = null;
  17810. }
  17811. if (this._edgesRenderer) {
  17812. this._edgesRenderer._rebuild();
  17813. }
  17814. if (!this.subMeshes) {
  17815. return;
  17816. }
  17817. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17818. var subMesh = _a[_i];
  17819. subMesh._rebuild();
  17820. }
  17821. };
  17822. AbstractMesh.prototype._resyncLightSources = function () {
  17823. this._lightSources.length = 0;
  17824. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17825. var light = _a[_i];
  17826. if (!light.isEnabled()) {
  17827. continue;
  17828. }
  17829. if (light.canAffectMesh(this)) {
  17830. this._lightSources.push(light);
  17831. }
  17832. }
  17833. this._markSubMeshesAsLightDirty();
  17834. };
  17835. AbstractMesh.prototype._resyncLighSource = function (light) {
  17836. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17837. var index = this._lightSources.indexOf(light);
  17838. if (index === -1) {
  17839. if (!isIn) {
  17840. return;
  17841. }
  17842. this._lightSources.push(light);
  17843. }
  17844. else {
  17845. if (isIn) {
  17846. return;
  17847. }
  17848. this._lightSources.splice(index, 1);
  17849. }
  17850. this._markSubMeshesAsLightDirty();
  17851. };
  17852. AbstractMesh.prototype._removeLightSource = function (light) {
  17853. var index = this._lightSources.indexOf(light);
  17854. if (index === -1) {
  17855. return;
  17856. }
  17857. this._lightSources.splice(index, 1);
  17858. this._markSubMeshesAsLightDirty();
  17859. };
  17860. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17861. if (!this.subMeshes) {
  17862. return;
  17863. }
  17864. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17865. var subMesh = _a[_i];
  17866. if (subMesh._materialDefines) {
  17867. func(subMesh._materialDefines);
  17868. }
  17869. }
  17870. };
  17871. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17872. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17873. };
  17874. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17875. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17876. };
  17877. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17878. if (!this.subMeshes) {
  17879. return;
  17880. }
  17881. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17882. var subMesh = _a[_i];
  17883. var material = subMesh.getMaterial();
  17884. if (material) {
  17885. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17886. }
  17887. }
  17888. };
  17889. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17890. /**
  17891. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17892. * Default : (1.0, 1.0, 1.0)
  17893. */
  17894. get: function () {
  17895. return this._scaling;
  17896. },
  17897. /**
  17898. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17899. * Default : (1.0, 1.0, 1.0)
  17900. */
  17901. set: function (newScaling) {
  17902. this._scaling = newScaling;
  17903. if (this.physicsImpostor) {
  17904. this.physicsImpostor.forceUpdate();
  17905. }
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. // Methods
  17911. /**
  17912. * Disables the mesh edger rendering mode.
  17913. * Returns the AbstractMesh.
  17914. */
  17915. AbstractMesh.prototype.disableEdgesRendering = function () {
  17916. if (this._edgesRenderer) {
  17917. this._edgesRenderer.dispose();
  17918. this._edgesRenderer = null;
  17919. }
  17920. return this;
  17921. };
  17922. /**
  17923. * Enables the edge rendering mode on the mesh.
  17924. * This mode makes the mesh edges visible.
  17925. * Returns the AbstractMesh.
  17926. */
  17927. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17928. if (epsilon === void 0) { epsilon = 0.95; }
  17929. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17930. this.disableEdgesRendering();
  17931. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17932. return this;
  17933. };
  17934. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17935. /**
  17936. * Returns true if the mesh is blocked. Used by the class Mesh.
  17937. * Returns the boolean `false` by default.
  17938. */
  17939. get: function () {
  17940. return false;
  17941. },
  17942. enumerable: true,
  17943. configurable: true
  17944. });
  17945. /**
  17946. * Returns the mesh itself by default, used by the class Mesh.
  17947. * Returned type : AbstractMesh
  17948. */
  17949. AbstractMesh.prototype.getLOD = function (camera) {
  17950. return this;
  17951. };
  17952. /**
  17953. * Returns 0 by default, used by the class Mesh.
  17954. * Returns an integer.
  17955. */
  17956. AbstractMesh.prototype.getTotalVertices = function () {
  17957. return 0;
  17958. };
  17959. /**
  17960. * Returns null by default, used by the class Mesh.
  17961. * Returned type : integer array
  17962. */
  17963. AbstractMesh.prototype.getIndices = function () {
  17964. return null;
  17965. };
  17966. /**
  17967. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17968. * Returned type : float array or Float32Array
  17969. */
  17970. AbstractMesh.prototype.getVerticesData = function (kind) {
  17971. return null;
  17972. };
  17973. /**
  17974. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17975. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17976. * The `data` are either a numeric array either a Float32Array.
  17977. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17978. * 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).
  17979. * Note that a new underlying VertexBuffer object is created each call.
  17980. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17981. *
  17982. * Possible `kind` values :
  17983. * - BABYLON.VertexBuffer.PositionKind
  17984. * - BABYLON.VertexBuffer.UVKind
  17985. * - BABYLON.VertexBuffer.UV2Kind
  17986. * - BABYLON.VertexBuffer.UV3Kind
  17987. * - BABYLON.VertexBuffer.UV4Kind
  17988. * - BABYLON.VertexBuffer.UV5Kind
  17989. * - BABYLON.VertexBuffer.UV6Kind
  17990. * - BABYLON.VertexBuffer.ColorKind
  17991. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17992. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17993. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17994. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17995. *
  17996. * Returns the Mesh.
  17997. */
  17998. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17999. return this;
  18000. };
  18001. /**
  18002. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18003. * If the mesh has no geometry, it is simply returned as it is.
  18004. * The `data` are either a numeric array either a Float32Array.
  18005. * No new underlying VertexBuffer object is created.
  18006. * 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.
  18007. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18008. *
  18009. * Possible `kind` values :
  18010. * - BABYLON.VertexBuffer.PositionKind
  18011. * - BABYLON.VertexBuffer.UVKind
  18012. * - BABYLON.VertexBuffer.UV2Kind
  18013. * - BABYLON.VertexBuffer.UV3Kind
  18014. * - BABYLON.VertexBuffer.UV4Kind
  18015. * - BABYLON.VertexBuffer.UV5Kind
  18016. * - BABYLON.VertexBuffer.UV6Kind
  18017. * - BABYLON.VertexBuffer.ColorKind
  18018. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18019. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18020. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18021. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18022. *
  18023. * Returns the Mesh.
  18024. */
  18025. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18026. return this;
  18027. };
  18028. /**
  18029. * Sets the mesh indices.
  18030. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18031. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18032. * This method creates a new index buffer each call.
  18033. * Returns the Mesh.
  18034. */
  18035. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18036. return this;
  18037. };
  18038. /** Returns false by default, used by the class Mesh.
  18039. * Returns a boolean
  18040. */
  18041. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18042. return false;
  18043. };
  18044. /**
  18045. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18046. * Returns a BoundingInfo
  18047. */
  18048. AbstractMesh.prototype.getBoundingInfo = function () {
  18049. if (this._masterMesh) {
  18050. return this._masterMesh.getBoundingInfo();
  18051. }
  18052. if (!this._boundingInfo) {
  18053. // this._boundingInfo is being created here
  18054. this._updateBoundingInfo();
  18055. }
  18056. // cannot be null.
  18057. return this._boundingInfo;
  18058. };
  18059. /**
  18060. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18061. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18062. */
  18063. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18064. if (includeDescendants === void 0) { includeDescendants = true; }
  18065. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18066. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18067. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18068. if (maxDimension === 0) {
  18069. return this;
  18070. }
  18071. var scale = 1 / maxDimension;
  18072. this.scaling.scaleInPlace(scale);
  18073. return this;
  18074. };
  18075. /**
  18076. * Sets a mesh new object BoundingInfo.
  18077. * Returns the AbstractMesh.
  18078. */
  18079. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18080. this._boundingInfo = boundingInfo;
  18081. return this;
  18082. };
  18083. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18084. get: function () {
  18085. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18086. },
  18087. enumerable: true,
  18088. configurable: true
  18089. });
  18090. AbstractMesh.prototype._preActivate = function () {
  18091. };
  18092. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18093. };
  18094. AbstractMesh.prototype._activate = function (renderId) {
  18095. this._renderId = renderId;
  18096. };
  18097. /**
  18098. * Returns the latest update of the World matrix
  18099. * Returns a Matrix.
  18100. */
  18101. AbstractMesh.prototype.getWorldMatrix = function () {
  18102. if (this._masterMesh) {
  18103. return this._masterMesh.getWorldMatrix();
  18104. }
  18105. return _super.prototype.getWorldMatrix.call(this);
  18106. };
  18107. /**
  18108. * Returns the latest update of the World matrix determinant.
  18109. */
  18110. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18111. if (this._masterMesh) {
  18112. return this._masterMesh._getWorldMatrixDeterminant();
  18113. }
  18114. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18115. };
  18116. // ================================== Point of View Movement =================================
  18117. /**
  18118. * Perform relative position change from the point of view of behind the front of the mesh.
  18119. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18120. * Supports definition of mesh facing forward or backward.
  18121. * @param {number} amountRight
  18122. * @param {number} amountUp
  18123. * @param {number} amountForward
  18124. *
  18125. * Returns the AbstractMesh.
  18126. */
  18127. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18128. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18129. return this;
  18130. };
  18131. /**
  18132. * Calculate relative position change from the point of view of behind the front of the mesh.
  18133. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18134. * Supports definition of mesh facing forward or backward.
  18135. * @param {number} amountRight
  18136. * @param {number} amountUp
  18137. * @param {number} amountForward
  18138. *
  18139. * Returns a new Vector3.
  18140. */
  18141. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18142. var rotMatrix = new BABYLON.Matrix();
  18143. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18144. rotQuaternion.toRotationMatrix(rotMatrix);
  18145. var translationDelta = BABYLON.Vector3.Zero();
  18146. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18148. return translationDelta;
  18149. };
  18150. // ================================== Point of View Rotation =================================
  18151. /**
  18152. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18153. * Supports definition of mesh facing forward or backward.
  18154. * @param {number} flipBack
  18155. * @param {number} twirlClockwise
  18156. * @param {number} tiltRight
  18157. *
  18158. * Returns the AbstractMesh.
  18159. */
  18160. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18161. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18162. return this;
  18163. };
  18164. /**
  18165. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18166. * Supports definition of mesh facing forward or backward.
  18167. * @param {number} flipBack
  18168. * @param {number} twirlClockwise
  18169. * @param {number} tiltRight
  18170. *
  18171. * Returns a new Vector3.
  18172. */
  18173. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18174. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18175. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18176. };
  18177. /**
  18178. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18179. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18180. */
  18181. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18182. if (includeDescendants === void 0) { includeDescendants = true; }
  18183. this.computeWorldMatrix(true);
  18184. var min;
  18185. var max;
  18186. var boundingInfo = this.getBoundingInfo();
  18187. if (!this.subMeshes) {
  18188. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18189. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18190. }
  18191. else {
  18192. min = boundingInfo.boundingBox.minimumWorld;
  18193. max = boundingInfo.boundingBox.maximumWorld;
  18194. }
  18195. if (includeDescendants) {
  18196. var descendants = this.getDescendants(false);
  18197. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18198. var descendant = descendants_1[_i];
  18199. var childMesh = descendant;
  18200. childMesh.computeWorldMatrix(true);
  18201. //make sure we have the needed params to get mix and max
  18202. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18203. continue;
  18204. }
  18205. var childBoundingInfo = childMesh.getBoundingInfo();
  18206. var boundingBox = childBoundingInfo.boundingBox;
  18207. var minBox = boundingBox.minimumWorld;
  18208. var maxBox = boundingBox.maximumWorld;
  18209. BABYLON.Tools.CheckExtends(minBox, min, max);
  18210. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18211. }
  18212. }
  18213. return {
  18214. min: min,
  18215. max: max
  18216. };
  18217. };
  18218. /**
  18219. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18220. * Returns the AbstractMesh.
  18221. */
  18222. AbstractMesh.prototype._updateBoundingInfo = function () {
  18223. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18224. this._boundingInfo.update(this.worldMatrixFromCache);
  18225. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18226. return this;
  18227. };
  18228. /**
  18229. * Update a mesh's children BoundingInfo objects only.
  18230. * Returns the AbstractMesh.
  18231. */
  18232. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18233. if (!this.subMeshes) {
  18234. return this;
  18235. }
  18236. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18237. var subMesh = this.subMeshes[subIndex];
  18238. if (!subMesh.IsGlobal) {
  18239. subMesh.updateBoundingInfo(matrix);
  18240. }
  18241. }
  18242. return this;
  18243. };
  18244. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18245. // Bounding info
  18246. this._updateBoundingInfo();
  18247. };
  18248. /**
  18249. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18250. * A mesh is in the frustum if its bounding box intersects the frustum.
  18251. * Boolean returned.
  18252. */
  18253. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18254. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18255. };
  18256. /**
  18257. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18258. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18259. * Boolean returned.
  18260. */
  18261. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18262. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18263. ;
  18264. };
  18265. /**
  18266. * True if the mesh intersects another mesh or a SolidParticle object.
  18267. * 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)
  18268. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18269. * Returns a boolean.
  18270. */
  18271. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18272. if (precise === void 0) { precise = false; }
  18273. if (!this._boundingInfo || !mesh._boundingInfo) {
  18274. return false;
  18275. }
  18276. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18277. return true;
  18278. }
  18279. if (includeDescendants) {
  18280. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18281. var child = _a[_i];
  18282. if (child.intersectsMesh(mesh, precise, true)) {
  18283. return true;
  18284. }
  18285. }
  18286. }
  18287. return false;
  18288. };
  18289. /**
  18290. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18291. * Returns a boolean.
  18292. */
  18293. AbstractMesh.prototype.intersectsPoint = function (point) {
  18294. if (!this._boundingInfo) {
  18295. return false;
  18296. }
  18297. return this._boundingInfo.intersectsPoint(point);
  18298. };
  18299. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18300. return this.physicsImpostor;
  18301. };
  18302. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18303. if (camera === void 0) { camera = null; }
  18304. if (!camera) {
  18305. camera = this.getScene().activeCamera;
  18306. }
  18307. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18308. };
  18309. /**
  18310. * Returns the distance from the mesh to the active camera.
  18311. * Returns a float.
  18312. */
  18313. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18314. if (camera === void 0) { camera = null; }
  18315. if (!camera) {
  18316. camera = this.getScene().activeCamera;
  18317. }
  18318. return this.absolutePosition.subtract(camera.position).length();
  18319. };
  18320. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18321. if (!this.physicsImpostor) {
  18322. return this;
  18323. }
  18324. this.physicsImpostor.applyImpulse(force, contactPoint);
  18325. return this;
  18326. };
  18327. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18328. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18329. return this;
  18330. }
  18331. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18332. mainPivot: pivot1,
  18333. connectedPivot: pivot2,
  18334. nativeParams: options
  18335. });
  18336. return this;
  18337. };
  18338. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18339. // Collisions
  18340. /**
  18341. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18342. * Default `false`.
  18343. */
  18344. get: function () {
  18345. return this._checkCollisions;
  18346. },
  18347. set: function (collisionEnabled) {
  18348. this._checkCollisions = collisionEnabled;
  18349. if (this.getScene().workerCollisions) {
  18350. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18351. }
  18352. },
  18353. enumerable: true,
  18354. configurable: true
  18355. });
  18356. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18357. /**
  18358. * Gets Collider object used to compute collisions (not physics)
  18359. */
  18360. get: function () {
  18361. return this._collider;
  18362. },
  18363. enumerable: true,
  18364. configurable: true
  18365. });
  18366. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18367. var globalPosition = this.getAbsolutePosition();
  18368. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18369. if (!this._collider) {
  18370. this._collider = new BABYLON.Collider();
  18371. }
  18372. this._collider._radius = this.ellipsoid;
  18373. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18374. return this;
  18375. };
  18376. // Submeshes octree
  18377. /**
  18378. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18379. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18380. * Returns an Octree of submeshes.
  18381. */
  18382. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18383. if (maxCapacity === void 0) { maxCapacity = 64; }
  18384. if (maxDepth === void 0) { maxDepth = 2; }
  18385. if (!this._submeshesOctree) {
  18386. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18387. }
  18388. this.computeWorldMatrix(true);
  18389. var boundingInfo = this.getBoundingInfo();
  18390. // Update octree
  18391. var bbox = boundingInfo.boundingBox;
  18392. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18393. return this._submeshesOctree;
  18394. };
  18395. // Collisions
  18396. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18397. this._generatePointsArray();
  18398. if (!this._positions) {
  18399. return this;
  18400. }
  18401. // Transformation
  18402. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18403. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18404. subMesh._lastColliderWorldVertices = [];
  18405. subMesh._trianglePlanes = [];
  18406. var start = subMesh.verticesStart;
  18407. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18408. for (var i = start; i < end; i++) {
  18409. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18410. }
  18411. }
  18412. // Collide
  18413. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18414. if (collider.collisionFound) {
  18415. collider.collidedMesh = this;
  18416. }
  18417. return this;
  18418. };
  18419. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18420. var subMeshes;
  18421. var len;
  18422. // Octrees
  18423. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18424. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18425. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18426. len = intersections.length;
  18427. subMeshes = intersections.data;
  18428. }
  18429. else {
  18430. subMeshes = this.subMeshes;
  18431. len = subMeshes.length;
  18432. }
  18433. for (var index = 0; index < len; index++) {
  18434. var subMesh = subMeshes[index];
  18435. // Bounding test
  18436. if (len > 1 && !subMesh._checkCollision(collider))
  18437. continue;
  18438. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18439. }
  18440. return this;
  18441. };
  18442. AbstractMesh.prototype._checkCollision = function (collider) {
  18443. // Bounding box test
  18444. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18445. return this;
  18446. // Transformation matrix
  18447. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18448. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18449. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18450. return this;
  18451. };
  18452. // Picking
  18453. AbstractMesh.prototype._generatePointsArray = function () {
  18454. return false;
  18455. };
  18456. /**
  18457. * Checks if the passed Ray intersects with the mesh.
  18458. * Returns an object PickingInfo.
  18459. */
  18460. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18461. var pickingInfo = new BABYLON.PickingInfo();
  18462. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18463. return pickingInfo;
  18464. }
  18465. if (!this._generatePointsArray()) {
  18466. return pickingInfo;
  18467. }
  18468. var intersectInfo = null;
  18469. // Octrees
  18470. var subMeshes;
  18471. var len;
  18472. if (this._submeshesOctree && this.useOctreeForPicking) {
  18473. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18474. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18475. len = intersections.length;
  18476. subMeshes = intersections.data;
  18477. }
  18478. else {
  18479. subMeshes = this.subMeshes;
  18480. len = subMeshes.length;
  18481. }
  18482. for (var index = 0; index < len; index++) {
  18483. var subMesh = subMeshes[index];
  18484. // Bounding test
  18485. if (len > 1 && !subMesh.canIntersects(ray))
  18486. continue;
  18487. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18488. if (currentIntersectInfo) {
  18489. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18490. intersectInfo = currentIntersectInfo;
  18491. intersectInfo.subMeshId = index;
  18492. if (fastCheck) {
  18493. break;
  18494. }
  18495. }
  18496. }
  18497. }
  18498. if (intersectInfo) {
  18499. // Get picked point
  18500. var world = this.getWorldMatrix();
  18501. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18502. var direction = ray.direction.clone();
  18503. direction = direction.scale(intersectInfo.distance);
  18504. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18505. var pickedPoint = worldOrigin.add(worldDirection);
  18506. // Return result
  18507. pickingInfo.hit = true;
  18508. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18509. pickingInfo.pickedPoint = pickedPoint;
  18510. pickingInfo.pickedMesh = this;
  18511. pickingInfo.bu = intersectInfo.bu || 0;
  18512. pickingInfo.bv = intersectInfo.bv || 0;
  18513. pickingInfo.faceId = intersectInfo.faceId;
  18514. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18515. return pickingInfo;
  18516. }
  18517. return pickingInfo;
  18518. };
  18519. /**
  18520. * Clones the mesh, used by the class Mesh.
  18521. * Just returns `null` for an AbstractMesh.
  18522. */
  18523. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18524. return null;
  18525. };
  18526. /**
  18527. * Disposes all the mesh submeshes.
  18528. * Returns the AbstractMesh.
  18529. */
  18530. AbstractMesh.prototype.releaseSubMeshes = function () {
  18531. if (this.subMeshes) {
  18532. while (this.subMeshes.length) {
  18533. this.subMeshes[0].dispose();
  18534. }
  18535. }
  18536. else {
  18537. this.subMeshes = new Array();
  18538. }
  18539. return this;
  18540. };
  18541. /**
  18542. * Releases resources associated with this abstract mesh.
  18543. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18544. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18545. */
  18546. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18547. var _this = this;
  18548. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18549. var index;
  18550. // Action manager
  18551. if (this.actionManager !== undefined && this.actionManager !== null) {
  18552. this.actionManager.dispose();
  18553. this.actionManager = null;
  18554. }
  18555. // Skeleton
  18556. this.skeleton = null;
  18557. // Physics
  18558. if (this.physicsImpostor) {
  18559. this.physicsImpostor.dispose();
  18560. }
  18561. // Intersections in progress
  18562. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18563. var other = this._intersectionsInProgress[index];
  18564. var pos = other._intersectionsInProgress.indexOf(this);
  18565. other._intersectionsInProgress.splice(pos, 1);
  18566. }
  18567. this._intersectionsInProgress = [];
  18568. // Lights
  18569. var lights = this.getScene().lights;
  18570. lights.forEach(function (light) {
  18571. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18572. if (meshIndex !== -1) {
  18573. light.includedOnlyMeshes.splice(meshIndex, 1);
  18574. }
  18575. meshIndex = light.excludedMeshes.indexOf(_this);
  18576. if (meshIndex !== -1) {
  18577. light.excludedMeshes.splice(meshIndex, 1);
  18578. }
  18579. // Shadow generators
  18580. var generator = light.getShadowGenerator();
  18581. if (generator) {
  18582. var shadowMap = generator.getShadowMap();
  18583. if (shadowMap && shadowMap.renderList) {
  18584. meshIndex = shadowMap.renderList.indexOf(_this);
  18585. if (meshIndex !== -1) {
  18586. shadowMap.renderList.splice(meshIndex, 1);
  18587. }
  18588. }
  18589. }
  18590. });
  18591. // Edges
  18592. if (this._edgesRenderer) {
  18593. this._edgesRenderer.dispose();
  18594. this._edgesRenderer = null;
  18595. }
  18596. // SubMeshes
  18597. if (this.getClassName() !== "InstancedMesh") {
  18598. this.releaseSubMeshes();
  18599. }
  18600. // Octree
  18601. var sceneOctree = this.getScene().selectionOctree;
  18602. if (sceneOctree !== undefined && sceneOctree !== null) {
  18603. var index = sceneOctree.dynamicContent.indexOf(this);
  18604. if (index !== -1) {
  18605. sceneOctree.dynamicContent.splice(index, 1);
  18606. }
  18607. }
  18608. // Query
  18609. var engine = this.getScene().getEngine();
  18610. if (this._occlusionQuery) {
  18611. this._isOcclusionQueryInProgress = false;
  18612. engine.deleteQuery(this._occlusionQuery);
  18613. this._occlusionQuery = null;
  18614. }
  18615. // Engine
  18616. engine.wipeCaches();
  18617. // Remove from scene
  18618. this.getScene().removeMesh(this);
  18619. if (disposeMaterialAndTextures) {
  18620. if (this.material) {
  18621. this.material.dispose(false, true);
  18622. }
  18623. }
  18624. if (!doNotRecurse) {
  18625. // Particles
  18626. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18627. if (this.getScene().particleSystems[index].emitter === this) {
  18628. this.getScene().particleSystems[index].dispose();
  18629. index--;
  18630. }
  18631. }
  18632. }
  18633. // facet data
  18634. if (this._facetDataEnabled) {
  18635. this.disableFacetData();
  18636. }
  18637. this.onAfterWorldMatrixUpdateObservable.clear();
  18638. this.onCollideObservable.clear();
  18639. this.onCollisionPositionChangeObservable.clear();
  18640. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18641. };
  18642. /**
  18643. * Adds the passed mesh as a child to the current mesh.
  18644. * Returns the AbstractMesh.
  18645. */
  18646. AbstractMesh.prototype.addChild = function (mesh) {
  18647. mesh.setParent(this);
  18648. return this;
  18649. };
  18650. /**
  18651. * Removes the passed mesh from the current mesh children list.
  18652. * Returns the AbstractMesh.
  18653. */
  18654. AbstractMesh.prototype.removeChild = function (mesh) {
  18655. mesh.setParent(null);
  18656. return this;
  18657. };
  18658. // Facet data
  18659. /**
  18660. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18661. * Returns the AbstractMesh.
  18662. */
  18663. AbstractMesh.prototype._initFacetData = function () {
  18664. if (!this._facetNormals) {
  18665. this._facetNormals = new Array();
  18666. }
  18667. if (!this._facetPositions) {
  18668. this._facetPositions = new Array();
  18669. }
  18670. if (!this._facetPartitioning) {
  18671. this._facetPartitioning = new Array();
  18672. }
  18673. this._facetNb = (this.getIndices().length / 3) | 0;
  18674. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18675. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18676. for (var f = 0; f < this._facetNb; f++) {
  18677. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18678. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18679. }
  18680. this._facetDataEnabled = true;
  18681. return this;
  18682. };
  18683. /**
  18684. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18685. * This method can be called within the render loop.
  18686. * 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.
  18687. * Returns the AbstractMesh.
  18688. */
  18689. AbstractMesh.prototype.updateFacetData = function () {
  18690. if (!this._facetDataEnabled) {
  18691. this._initFacetData();
  18692. }
  18693. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18694. var indices = this.getIndices();
  18695. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18696. var bInfo = this.getBoundingInfo();
  18697. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18698. // init arrays, matrix and sort function on first call
  18699. this._facetDepthSortEnabled = true;
  18700. if (indices instanceof Uint16Array) {
  18701. this._depthSortedIndices = new Uint16Array(indices);
  18702. }
  18703. else if (indices instanceof Uint32Array) {
  18704. this._depthSortedIndices = new Uint32Array(indices);
  18705. }
  18706. else {
  18707. var needs32bits = false;
  18708. for (var i = 0; i < indices.length; i++) {
  18709. if (indices[i] > 65535) {
  18710. needs32bits = true;
  18711. break;
  18712. }
  18713. }
  18714. if (needs32bits) {
  18715. this._depthSortedIndices = new Uint32Array(indices);
  18716. }
  18717. else {
  18718. this._depthSortedIndices = new Uint16Array(indices);
  18719. }
  18720. }
  18721. this._facetDepthSortFunction = function (f1, f2) {
  18722. return (f2.sqDistance - f1.sqDistance);
  18723. };
  18724. if (!this._facetDepthSortFrom) {
  18725. var camera = this.getScene().activeCamera;
  18726. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18727. }
  18728. this._depthSortedFacets = [];
  18729. for (var f = 0; f < this._facetNb; f++) {
  18730. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18731. this._depthSortedFacets.push(depthSortedFacet);
  18732. }
  18733. this._invertedMatrix = BABYLON.Matrix.Identity();
  18734. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18735. }
  18736. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18737. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18738. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18739. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18740. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18741. this._subDiv.max = this._partitioningSubdivisions;
  18742. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18743. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18744. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18745. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18746. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18747. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18748. // set the parameters for ComputeNormals()
  18749. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18750. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18751. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18752. this._facetParameters.bInfo = bInfo;
  18753. this._facetParameters.bbSize = this._bbSize;
  18754. this._facetParameters.subDiv = this._subDiv;
  18755. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18756. this._facetParameters.depthSort = this._facetDepthSort;
  18757. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18758. this.computeWorldMatrix(true);
  18759. this._worldMatrix.invertToRef(this._invertedMatrix);
  18760. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18761. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18762. }
  18763. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18764. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18765. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18766. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18767. var l = (this._depthSortedIndices.length / 3) | 0;
  18768. for (var f = 0; f < l; f++) {
  18769. var sind = this._depthSortedFacets[f].ind;
  18770. this._depthSortedIndices[f * 3] = indices[sind];
  18771. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18772. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18773. }
  18774. this.updateIndices(this._depthSortedIndices);
  18775. }
  18776. return this;
  18777. };
  18778. /**
  18779. * Returns the facetLocalNormals array.
  18780. * The normals are expressed in the mesh local space.
  18781. */
  18782. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18783. if (!this._facetNormals) {
  18784. this.updateFacetData();
  18785. }
  18786. return this._facetNormals;
  18787. };
  18788. /**
  18789. * Returns the facetLocalPositions array.
  18790. * The facet positions are expressed in the mesh local space.
  18791. */
  18792. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18793. if (!this._facetPositions) {
  18794. this.updateFacetData();
  18795. }
  18796. return this._facetPositions;
  18797. };
  18798. /**
  18799. * Returns the facetLocalPartioning array.
  18800. */
  18801. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18802. if (!this._facetPartitioning) {
  18803. this.updateFacetData();
  18804. }
  18805. return this._facetPartitioning;
  18806. };
  18807. /**
  18808. * Returns the i-th facet position in the world system.
  18809. * This method allocates a new Vector3 per call.
  18810. */
  18811. AbstractMesh.prototype.getFacetPosition = function (i) {
  18812. var pos = BABYLON.Vector3.Zero();
  18813. this.getFacetPositionToRef(i, pos);
  18814. return pos;
  18815. };
  18816. /**
  18817. * Sets the reference Vector3 with the i-th facet position in the world system.
  18818. * Returns the AbstractMesh.
  18819. */
  18820. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18821. var localPos = (this.getFacetLocalPositions())[i];
  18822. var world = this.getWorldMatrix();
  18823. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18824. return this;
  18825. };
  18826. /**
  18827. * Returns the i-th facet normal in the world system.
  18828. * This method allocates a new Vector3 per call.
  18829. */
  18830. AbstractMesh.prototype.getFacetNormal = function (i) {
  18831. var norm = BABYLON.Vector3.Zero();
  18832. this.getFacetNormalToRef(i, norm);
  18833. return norm;
  18834. };
  18835. /**
  18836. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18837. * Returns the AbstractMesh.
  18838. */
  18839. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18840. var localNorm = (this.getFacetLocalNormals())[i];
  18841. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18842. return this;
  18843. };
  18844. /**
  18845. * 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).
  18846. */
  18847. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18848. var bInfo = this.getBoundingInfo();
  18849. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18850. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18851. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18852. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18853. return null;
  18854. }
  18855. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18856. };
  18857. /**
  18858. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18859. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18860. * 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.
  18861. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18862. * 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.
  18863. */
  18864. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18865. if (checkFace === void 0) { checkFace = false; }
  18866. if (facing === void 0) { facing = true; }
  18867. var world = this.getWorldMatrix();
  18868. var invMat = BABYLON.Tmp.Matrix[5];
  18869. world.invertToRef(invMat);
  18870. var invVect = BABYLON.Tmp.Vector3[8];
  18871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18872. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18873. if (projected) {
  18874. // tranform the local computed projected vector to world coordinates
  18875. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18876. }
  18877. return closest;
  18878. };
  18879. /**
  18880. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18881. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18882. * 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.
  18883. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18884. * 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.
  18885. */
  18886. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18887. if (checkFace === void 0) { checkFace = false; }
  18888. if (facing === void 0) { facing = true; }
  18889. var closest = null;
  18890. var tmpx = 0.0;
  18891. var tmpy = 0.0;
  18892. var tmpz = 0.0;
  18893. var d = 0.0; // tmp dot facet normal * facet position
  18894. var t0 = 0.0;
  18895. var projx = 0.0;
  18896. var projy = 0.0;
  18897. var projz = 0.0;
  18898. // Get all the facets in the same partitioning block than (x, y, z)
  18899. var facetPositions = this.getFacetLocalPositions();
  18900. var facetNormals = this.getFacetLocalNormals();
  18901. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18902. if (!facetsInBlock) {
  18903. return null;
  18904. }
  18905. // Get the closest facet to (x, y, z)
  18906. var shortest = Number.MAX_VALUE; // init distance vars
  18907. var tmpDistance = shortest;
  18908. var fib; // current facet in the block
  18909. var norm; // current facet normal
  18910. var p0; // current facet barycenter position
  18911. // loop on all the facets in the current partitioning block
  18912. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18913. fib = facetsInBlock[idx];
  18914. norm = facetNormals[fib];
  18915. p0 = facetPositions[fib];
  18916. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18917. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18918. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18919. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18920. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18921. projx = x + norm.x * t0;
  18922. projy = y + norm.y * t0;
  18923. projz = z + norm.z * t0;
  18924. tmpx = projx - x;
  18925. tmpy = projy - y;
  18926. tmpz = projz - z;
  18927. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18928. if (tmpDistance < shortest) {
  18929. shortest = tmpDistance;
  18930. closest = fib;
  18931. if (projected) {
  18932. projected.x = projx;
  18933. projected.y = projy;
  18934. projected.z = projz;
  18935. }
  18936. }
  18937. }
  18938. }
  18939. return closest;
  18940. };
  18941. /**
  18942. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18943. */
  18944. AbstractMesh.prototype.getFacetDataParameters = function () {
  18945. return this._facetParameters;
  18946. };
  18947. /**
  18948. * Disables the feature FacetData and frees the related memory.
  18949. * Returns the AbstractMesh.
  18950. */
  18951. AbstractMesh.prototype.disableFacetData = function () {
  18952. if (this._facetDataEnabled) {
  18953. this._facetDataEnabled = false;
  18954. this._facetPositions = new Array();
  18955. this._facetNormals = new Array();
  18956. this._facetPartitioning = new Array();
  18957. this._facetParameters = null;
  18958. this._depthSortedIndices = new Uint32Array(0);
  18959. }
  18960. return this;
  18961. };
  18962. /**
  18963. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18964. * Returns the mesh.
  18965. */
  18966. AbstractMesh.prototype.updateIndices = function (indices) {
  18967. return this;
  18968. };
  18969. /**
  18970. * The mesh Geometry. Actually used by the Mesh object.
  18971. * Returns a blank geometry object.
  18972. */
  18973. /**
  18974. * Creates new normals data for the mesh.
  18975. * @param updatable.
  18976. */
  18977. AbstractMesh.prototype.createNormals = function (updatable) {
  18978. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18979. var indices = this.getIndices();
  18980. var normals;
  18981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18982. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18983. }
  18984. else {
  18985. normals = [];
  18986. }
  18987. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18988. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18989. };
  18990. /**
  18991. * Align the mesh with a normal.
  18992. * Returns the mesh.
  18993. */
  18994. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18995. if (!upDirection) {
  18996. upDirection = BABYLON.Axis.Y;
  18997. }
  18998. var axisX = BABYLON.Tmp.Vector3[0];
  18999. var axisZ = BABYLON.Tmp.Vector3[1];
  19000. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19001. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19002. if (this.rotationQuaternion) {
  19003. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19004. }
  19005. else {
  19006. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19007. }
  19008. return this;
  19009. };
  19010. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19011. var engine = this.getEngine();
  19012. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19013. this._isOccluded = false;
  19014. return;
  19015. }
  19016. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19017. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19018. if (isOcclusionQueryAvailable) {
  19019. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19020. this._isOcclusionQueryInProgress = false;
  19021. this._occlusionInternalRetryCounter = 0;
  19022. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19023. }
  19024. else {
  19025. this._occlusionInternalRetryCounter++;
  19026. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19027. this._isOcclusionQueryInProgress = false;
  19028. this._occlusionInternalRetryCounter = 0;
  19029. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19030. // if strict continue the last state of the object.
  19031. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19032. }
  19033. else {
  19034. return;
  19035. }
  19036. }
  19037. }
  19038. var scene = this.getScene();
  19039. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19040. if (!this._occlusionQuery) {
  19041. this._occlusionQuery = engine.createQuery();
  19042. }
  19043. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19044. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19045. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19046. this._isOcclusionQueryInProgress = true;
  19047. };
  19048. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19049. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19050. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19051. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19052. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19053. return AbstractMesh;
  19054. }(BABYLON.TransformNode));
  19055. BABYLON.AbstractMesh = AbstractMesh;
  19056. })(BABYLON || (BABYLON = {}));
  19057. //# sourceMappingURL=babylon.abstractMesh.js.map
  19058. var BABYLON;
  19059. (function (BABYLON) {
  19060. /**
  19061. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19062. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19063. * 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.
  19064. */
  19065. var Light = /** @class */ (function (_super) {
  19066. __extends(Light, _super);
  19067. /**
  19068. * Creates a Light object in the scene.
  19069. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19070. * @param name The firendly name of the light
  19071. * @param scene The scene the light belongs too
  19072. */
  19073. function Light(name, scene) {
  19074. var _this = _super.call(this, name, scene) || this;
  19075. /**
  19076. * Diffuse gives the basic color to an object.
  19077. */
  19078. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19079. /**
  19080. * Specular produces a highlight color on an object.
  19081. * Note: This is note affecting PBR materials.
  19082. */
  19083. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19084. /**
  19085. * Strength of the light.
  19086. * Note: By default it is define in the framework own unit.
  19087. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19088. */
  19089. _this.intensity = 1.0;
  19090. /**
  19091. * Defines how far from the source the light is impacting in scene units.
  19092. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19093. */
  19094. _this.range = Number.MAX_VALUE;
  19095. /**
  19096. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19097. * of light.
  19098. */
  19099. _this._photometricScale = 1.0;
  19100. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19101. _this._radius = 0.00001;
  19102. /**
  19103. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19104. * exceeding the number allowed of the materials.
  19105. */
  19106. _this.renderPriority = 0;
  19107. /**
  19108. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19109. * the current shadow generator.
  19110. */
  19111. _this.shadowEnabled = true;
  19112. _this._excludeWithLayerMask = 0;
  19113. _this._includeOnlyWithLayerMask = 0;
  19114. _this._lightmapMode = 0;
  19115. /**
  19116. * @ignore Internal use only.
  19117. */
  19118. _this._excludedMeshesIds = new Array();
  19119. /**
  19120. * @ignore Internal use only.
  19121. */
  19122. _this._includedOnlyMeshesIds = new Array();
  19123. _this.getScene().addLight(_this);
  19124. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19125. _this._buildUniformLayout();
  19126. _this.includedOnlyMeshes = new Array();
  19127. _this.excludedMeshes = new Array();
  19128. _this._resyncMeshes();
  19129. return _this;
  19130. }
  19131. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19132. /**
  19133. * If every light affecting the material is in this lightmapMode,
  19134. * material.lightmapTexture adds or multiplies
  19135. * (depends on material.useLightmapAsShadowmap)
  19136. * after every other light calculations.
  19137. */
  19138. get: function () {
  19139. return Light._LIGHTMAP_DEFAULT;
  19140. },
  19141. enumerable: true,
  19142. configurable: true
  19143. });
  19144. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19145. /**
  19146. * material.lightmapTexture as only diffuse lighting from this light
  19147. * adds only specular lighting from this light
  19148. * adds dynamic shadows
  19149. */
  19150. get: function () {
  19151. return Light._LIGHTMAP_SPECULAR;
  19152. },
  19153. enumerable: true,
  19154. configurable: true
  19155. });
  19156. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19157. /**
  19158. * material.lightmapTexture as only lighting
  19159. * no light calculation from this light
  19160. * only adds dynamic shadows from this light
  19161. */
  19162. get: function () {
  19163. return Light._LIGHTMAP_SHADOWSONLY;
  19164. },
  19165. enumerable: true,
  19166. configurable: true
  19167. });
  19168. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19169. /**
  19170. * Each light type uses the default quantity according to its type:
  19171. * point/spot lights use luminous intensity
  19172. * directional lights use illuminance
  19173. */
  19174. get: function () {
  19175. return Light._INTENSITYMODE_AUTOMATIC;
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19181. /**
  19182. * lumen (lm)
  19183. */
  19184. get: function () {
  19185. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19186. },
  19187. enumerable: true,
  19188. configurable: true
  19189. });
  19190. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19191. /**
  19192. * candela (lm/sr)
  19193. */
  19194. get: function () {
  19195. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19196. },
  19197. enumerable: true,
  19198. configurable: true
  19199. });
  19200. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19201. /**
  19202. * lux (lm/m^2)
  19203. */
  19204. get: function () {
  19205. return Light._INTENSITYMODE_ILLUMINANCE;
  19206. },
  19207. enumerable: true,
  19208. configurable: true
  19209. });
  19210. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19211. /**
  19212. * nit (cd/m^2)
  19213. */
  19214. get: function () {
  19215. return Light._INTENSITYMODE_LUMINANCE;
  19216. },
  19217. enumerable: true,
  19218. configurable: true
  19219. });
  19220. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19221. /**
  19222. * Light type const id of the point light.
  19223. */
  19224. get: function () {
  19225. return Light._LIGHTTYPEID_POINTLIGHT;
  19226. },
  19227. enumerable: true,
  19228. configurable: true
  19229. });
  19230. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19231. /**
  19232. * Light type const id of the directional light.
  19233. */
  19234. get: function () {
  19235. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19241. /**
  19242. * Light type const id of the spot light.
  19243. */
  19244. get: function () {
  19245. return Light._LIGHTTYPEID_SPOTLIGHT;
  19246. },
  19247. enumerable: true,
  19248. configurable: true
  19249. });
  19250. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19251. /**
  19252. * Light type const id of the hemispheric light.
  19253. */
  19254. get: function () {
  19255. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19256. },
  19257. enumerable: true,
  19258. configurable: true
  19259. });
  19260. Object.defineProperty(Light.prototype, "intensityMode", {
  19261. /**
  19262. * Gets the photometric scale used to interpret the intensity.
  19263. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19264. */
  19265. get: function () {
  19266. return this._intensityMode;
  19267. },
  19268. /**
  19269. * Sets the photometric scale used to interpret the intensity.
  19270. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19271. */
  19272. set: function (value) {
  19273. this._intensityMode = value;
  19274. this._computePhotometricScale();
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. ;
  19280. ;
  19281. Object.defineProperty(Light.prototype, "radius", {
  19282. /**
  19283. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19284. */
  19285. get: function () {
  19286. return this._radius;
  19287. },
  19288. /**
  19289. * sets the light radius used by PBR Materials to simulate soft area lights.
  19290. */
  19291. set: function (value) {
  19292. this._radius = value;
  19293. this._computePhotometricScale();
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. ;
  19299. ;
  19300. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19301. /**
  19302. * Gets the only meshes impacted by this light.
  19303. */
  19304. get: function () {
  19305. return this._includedOnlyMeshes;
  19306. },
  19307. /**
  19308. * Sets the only meshes impacted by this light.
  19309. */
  19310. set: function (value) {
  19311. this._includedOnlyMeshes = value;
  19312. this._hookArrayForIncludedOnly(value);
  19313. },
  19314. enumerable: true,
  19315. configurable: true
  19316. });
  19317. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19318. /**
  19319. * Gets the meshes not impacted by this light.
  19320. */
  19321. get: function () {
  19322. return this._excludedMeshes;
  19323. },
  19324. /**
  19325. * Sets the meshes not impacted by this light.
  19326. */
  19327. set: function (value) {
  19328. this._excludedMeshes = value;
  19329. this._hookArrayForExcluded(value);
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19335. /**
  19336. * Gets the layer id use to find what meshes are not impacted by the light.
  19337. * Inactive if 0
  19338. */
  19339. get: function () {
  19340. return this._excludeWithLayerMask;
  19341. },
  19342. /**
  19343. * Sets the layer id use to find what meshes are not impacted by the light.
  19344. * Inactive if 0
  19345. */
  19346. set: function (value) {
  19347. this._excludeWithLayerMask = value;
  19348. this._resyncMeshes();
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19354. /**
  19355. * Gets the layer id use to find what meshes are impacted by the light.
  19356. * Inactive if 0
  19357. */
  19358. get: function () {
  19359. return this._includeOnlyWithLayerMask;
  19360. },
  19361. /**
  19362. * Sets the layer id use to find what meshes are impacted by the light.
  19363. * Inactive if 0
  19364. */
  19365. set: function (value) {
  19366. this._includeOnlyWithLayerMask = value;
  19367. this._resyncMeshes();
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Object.defineProperty(Light.prototype, "lightmapMode", {
  19373. /**
  19374. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19375. */
  19376. get: function () {
  19377. return this._lightmapMode;
  19378. },
  19379. /**
  19380. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19381. */
  19382. set: function (value) {
  19383. if (this._lightmapMode === value) {
  19384. return;
  19385. }
  19386. this._lightmapMode = value;
  19387. this._markMeshesAsLightDirty();
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. /**
  19393. * Returns the string "Light".
  19394. * @returns the class name
  19395. */
  19396. Light.prototype.getClassName = function () {
  19397. return "Light";
  19398. };
  19399. /**
  19400. * Converts the light information to a readable string for debug purpose.
  19401. * @param fullDetails Supports for multiple levels of logging within scene loading
  19402. * @returns the human readable light info
  19403. */
  19404. Light.prototype.toString = function (fullDetails) {
  19405. var ret = "Name: " + this.name;
  19406. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19407. if (this.animations) {
  19408. for (var i = 0; i < this.animations.length; i++) {
  19409. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19410. }
  19411. }
  19412. if (fullDetails) {
  19413. }
  19414. return ret;
  19415. };
  19416. /**
  19417. * Set the enabled state of this node.
  19418. * @param value - the new enabled state
  19419. * @see isEnabled
  19420. */
  19421. Light.prototype.setEnabled = function (value) {
  19422. _super.prototype.setEnabled.call(this, value);
  19423. this._resyncMeshes();
  19424. };
  19425. /**
  19426. * Returns the Light associated shadow generator if any.
  19427. * @return the associated shadow generator.
  19428. */
  19429. Light.prototype.getShadowGenerator = function () {
  19430. return this._shadowGenerator;
  19431. };
  19432. /**
  19433. * Returns a Vector3, the absolute light position in the World.
  19434. * @returns the world space position of the light
  19435. */
  19436. Light.prototype.getAbsolutePosition = function () {
  19437. return BABYLON.Vector3.Zero();
  19438. };
  19439. /**
  19440. * Specifies if the light will affect the passed mesh.
  19441. * @param mesh The mesh to test against the light
  19442. * @return true the mesh is affected otherwise, false.
  19443. */
  19444. Light.prototype.canAffectMesh = function (mesh) {
  19445. if (!mesh) {
  19446. return true;
  19447. }
  19448. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19449. return false;
  19450. }
  19451. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19452. return false;
  19453. }
  19454. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19455. return false;
  19456. }
  19457. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19458. return false;
  19459. }
  19460. return true;
  19461. };
  19462. /**
  19463. * Computes and Returns the light World matrix.
  19464. * @returns the world matrix
  19465. */
  19466. Light.prototype.getWorldMatrix = function () {
  19467. this._currentRenderId = this.getScene().getRenderId();
  19468. var worldMatrix = this._getWorldMatrix();
  19469. if (this.parent && this.parent.getWorldMatrix) {
  19470. if (!this._parentedWorldMatrix) {
  19471. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19472. }
  19473. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19474. this._markSyncedWithParent();
  19475. return this._parentedWorldMatrix;
  19476. }
  19477. return worldMatrix;
  19478. };
  19479. /**
  19480. * Sort function to order lights for rendering.
  19481. * @param a First Light object to compare to second.
  19482. * @param b Second Light object to compare first.
  19483. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19484. */
  19485. Light.CompareLightsPriority = function (a, b) {
  19486. //shadow-casting lights have priority over non-shadow-casting lights
  19487. //the renderPrioirty is a secondary sort criterion
  19488. if (a.shadowEnabled !== b.shadowEnabled) {
  19489. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19490. }
  19491. return b.renderPriority - a.renderPriority;
  19492. };
  19493. /**
  19494. * Releases resources associated with this node.
  19495. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19496. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19497. */
  19498. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19499. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19500. if (this._shadowGenerator) {
  19501. this._shadowGenerator.dispose();
  19502. this._shadowGenerator = null;
  19503. }
  19504. // Animations
  19505. this.getScene().stopAnimation(this);
  19506. // Remove from meshes
  19507. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19508. var mesh = _a[_i];
  19509. mesh._removeLightSource(this);
  19510. }
  19511. this._uniformBuffer.dispose();
  19512. // Remove from scene
  19513. this.getScene().removeLight(this);
  19514. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19515. };
  19516. /**
  19517. * Returns the light type ID (integer).
  19518. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19519. */
  19520. Light.prototype.getTypeID = function () {
  19521. return 0;
  19522. };
  19523. /**
  19524. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19525. * @returns the scaled intensity in intensity mode unit
  19526. */
  19527. Light.prototype.getScaledIntensity = function () {
  19528. return this._photometricScale * this.intensity;
  19529. };
  19530. /**
  19531. * Returns a new Light object, named "name", from the current one.
  19532. * @param name The name of the cloned light
  19533. * @returns the new created light
  19534. */
  19535. Light.prototype.clone = function (name) {
  19536. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19537. if (!constructor) {
  19538. return null;
  19539. }
  19540. return BABYLON.SerializationHelper.Clone(constructor, this);
  19541. };
  19542. /**
  19543. * Serializes the current light into a Serialization object.
  19544. * @returns the serialized object.
  19545. */
  19546. Light.prototype.serialize = function () {
  19547. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19548. // Type
  19549. serializationObject.type = this.getTypeID();
  19550. // Parent
  19551. if (this.parent) {
  19552. serializationObject.parentId = this.parent.id;
  19553. }
  19554. // Inclusion / exclusions
  19555. if (this.excludedMeshes.length > 0) {
  19556. serializationObject.excludedMeshesIds = [];
  19557. this.excludedMeshes.forEach(function (mesh) {
  19558. serializationObject.excludedMeshesIds.push(mesh.id);
  19559. });
  19560. }
  19561. if (this.includedOnlyMeshes.length > 0) {
  19562. serializationObject.includedOnlyMeshesIds = [];
  19563. this.includedOnlyMeshes.forEach(function (mesh) {
  19564. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19565. });
  19566. }
  19567. // Animations
  19568. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19569. serializationObject.ranges = this.serializeAnimationRanges();
  19570. return serializationObject;
  19571. };
  19572. /**
  19573. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19574. * This new light is named "name" and added to the passed scene.
  19575. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19576. * @param name The friendly name of the light
  19577. * @param scene The scene the new light will belong to
  19578. * @returns the constructor function
  19579. */
  19580. Light.GetConstructorFromName = function (type, name, scene) {
  19581. switch (type) {
  19582. case 0:
  19583. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19584. case 1:
  19585. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19586. case 2:
  19587. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19588. case 3:
  19589. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19590. }
  19591. return null;
  19592. };
  19593. /**
  19594. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19595. * @param parsedLight The JSON representation of the light
  19596. * @param scene The scene to create the parsed light in
  19597. * @returns the created light after parsing
  19598. */
  19599. Light.Parse = function (parsedLight, scene) {
  19600. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19601. if (!constructor) {
  19602. return null;
  19603. }
  19604. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19605. // Inclusion / exclusions
  19606. if (parsedLight.excludedMeshesIds) {
  19607. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19608. }
  19609. if (parsedLight.includedOnlyMeshesIds) {
  19610. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19611. }
  19612. // Parent
  19613. if (parsedLight.parentId) {
  19614. light._waitingParentId = parsedLight.parentId;
  19615. }
  19616. // Animations
  19617. if (parsedLight.animations) {
  19618. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19619. var parsedAnimation = parsedLight.animations[animationIndex];
  19620. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19621. }
  19622. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19623. }
  19624. if (parsedLight.autoAnimate) {
  19625. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19626. }
  19627. return light;
  19628. };
  19629. Light.prototype._hookArrayForExcluded = function (array) {
  19630. var _this = this;
  19631. var oldPush = array.push;
  19632. array.push = function () {
  19633. var items = [];
  19634. for (var _i = 0; _i < arguments.length; _i++) {
  19635. items[_i] = arguments[_i];
  19636. }
  19637. var result = oldPush.apply(array, items);
  19638. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19639. var item = items_1[_a];
  19640. item._resyncLighSource(_this);
  19641. }
  19642. return result;
  19643. };
  19644. var oldSplice = array.splice;
  19645. array.splice = function (index, deleteCount) {
  19646. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19647. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19648. var item = deleted_1[_i];
  19649. item._resyncLighSource(_this);
  19650. }
  19651. return deleted;
  19652. };
  19653. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19654. var item = array_1[_i];
  19655. item._resyncLighSource(this);
  19656. }
  19657. };
  19658. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19659. var _this = this;
  19660. var oldPush = array.push;
  19661. array.push = function () {
  19662. var items = [];
  19663. for (var _i = 0; _i < arguments.length; _i++) {
  19664. items[_i] = arguments[_i];
  19665. }
  19666. var result = oldPush.apply(array, items);
  19667. _this._resyncMeshes();
  19668. return result;
  19669. };
  19670. var oldSplice = array.splice;
  19671. array.splice = function (index, deleteCount) {
  19672. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19673. _this._resyncMeshes();
  19674. return deleted;
  19675. };
  19676. this._resyncMeshes();
  19677. };
  19678. Light.prototype._resyncMeshes = function () {
  19679. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19680. var mesh = _a[_i];
  19681. mesh._resyncLighSource(this);
  19682. }
  19683. };
  19684. /**
  19685. * Forces the meshes to update their light related information in their rendering used effects
  19686. * @ignore Internal Use Only
  19687. */
  19688. Light.prototype._markMeshesAsLightDirty = function () {
  19689. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19690. var mesh = _a[_i];
  19691. if (mesh._lightSources.indexOf(this) !== -1) {
  19692. mesh._markSubMeshesAsLightDirty();
  19693. }
  19694. }
  19695. };
  19696. /**
  19697. * Recomputes the cached photometric scale if needed.
  19698. */
  19699. Light.prototype._computePhotometricScale = function () {
  19700. this._photometricScale = this._getPhotometricScale();
  19701. this.getScene().resetCachedMaterial();
  19702. };
  19703. /**
  19704. * Returns the Photometric Scale according to the light type and intensity mode.
  19705. */
  19706. Light.prototype._getPhotometricScale = function () {
  19707. var photometricScale = 0.0;
  19708. var lightTypeID = this.getTypeID();
  19709. //get photometric mode
  19710. var photometricMode = this.intensityMode;
  19711. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19712. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19713. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19714. }
  19715. else {
  19716. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19717. }
  19718. }
  19719. //compute photometric scale
  19720. switch (lightTypeID) {
  19721. case Light.LIGHTTYPEID_POINTLIGHT:
  19722. case Light.LIGHTTYPEID_SPOTLIGHT:
  19723. switch (photometricMode) {
  19724. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19725. photometricScale = 1.0 / (4.0 * Math.PI);
  19726. break;
  19727. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19728. photometricScale = 1.0;
  19729. break;
  19730. case Light.INTENSITYMODE_LUMINANCE:
  19731. photometricScale = this.radius * this.radius;
  19732. break;
  19733. }
  19734. break;
  19735. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19736. switch (photometricMode) {
  19737. case Light.INTENSITYMODE_ILLUMINANCE:
  19738. photometricScale = 1.0;
  19739. break;
  19740. case Light.INTENSITYMODE_LUMINANCE:
  19741. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19742. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19743. var apexAngleRadians = this.radius;
  19744. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19745. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19746. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19747. photometricScale = solidAngle;
  19748. break;
  19749. }
  19750. break;
  19751. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19752. // No fall off in hemisperic light.
  19753. photometricScale = 1.0;
  19754. break;
  19755. }
  19756. return photometricScale;
  19757. };
  19758. /**
  19759. * Reorder the light in the scene according to their defined priority.
  19760. * @ignore Internal Use Only
  19761. */
  19762. Light.prototype._reorderLightsInScene = function () {
  19763. var scene = this.getScene();
  19764. if (this._renderPriority != 0) {
  19765. scene.requireLightSorting = true;
  19766. }
  19767. this.getScene().sortLightsByPriority();
  19768. };
  19769. //lightmapMode Consts
  19770. Light._LIGHTMAP_DEFAULT = 0;
  19771. Light._LIGHTMAP_SPECULAR = 1;
  19772. Light._LIGHTMAP_SHADOWSONLY = 2;
  19773. // Intensity Mode Consts
  19774. Light._INTENSITYMODE_AUTOMATIC = 0;
  19775. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19776. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19777. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19778. Light._INTENSITYMODE_LUMINANCE = 4;
  19779. // Light types ids const.
  19780. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19781. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19782. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19783. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19784. __decorate([
  19785. BABYLON.serializeAsColor3()
  19786. ], Light.prototype, "diffuse", void 0);
  19787. __decorate([
  19788. BABYLON.serializeAsColor3()
  19789. ], Light.prototype, "specular", void 0);
  19790. __decorate([
  19791. BABYLON.serialize()
  19792. ], Light.prototype, "intensity", void 0);
  19793. __decorate([
  19794. BABYLON.serialize()
  19795. ], Light.prototype, "range", void 0);
  19796. __decorate([
  19797. BABYLON.serialize()
  19798. ], Light.prototype, "intensityMode", null);
  19799. __decorate([
  19800. BABYLON.serialize()
  19801. ], Light.prototype, "radius", null);
  19802. __decorate([
  19803. BABYLON.serialize()
  19804. ], Light.prototype, "_renderPriority", void 0);
  19805. __decorate([
  19806. BABYLON.expandToProperty("_reorderLightsInScene")
  19807. ], Light.prototype, "renderPriority", void 0);
  19808. __decorate([
  19809. BABYLON.serialize()
  19810. ], Light.prototype, "shadowEnabled", void 0);
  19811. __decorate([
  19812. BABYLON.serialize("excludeWithLayerMask")
  19813. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19814. __decorate([
  19815. BABYLON.serialize("includeOnlyWithLayerMask")
  19816. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19817. __decorate([
  19818. BABYLON.serialize("lightmapMode")
  19819. ], Light.prototype, "_lightmapMode", void 0);
  19820. return Light;
  19821. }(BABYLON.Node));
  19822. BABYLON.Light = Light;
  19823. })(BABYLON || (BABYLON = {}));
  19824. //# sourceMappingURL=babylon.light.js.map
  19825. var BABYLON;
  19826. (function (BABYLON) {
  19827. var Camera = /** @class */ (function (_super) {
  19828. __extends(Camera, _super);
  19829. function Camera(name, position, scene) {
  19830. var _this = _super.call(this, name, scene) || this;
  19831. /**
  19832. * The vector the camera should consider as up.
  19833. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19834. */
  19835. _this.upVector = BABYLON.Vector3.Up();
  19836. _this.orthoLeft = null;
  19837. _this.orthoRight = null;
  19838. _this.orthoBottom = null;
  19839. _this.orthoTop = null;
  19840. /**
  19841. * FOV is set in Radians. (default is 0.8)
  19842. */
  19843. _this.fov = 0.8;
  19844. _this.minZ = 1;
  19845. _this.maxZ = 10000.0;
  19846. _this.inertia = 0.9;
  19847. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19848. _this.isIntermediate = false;
  19849. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19850. /**
  19851. * Restricts the camera to viewing objects with the same layerMask.
  19852. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19853. */
  19854. _this.layerMask = 0x0FFFFFFF;
  19855. /**
  19856. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19857. */
  19858. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19859. // Camera rig members
  19860. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19861. _this._rigCameras = new Array();
  19862. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19863. _this._skipRendering = false;
  19864. _this.customRenderTargets = new Array();
  19865. // Observables
  19866. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19867. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19868. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19869. _this.onRestoreStateObservable = new BABYLON.Observable();
  19870. // Cache
  19871. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19872. _this._projectionMatrix = new BABYLON.Matrix();
  19873. _this._doNotComputeProjectionMatrix = false;
  19874. _this._postProcesses = new Array();
  19875. _this._transformMatrix = BABYLON.Matrix.Zero();
  19876. _this._activeMeshes = new BABYLON.SmartArray(256);
  19877. _this._globalPosition = BABYLON.Vector3.Zero();
  19878. _this._refreshFrustumPlanes = true;
  19879. _this.getScene().addCamera(_this);
  19880. if (!_this.getScene().activeCamera) {
  19881. _this.getScene().activeCamera = _this;
  19882. }
  19883. _this.position = position;
  19884. return _this;
  19885. }
  19886. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19887. get: function () {
  19888. return Camera._PERSPECTIVE_CAMERA;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19894. get: function () {
  19895. return Camera._ORTHOGRAPHIC_CAMERA;
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19901. /**
  19902. * This is the default FOV mode for perspective cameras.
  19903. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19904. *
  19905. */
  19906. get: function () {
  19907. return Camera._FOVMODE_VERTICAL_FIXED;
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19913. /**
  19914. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19915. *
  19916. */
  19917. get: function () {
  19918. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19924. get: function () {
  19925. return Camera._RIG_MODE_NONE;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19931. get: function () {
  19932. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19938. get: function () {
  19939. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19945. get: function () {
  19946. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19952. get: function () {
  19953. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19954. },
  19955. enumerable: true,
  19956. configurable: true
  19957. });
  19958. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19959. get: function () {
  19960. return Camera._RIG_MODE_VR;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19966. get: function () {
  19967. return Camera._RIG_MODE_WEBVR;
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. /**
  19973. * Store current camera state (fov, position, etc..)
  19974. */
  19975. Camera.prototype.storeState = function () {
  19976. this._stateStored = true;
  19977. this._storedFov = this.fov;
  19978. return this;
  19979. };
  19980. /**
  19981. * Restores the camera state values if it has been stored. You must call storeState() first
  19982. */
  19983. Camera.prototype._restoreStateValues = function () {
  19984. if (!this._stateStored) {
  19985. return false;
  19986. }
  19987. this.fov = this._storedFov;
  19988. return true;
  19989. };
  19990. /**
  19991. * Restored camera state. You must call storeState() first
  19992. */
  19993. Camera.prototype.restoreState = function () {
  19994. if (this._restoreStateValues()) {
  19995. this.onRestoreStateObservable.notifyObservers(this);
  19996. return true;
  19997. }
  19998. return false;
  19999. };
  20000. Camera.prototype.getClassName = function () {
  20001. return "Camera";
  20002. };
  20003. /**
  20004. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20005. */
  20006. Camera.prototype.toString = function (fullDetails) {
  20007. var ret = "Name: " + this.name;
  20008. ret += ", type: " + this.getClassName();
  20009. if (this.animations) {
  20010. for (var i = 0; i < this.animations.length; i++) {
  20011. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20012. }
  20013. }
  20014. if (fullDetails) {
  20015. }
  20016. return ret;
  20017. };
  20018. Object.defineProperty(Camera.prototype, "globalPosition", {
  20019. get: function () {
  20020. return this._globalPosition;
  20021. },
  20022. enumerable: true,
  20023. configurable: true
  20024. });
  20025. Camera.prototype.getActiveMeshes = function () {
  20026. return this._activeMeshes;
  20027. };
  20028. Camera.prototype.isActiveMesh = function (mesh) {
  20029. return (this._activeMeshes.indexOf(mesh) !== -1);
  20030. };
  20031. //Cache
  20032. Camera.prototype._initCache = function () {
  20033. _super.prototype._initCache.call(this);
  20034. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20035. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20036. this._cache.mode = undefined;
  20037. this._cache.minZ = undefined;
  20038. this._cache.maxZ = undefined;
  20039. this._cache.fov = undefined;
  20040. this._cache.fovMode = undefined;
  20041. this._cache.aspectRatio = undefined;
  20042. this._cache.orthoLeft = undefined;
  20043. this._cache.orthoRight = undefined;
  20044. this._cache.orthoBottom = undefined;
  20045. this._cache.orthoTop = undefined;
  20046. this._cache.renderWidth = undefined;
  20047. this._cache.renderHeight = undefined;
  20048. };
  20049. Camera.prototype._updateCache = function (ignoreParentClass) {
  20050. if (!ignoreParentClass) {
  20051. _super.prototype._updateCache.call(this);
  20052. }
  20053. this._cache.position.copyFrom(this.position);
  20054. this._cache.upVector.copyFrom(this.upVector);
  20055. };
  20056. // Synchronized
  20057. Camera.prototype._isSynchronized = function () {
  20058. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20059. };
  20060. Camera.prototype._isSynchronizedViewMatrix = function () {
  20061. if (!_super.prototype._isSynchronized.call(this))
  20062. return false;
  20063. return this._cache.position.equals(this.position)
  20064. && this._cache.upVector.equals(this.upVector)
  20065. && this.isSynchronizedWithParent();
  20066. };
  20067. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20068. var check = this._cache.mode === this.mode
  20069. && this._cache.minZ === this.minZ
  20070. && this._cache.maxZ === this.maxZ;
  20071. if (!check) {
  20072. return false;
  20073. }
  20074. var engine = this.getEngine();
  20075. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20076. check = this._cache.fov === this.fov
  20077. && this._cache.fovMode === this.fovMode
  20078. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20079. }
  20080. else {
  20081. check = this._cache.orthoLeft === this.orthoLeft
  20082. && this._cache.orthoRight === this.orthoRight
  20083. && this._cache.orthoBottom === this.orthoBottom
  20084. && this._cache.orthoTop === this.orthoTop
  20085. && this._cache.renderWidth === engine.getRenderWidth()
  20086. && this._cache.renderHeight === engine.getRenderHeight();
  20087. }
  20088. return check;
  20089. };
  20090. // Controls
  20091. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20092. };
  20093. Camera.prototype.detachControl = function (element) {
  20094. };
  20095. Camera.prototype.update = function () {
  20096. this._checkInputs();
  20097. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20098. this._updateRigCameras();
  20099. }
  20100. };
  20101. Camera.prototype._checkInputs = function () {
  20102. this.onAfterCheckInputsObservable.notifyObservers(this);
  20103. };
  20104. Object.defineProperty(Camera.prototype, "rigCameras", {
  20105. get: function () {
  20106. return this._rigCameras;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20112. get: function () {
  20113. return this._rigPostProcess;
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20119. // invalidate framebuffer
  20120. if (this._postProcesses.length > 0) {
  20121. this._postProcesses[0].markTextureDirty();
  20122. }
  20123. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20124. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20125. var cam = this._rigCameras[i];
  20126. var rigPostProcess = cam._rigPostProcess;
  20127. // for VR rig, there does not have to be a post process
  20128. if (rigPostProcess) {
  20129. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20130. if (isPass) {
  20131. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20132. cam.isIntermediate = this._postProcesses.length === 0;
  20133. }
  20134. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20135. rigPostProcess.markTextureDirty();
  20136. }
  20137. else {
  20138. cam._postProcesses = this._postProcesses.slice(0);
  20139. }
  20140. }
  20141. };
  20142. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20143. if (insertAt === void 0) { insertAt = null; }
  20144. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20145. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20146. return 0;
  20147. }
  20148. if (insertAt == null || insertAt < 0) {
  20149. this._postProcesses.push(postProcess);
  20150. }
  20151. else {
  20152. this._postProcesses.splice(insertAt, 0, postProcess);
  20153. }
  20154. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20155. return this._postProcesses.indexOf(postProcess);
  20156. };
  20157. Camera.prototype.detachPostProcess = function (postProcess) {
  20158. var idx = this._postProcesses.indexOf(postProcess);
  20159. if (idx !== -1) {
  20160. this._postProcesses.splice(idx, 1);
  20161. }
  20162. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20163. };
  20164. Camera.prototype.getWorldMatrix = function () {
  20165. if (!this._worldMatrix) {
  20166. this._worldMatrix = BABYLON.Matrix.Identity();
  20167. }
  20168. var viewMatrix = this.getViewMatrix();
  20169. viewMatrix.invertToRef(this._worldMatrix);
  20170. return this._worldMatrix;
  20171. };
  20172. Camera.prototype._getViewMatrix = function () {
  20173. return BABYLON.Matrix.Identity();
  20174. };
  20175. Camera.prototype.getViewMatrix = function (force) {
  20176. if (!force && this._isSynchronizedViewMatrix()) {
  20177. return this._computedViewMatrix;
  20178. }
  20179. this.updateCache();
  20180. this._computedViewMatrix = this._getViewMatrix();
  20181. this._currentRenderId = this.getScene().getRenderId();
  20182. this._refreshFrustumPlanes = true;
  20183. if (!this.parent || !this.parent.getWorldMatrix) {
  20184. this._globalPosition.copyFrom(this.position);
  20185. }
  20186. else {
  20187. if (!this._worldMatrix) {
  20188. this._worldMatrix = BABYLON.Matrix.Identity();
  20189. }
  20190. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20191. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20192. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20193. this._computedViewMatrix.invert();
  20194. this._markSyncedWithParent();
  20195. }
  20196. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20197. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20198. }
  20199. this.onViewMatrixChangedObservable.notifyObservers(this);
  20200. return this._computedViewMatrix;
  20201. };
  20202. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20203. this._doNotComputeProjectionMatrix = true;
  20204. if (projection !== undefined) {
  20205. this._projectionMatrix = projection;
  20206. }
  20207. };
  20208. ;
  20209. Camera.prototype.unfreezeProjectionMatrix = function () {
  20210. this._doNotComputeProjectionMatrix = false;
  20211. };
  20212. ;
  20213. Camera.prototype.getProjectionMatrix = function (force) {
  20214. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20215. return this._projectionMatrix;
  20216. }
  20217. // Cache
  20218. this._cache.mode = this.mode;
  20219. this._cache.minZ = this.minZ;
  20220. this._cache.maxZ = this.maxZ;
  20221. // Matrix
  20222. this._refreshFrustumPlanes = true;
  20223. var engine = this.getEngine();
  20224. var scene = this.getScene();
  20225. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20226. this._cache.fov = this.fov;
  20227. this._cache.fovMode = this.fovMode;
  20228. this._cache.aspectRatio = engine.getAspectRatio(this);
  20229. if (this.minZ <= 0) {
  20230. this.minZ = 0.1;
  20231. }
  20232. if (scene.useRightHandedSystem) {
  20233. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20234. }
  20235. else {
  20236. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20237. }
  20238. }
  20239. else {
  20240. var halfWidth = engine.getRenderWidth() / 2.0;
  20241. var halfHeight = engine.getRenderHeight() / 2.0;
  20242. if (scene.useRightHandedSystem) {
  20243. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20244. }
  20245. else {
  20246. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20247. }
  20248. this._cache.orthoLeft = this.orthoLeft;
  20249. this._cache.orthoRight = this.orthoRight;
  20250. this._cache.orthoBottom = this.orthoBottom;
  20251. this._cache.orthoTop = this.orthoTop;
  20252. this._cache.renderWidth = engine.getRenderWidth();
  20253. this._cache.renderHeight = engine.getRenderHeight();
  20254. }
  20255. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20256. return this._projectionMatrix;
  20257. };
  20258. Camera.prototype.getTranformationMatrix = function () {
  20259. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20260. return this._transformMatrix;
  20261. };
  20262. Camera.prototype.updateFrustumPlanes = function () {
  20263. if (!this._refreshFrustumPlanes) {
  20264. return;
  20265. }
  20266. this.getTranformationMatrix();
  20267. if (!this._frustumPlanes) {
  20268. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20269. }
  20270. else {
  20271. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20272. }
  20273. this._refreshFrustumPlanes = false;
  20274. };
  20275. Camera.prototype.isInFrustum = function (target) {
  20276. this.updateFrustumPlanes();
  20277. return target.isInFrustum(this._frustumPlanes);
  20278. };
  20279. Camera.prototype.isCompletelyInFrustum = function (target) {
  20280. this.updateFrustumPlanes();
  20281. return target.isCompletelyInFrustum(this._frustumPlanes);
  20282. };
  20283. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20284. if (length === void 0) { length = 100; }
  20285. if (!transform) {
  20286. transform = this.getWorldMatrix();
  20287. }
  20288. if (!origin) {
  20289. origin = this.position;
  20290. }
  20291. var forward = new BABYLON.Vector3(0, 0, 1);
  20292. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20293. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20294. return new BABYLON.Ray(origin, direction, length);
  20295. };
  20296. /**
  20297. * Releases resources associated with this node.
  20298. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20299. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20300. */
  20301. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20302. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20303. // Observables
  20304. this.onViewMatrixChangedObservable.clear();
  20305. this.onProjectionMatrixChangedObservable.clear();
  20306. this.onAfterCheckInputsObservable.clear();
  20307. this.onRestoreStateObservable.clear();
  20308. // Inputs
  20309. if (this.inputs) {
  20310. this.inputs.clear();
  20311. }
  20312. // Animations
  20313. this.getScene().stopAnimation(this);
  20314. // Remove from scene
  20315. this.getScene().removeCamera(this);
  20316. while (this._rigCameras.length > 0) {
  20317. var camera = this._rigCameras.pop();
  20318. if (camera) {
  20319. camera.dispose();
  20320. }
  20321. }
  20322. // Postprocesses
  20323. if (this._rigPostProcess) {
  20324. this._rigPostProcess.dispose(this);
  20325. this._rigPostProcess = null;
  20326. this._postProcesses = [];
  20327. }
  20328. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20329. this._rigPostProcess = null;
  20330. this._postProcesses = [];
  20331. }
  20332. else {
  20333. var i = this._postProcesses.length;
  20334. while (--i >= 0) {
  20335. this._postProcesses[i].dispose(this);
  20336. }
  20337. }
  20338. // Render targets
  20339. var i = this.customRenderTargets.length;
  20340. while (--i >= 0) {
  20341. this.customRenderTargets[i].dispose();
  20342. }
  20343. this.customRenderTargets = [];
  20344. // Active Meshes
  20345. this._activeMeshes.dispose();
  20346. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20347. };
  20348. Object.defineProperty(Camera.prototype, "leftCamera", {
  20349. // ---- Camera rigs section ----
  20350. get: function () {
  20351. if (this._rigCameras.length < 1) {
  20352. return null;
  20353. }
  20354. return this._rigCameras[0];
  20355. },
  20356. enumerable: true,
  20357. configurable: true
  20358. });
  20359. Object.defineProperty(Camera.prototype, "rightCamera", {
  20360. get: function () {
  20361. if (this._rigCameras.length < 2) {
  20362. return null;
  20363. }
  20364. return this._rigCameras[1];
  20365. },
  20366. enumerable: true,
  20367. configurable: true
  20368. });
  20369. Camera.prototype.getLeftTarget = function () {
  20370. if (this._rigCameras.length < 1) {
  20371. return null;
  20372. }
  20373. return this._rigCameras[0].getTarget();
  20374. };
  20375. Camera.prototype.getRightTarget = function () {
  20376. if (this._rigCameras.length < 2) {
  20377. return null;
  20378. }
  20379. return this._rigCameras[1].getTarget();
  20380. };
  20381. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20382. if (this.cameraRigMode === mode) {
  20383. return;
  20384. }
  20385. while (this._rigCameras.length > 0) {
  20386. var camera = this._rigCameras.pop();
  20387. if (camera) {
  20388. camera.dispose();
  20389. }
  20390. }
  20391. this.cameraRigMode = mode;
  20392. this._cameraRigParams = {};
  20393. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20394. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20395. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20396. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20397. // create the rig cameras, unless none
  20398. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20399. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20400. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20401. if (leftCamera && rightCamera) {
  20402. this._rigCameras.push(leftCamera);
  20403. this._rigCameras.push(rightCamera);
  20404. }
  20405. }
  20406. switch (this.cameraRigMode) {
  20407. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20408. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20409. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20410. break;
  20411. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20412. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20413. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20414. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20415. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20416. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20417. break;
  20418. case Camera.RIG_MODE_VR:
  20419. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20420. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20421. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20422. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20423. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20424. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20425. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20426. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20427. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20428. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20429. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20430. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20431. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20432. if (metrics.compensateDistortion) {
  20433. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20434. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20435. }
  20436. break;
  20437. case Camera.RIG_MODE_WEBVR:
  20438. if (rigParams.vrDisplay) {
  20439. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20440. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20441. //Left eye
  20442. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20443. this._rigCameras[0].setCameraRigParameter("left", true);
  20444. //leaving this for future reference
  20445. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20446. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20447. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20448. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20449. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20450. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20451. this._rigCameras[0].parent = this;
  20452. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20453. //Right eye
  20454. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20455. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20456. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20457. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20458. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20459. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20460. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20461. this._rigCameras[1].parent = this;
  20462. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20463. if (Camera.UseAlternateWebVRRendering) {
  20464. this._rigCameras[1]._skipRendering = true;
  20465. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20466. }
  20467. }
  20468. break;
  20469. }
  20470. this._cascadePostProcessesToRigCams();
  20471. this.update();
  20472. };
  20473. Camera.prototype._getVRProjectionMatrix = function () {
  20474. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20475. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20476. return this._projectionMatrix;
  20477. };
  20478. Camera.prototype._updateCameraRotationMatrix = function () {
  20479. //Here for WebVR
  20480. };
  20481. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20482. //Here for WebVR
  20483. };
  20484. /**
  20485. * This function MUST be overwritten by the different WebVR cameras available.
  20486. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20487. */
  20488. Camera.prototype._getWebVRProjectionMatrix = function () {
  20489. return BABYLON.Matrix.Identity();
  20490. };
  20491. /**
  20492. * This function MUST be overwritten by the different WebVR cameras available.
  20493. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20494. */
  20495. Camera.prototype._getWebVRViewMatrix = function () {
  20496. return BABYLON.Matrix.Identity();
  20497. };
  20498. Camera.prototype.setCameraRigParameter = function (name, value) {
  20499. if (!this._cameraRigParams) {
  20500. this._cameraRigParams = {};
  20501. }
  20502. this._cameraRigParams[name] = value;
  20503. //provisionnally:
  20504. if (name === "interaxialDistance") {
  20505. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20506. }
  20507. };
  20508. /**
  20509. * needs to be overridden by children so sub has required properties to be copied
  20510. */
  20511. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20512. return null;
  20513. };
  20514. /**
  20515. * May need to be overridden by children
  20516. */
  20517. Camera.prototype._updateRigCameras = function () {
  20518. for (var i = 0; i < this._rigCameras.length; i++) {
  20519. this._rigCameras[i].minZ = this.minZ;
  20520. this._rigCameras[i].maxZ = this.maxZ;
  20521. this._rigCameras[i].fov = this.fov;
  20522. }
  20523. // only update viewport when ANAGLYPH
  20524. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20525. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20526. }
  20527. };
  20528. Camera.prototype._setupInputs = function () {
  20529. };
  20530. Camera.prototype.serialize = function () {
  20531. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20532. // Type
  20533. serializationObject.type = this.getClassName();
  20534. // Parent
  20535. if (this.parent) {
  20536. serializationObject.parentId = this.parent.id;
  20537. }
  20538. if (this.inputs) {
  20539. this.inputs.serialize(serializationObject);
  20540. }
  20541. // Animations
  20542. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20543. serializationObject.ranges = this.serializeAnimationRanges();
  20544. return serializationObject;
  20545. };
  20546. Camera.prototype.clone = function (name) {
  20547. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20548. };
  20549. Camera.prototype.getDirection = function (localAxis) {
  20550. var result = BABYLON.Vector3.Zero();
  20551. this.getDirectionToRef(localAxis, result);
  20552. return result;
  20553. };
  20554. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20555. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20556. };
  20557. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20558. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20559. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20560. switch (type) {
  20561. case "ArcRotateCamera":
  20562. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20563. case "DeviceOrientationCamera":
  20564. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20565. case "FollowCamera":
  20566. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20567. case "ArcFollowCamera":
  20568. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20569. case "GamepadCamera":
  20570. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20571. case "TouchCamera":
  20572. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20573. case "VirtualJoysticksCamera":
  20574. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20575. case "WebVRFreeCamera":
  20576. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20577. case "WebVRGamepadCamera":
  20578. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20579. case "VRDeviceOrientationFreeCamera":
  20580. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20581. case "VRDeviceOrientationGamepadCamera":
  20582. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20583. case "AnaglyphArcRotateCamera":
  20584. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20585. case "AnaglyphFreeCamera":
  20586. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20587. case "AnaglyphGamepadCamera":
  20588. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20589. case "AnaglyphUniversalCamera":
  20590. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20591. case "StereoscopicArcRotateCamera":
  20592. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20593. case "StereoscopicFreeCamera":
  20594. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20595. case "StereoscopicGamepadCamera":
  20596. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20597. case "StereoscopicUniversalCamera":
  20598. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20599. case "FreeCamera":// Forcing Universal here
  20600. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20601. default:// Universal Camera is the default value
  20602. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20603. }
  20604. };
  20605. Camera.prototype.computeWorldMatrix = function () {
  20606. return this.getWorldMatrix();
  20607. };
  20608. Camera.Parse = function (parsedCamera, scene) {
  20609. var type = parsedCamera.type;
  20610. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20611. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20612. // Parent
  20613. if (parsedCamera.parentId) {
  20614. camera._waitingParentId = parsedCamera.parentId;
  20615. }
  20616. //If camera has an input manager, let it parse inputs settings
  20617. if (camera.inputs) {
  20618. camera.inputs.parse(parsedCamera);
  20619. camera._setupInputs();
  20620. }
  20621. if (camera.setPosition) {
  20622. camera.position.copyFromFloats(0, 0, 0);
  20623. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20624. }
  20625. // Target
  20626. if (parsedCamera.target) {
  20627. if (camera.setTarget) {
  20628. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20629. }
  20630. }
  20631. // Apply 3d rig, when found
  20632. if (parsedCamera.cameraRigMode) {
  20633. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20634. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20635. }
  20636. // Animations
  20637. if (parsedCamera.animations) {
  20638. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20639. var parsedAnimation = parsedCamera.animations[animationIndex];
  20640. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20641. }
  20642. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20643. }
  20644. if (parsedCamera.autoAnimate) {
  20645. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20646. }
  20647. return camera;
  20648. };
  20649. // Statics
  20650. Camera._PERSPECTIVE_CAMERA = 0;
  20651. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20652. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20653. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20654. Camera._RIG_MODE_NONE = 0;
  20655. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20656. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20657. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20658. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20659. Camera._RIG_MODE_VR = 20;
  20660. Camera._RIG_MODE_WEBVR = 21;
  20661. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20662. Camera.UseAlternateWebVRRendering = false;
  20663. __decorate([
  20664. BABYLON.serializeAsVector3()
  20665. ], Camera.prototype, "position", void 0);
  20666. __decorate([
  20667. BABYLON.serializeAsVector3()
  20668. ], Camera.prototype, "upVector", void 0);
  20669. __decorate([
  20670. BABYLON.serialize()
  20671. ], Camera.prototype, "orthoLeft", void 0);
  20672. __decorate([
  20673. BABYLON.serialize()
  20674. ], Camera.prototype, "orthoRight", void 0);
  20675. __decorate([
  20676. BABYLON.serialize()
  20677. ], Camera.prototype, "orthoBottom", void 0);
  20678. __decorate([
  20679. BABYLON.serialize()
  20680. ], Camera.prototype, "orthoTop", void 0);
  20681. __decorate([
  20682. BABYLON.serialize()
  20683. ], Camera.prototype, "fov", void 0);
  20684. __decorate([
  20685. BABYLON.serialize()
  20686. ], Camera.prototype, "minZ", void 0);
  20687. __decorate([
  20688. BABYLON.serialize()
  20689. ], Camera.prototype, "maxZ", void 0);
  20690. __decorate([
  20691. BABYLON.serialize()
  20692. ], Camera.prototype, "inertia", void 0);
  20693. __decorate([
  20694. BABYLON.serialize()
  20695. ], Camera.prototype, "mode", void 0);
  20696. __decorate([
  20697. BABYLON.serialize()
  20698. ], Camera.prototype, "layerMask", void 0);
  20699. __decorate([
  20700. BABYLON.serialize()
  20701. ], Camera.prototype, "fovMode", void 0);
  20702. __decorate([
  20703. BABYLON.serialize()
  20704. ], Camera.prototype, "cameraRigMode", void 0);
  20705. __decorate([
  20706. BABYLON.serialize()
  20707. ], Camera.prototype, "interaxialDistance", void 0);
  20708. __decorate([
  20709. BABYLON.serialize()
  20710. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20711. return Camera;
  20712. }(BABYLON.Node));
  20713. BABYLON.Camera = Camera;
  20714. })(BABYLON || (BABYLON = {}));
  20715. //# sourceMappingURL=babylon.camera.js.map
  20716. var BABYLON;
  20717. (function (BABYLON) {
  20718. var RenderingManager = /** @class */ (function () {
  20719. function RenderingManager(scene) {
  20720. this._renderingGroups = new Array();
  20721. this._autoClearDepthStencil = {};
  20722. this._customOpaqueSortCompareFn = {};
  20723. this._customAlphaTestSortCompareFn = {};
  20724. this._customTransparentSortCompareFn = {};
  20725. this._renderinGroupInfo = null;
  20726. this._scene = scene;
  20727. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20728. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20729. }
  20730. }
  20731. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20732. if (depth === void 0) { depth = true; }
  20733. if (stencil === void 0) { stencil = true; }
  20734. if (this._depthStencilBufferAlreadyCleaned) {
  20735. return;
  20736. }
  20737. this._scene.getEngine().clear(null, false, depth, stencil);
  20738. this._depthStencilBufferAlreadyCleaned = true;
  20739. };
  20740. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20741. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20742. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20743. var info = null;
  20744. if (observable) {
  20745. if (!this._renderinGroupInfo) {
  20746. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20747. }
  20748. info = this._renderinGroupInfo;
  20749. info.scene = this._scene;
  20750. info.camera = this._scene.activeCamera;
  20751. }
  20752. // Dispatch sprites
  20753. if (renderSprites) {
  20754. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20755. var manager = this._scene.spriteManagers[index];
  20756. this.dispatchSprites(manager);
  20757. }
  20758. }
  20759. // Render
  20760. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20761. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20762. var renderingGroup = this._renderingGroups[index];
  20763. if (!renderingGroup && !observable)
  20764. continue;
  20765. var renderingGroupMask = 0;
  20766. // Fire PRECLEAR stage
  20767. if (observable && info) {
  20768. renderingGroupMask = Math.pow(2, index);
  20769. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20770. info.renderingGroupId = index;
  20771. observable.notifyObservers(info, renderingGroupMask);
  20772. }
  20773. // Clear depth/stencil if needed
  20774. if (RenderingManager.AUTOCLEAR) {
  20775. var autoClear = this._autoClearDepthStencil[index];
  20776. if (autoClear && autoClear.autoClear) {
  20777. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20778. }
  20779. }
  20780. if (observable && info) {
  20781. // Fire PREOPAQUE stage
  20782. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20783. observable.notifyObservers(info, renderingGroupMask);
  20784. // Fire PRETRANSPARENT stage
  20785. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20786. observable.notifyObservers(info, renderingGroupMask);
  20787. }
  20788. if (renderingGroup)
  20789. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20790. // Fire POSTTRANSPARENT stage
  20791. if (observable && info) {
  20792. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20793. observable.notifyObservers(info, renderingGroupMask);
  20794. }
  20795. }
  20796. };
  20797. RenderingManager.prototype.reset = function () {
  20798. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20799. var renderingGroup = this._renderingGroups[index];
  20800. if (renderingGroup) {
  20801. renderingGroup.prepare();
  20802. }
  20803. }
  20804. };
  20805. RenderingManager.prototype.dispose = function () {
  20806. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20807. var renderingGroup = this._renderingGroups[index];
  20808. if (renderingGroup) {
  20809. renderingGroup.dispose();
  20810. }
  20811. }
  20812. this._renderingGroups.length = 0;
  20813. };
  20814. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20815. if (this._renderingGroups[renderingGroupId] === undefined) {
  20816. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20817. }
  20818. };
  20819. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20820. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20821. this._prepareRenderingGroup(renderingGroupId);
  20822. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20823. };
  20824. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20825. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20826. this._prepareRenderingGroup(renderingGroupId);
  20827. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20828. };
  20829. /**
  20830. * @param subMesh The submesh to dispatch
  20831. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20832. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20833. */
  20834. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20835. if (mesh === undefined) {
  20836. mesh = subMesh.getMesh();
  20837. }
  20838. var renderingGroupId = mesh.renderingGroupId || 0;
  20839. this._prepareRenderingGroup(renderingGroupId);
  20840. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20841. };
  20842. /**
  20843. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20844. * This allowed control for front to back rendering or reversly depending of the special needs.
  20845. *
  20846. * @param renderingGroupId The rendering group id corresponding to its index
  20847. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20848. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20849. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20850. */
  20851. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20852. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20853. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20854. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20855. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20856. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20857. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20858. if (this._renderingGroups[renderingGroupId]) {
  20859. var group = this._renderingGroups[renderingGroupId];
  20860. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20861. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20862. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20863. }
  20864. };
  20865. /**
  20866. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20867. *
  20868. * @param renderingGroupId The rendering group id corresponding to its index
  20869. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20870. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20871. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20872. */
  20873. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20874. if (depth === void 0) { depth = true; }
  20875. if (stencil === void 0) { stencil = true; }
  20876. this._autoClearDepthStencil[renderingGroupId] = {
  20877. autoClear: autoClearDepthStencil,
  20878. depth: depth,
  20879. stencil: stencil
  20880. };
  20881. };
  20882. /**
  20883. * The max id used for rendering groups (not included)
  20884. */
  20885. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20886. /**
  20887. * The min id used for rendering groups (included)
  20888. */
  20889. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20890. /**
  20891. * Used to globally prevent autoclearing scenes.
  20892. */
  20893. RenderingManager.AUTOCLEAR = true;
  20894. return RenderingManager;
  20895. }());
  20896. BABYLON.RenderingManager = RenderingManager;
  20897. })(BABYLON || (BABYLON = {}));
  20898. //# sourceMappingURL=babylon.renderingManager.js.map
  20899. var BABYLON;
  20900. (function (BABYLON) {
  20901. var RenderingGroup = /** @class */ (function () {
  20902. /**
  20903. * Creates a new rendering group.
  20904. * @param index The rendering group index
  20905. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20906. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20907. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20908. */
  20909. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20910. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20911. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20912. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20913. this.index = index;
  20914. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20915. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20916. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20917. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20918. this._particleSystems = new BABYLON.SmartArray(256);
  20919. this._spriteManagers = new BABYLON.SmartArray(256);
  20920. this._edgesRenderers = new BABYLON.SmartArray(16);
  20921. this._scene = scene;
  20922. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20923. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20924. this.transparentSortCompareFn = transparentSortCompareFn;
  20925. }
  20926. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20927. /**
  20928. * Set the opaque sort comparison function.
  20929. * If null the sub meshes will be render in the order they were created
  20930. */
  20931. set: function (value) {
  20932. this._opaqueSortCompareFn = value;
  20933. if (value) {
  20934. this._renderOpaque = this.renderOpaqueSorted;
  20935. }
  20936. else {
  20937. this._renderOpaque = RenderingGroup.renderUnsorted;
  20938. }
  20939. },
  20940. enumerable: true,
  20941. configurable: true
  20942. });
  20943. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20944. /**
  20945. * Set the alpha test sort comparison function.
  20946. * If null the sub meshes will be render in the order they were created
  20947. */
  20948. set: function (value) {
  20949. this._alphaTestSortCompareFn = value;
  20950. if (value) {
  20951. this._renderAlphaTest = this.renderAlphaTestSorted;
  20952. }
  20953. else {
  20954. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20955. }
  20956. },
  20957. enumerable: true,
  20958. configurable: true
  20959. });
  20960. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20961. /**
  20962. * Set the transparent sort comparison function.
  20963. * If null the sub meshes will be render in the order they were created
  20964. */
  20965. set: function (value) {
  20966. if (value) {
  20967. this._transparentSortCompareFn = value;
  20968. }
  20969. else {
  20970. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20971. }
  20972. this._renderTransparent = this.renderTransparentSorted;
  20973. },
  20974. enumerable: true,
  20975. configurable: true
  20976. });
  20977. /**
  20978. * Render all the sub meshes contained in the group.
  20979. * @param customRenderFunction Used to override the default render behaviour of the group.
  20980. * @returns true if rendered some submeshes.
  20981. */
  20982. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20983. if (customRenderFunction) {
  20984. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20985. return;
  20986. }
  20987. var engine = this._scene.getEngine();
  20988. // Depth only
  20989. if (this._depthOnlySubMeshes.length !== 0) {
  20990. engine.setColorWrite(false);
  20991. this._renderAlphaTest(this._depthOnlySubMeshes);
  20992. engine.setColorWrite(true);
  20993. }
  20994. // Opaque
  20995. if (this._opaqueSubMeshes.length !== 0) {
  20996. this._renderOpaque(this._opaqueSubMeshes);
  20997. }
  20998. // Alpha test
  20999. if (this._alphaTestSubMeshes.length !== 0) {
  21000. this._renderAlphaTest(this._alphaTestSubMeshes);
  21001. }
  21002. var stencilState = engine.getStencilBuffer();
  21003. engine.setStencilBuffer(false);
  21004. // Sprites
  21005. if (renderSprites) {
  21006. this._renderSprites();
  21007. }
  21008. // Particles
  21009. if (renderParticles) {
  21010. this._renderParticles(activeMeshes);
  21011. }
  21012. if (this.onBeforeTransparentRendering) {
  21013. this.onBeforeTransparentRendering();
  21014. }
  21015. // Transparent
  21016. if (this._transparentSubMeshes.length !== 0) {
  21017. this._renderTransparent(this._transparentSubMeshes);
  21018. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21019. }
  21020. // Set back stencil to false in case it changes before the edge renderer.
  21021. engine.setStencilBuffer(false);
  21022. // Edges
  21023. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21024. this._edgesRenderers.data[edgesRendererIndex].render();
  21025. }
  21026. // Restore Stencil state.
  21027. engine.setStencilBuffer(stencilState);
  21028. };
  21029. /**
  21030. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21031. * @param subMeshes The submeshes to render
  21032. */
  21033. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21034. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21035. };
  21036. /**
  21037. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21038. * @param subMeshes The submeshes to render
  21039. */
  21040. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21041. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21042. };
  21043. /**
  21044. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21045. * @param subMeshes The submeshes to render
  21046. */
  21047. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21048. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21049. };
  21050. /**
  21051. * Renders the submeshes in a specified order.
  21052. * @param subMeshes The submeshes to sort before render
  21053. * @param sortCompareFn The comparison function use to sort
  21054. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21055. * @param transparent Specifies to activate blending if true
  21056. */
  21057. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21058. var subIndex = 0;
  21059. var subMesh;
  21060. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21061. for (; subIndex < subMeshes.length; subIndex++) {
  21062. subMesh = subMeshes.data[subIndex];
  21063. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21064. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21065. }
  21066. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21067. if (sortCompareFn) {
  21068. sortedArray.sort(sortCompareFn);
  21069. }
  21070. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21071. subMesh = sortedArray[subIndex];
  21072. if (transparent) {
  21073. var material = subMesh.getMaterial();
  21074. if (material && material.needDepthPrePass) {
  21075. var engine = material.getScene().getEngine();
  21076. engine.setColorWrite(false);
  21077. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21078. subMesh.render(false);
  21079. engine.setColorWrite(true);
  21080. }
  21081. }
  21082. subMesh.render(transparent);
  21083. }
  21084. };
  21085. /**
  21086. * Renders the submeshes in the order they were dispatched (no sort applied).
  21087. * @param subMeshes The submeshes to render
  21088. */
  21089. RenderingGroup.renderUnsorted = function (subMeshes) {
  21090. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21091. var submesh = subMeshes.data[subIndex];
  21092. submesh.render(false);
  21093. }
  21094. };
  21095. /**
  21096. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21097. * are rendered back to front if in the same alpha index.
  21098. *
  21099. * @param a The first submesh
  21100. * @param b The second submesh
  21101. * @returns The result of the comparison
  21102. */
  21103. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21104. // Alpha index first
  21105. if (a._alphaIndex > b._alphaIndex) {
  21106. return 1;
  21107. }
  21108. if (a._alphaIndex < b._alphaIndex) {
  21109. return -1;
  21110. }
  21111. // Then distance to camera
  21112. return RenderingGroup.backToFrontSortCompare(a, b);
  21113. };
  21114. /**
  21115. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21116. * are rendered back to front.
  21117. *
  21118. * @param a The first submesh
  21119. * @param b The second submesh
  21120. * @returns The result of the comparison
  21121. */
  21122. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21123. // Then distance to camera
  21124. if (a._distanceToCamera < b._distanceToCamera) {
  21125. return 1;
  21126. }
  21127. if (a._distanceToCamera > b._distanceToCamera) {
  21128. return -1;
  21129. }
  21130. return 0;
  21131. };
  21132. /**
  21133. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21134. * are rendered front to back (prevent overdraw).
  21135. *
  21136. * @param a The first submesh
  21137. * @param b The second submesh
  21138. * @returns The result of the comparison
  21139. */
  21140. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21141. // Then distance to camera
  21142. if (a._distanceToCamera < b._distanceToCamera) {
  21143. return -1;
  21144. }
  21145. if (a._distanceToCamera > b._distanceToCamera) {
  21146. return 1;
  21147. }
  21148. return 0;
  21149. };
  21150. /**
  21151. * Resets the different lists of submeshes to prepare a new frame.
  21152. */
  21153. RenderingGroup.prototype.prepare = function () {
  21154. this._opaqueSubMeshes.reset();
  21155. this._transparentSubMeshes.reset();
  21156. this._alphaTestSubMeshes.reset();
  21157. this._depthOnlySubMeshes.reset();
  21158. this._particleSystems.reset();
  21159. this._spriteManagers.reset();
  21160. this._edgesRenderers.reset();
  21161. };
  21162. RenderingGroup.prototype.dispose = function () {
  21163. this._opaqueSubMeshes.dispose();
  21164. this._transparentSubMeshes.dispose();
  21165. this._alphaTestSubMeshes.dispose();
  21166. this._depthOnlySubMeshes.dispose();
  21167. this._particleSystems.dispose();
  21168. this._spriteManagers.dispose();
  21169. this._edgesRenderers.dispose();
  21170. };
  21171. /**
  21172. * Inserts the submesh in its correct queue depending on its material.
  21173. * @param subMesh The submesh to dispatch
  21174. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21175. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21176. */
  21177. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21178. // Get mesh and materials if not provided
  21179. if (mesh === undefined) {
  21180. mesh = subMesh.getMesh();
  21181. }
  21182. if (material === undefined) {
  21183. material = subMesh.getMaterial();
  21184. }
  21185. if (material === null || material === undefined) {
  21186. return;
  21187. }
  21188. if (material.needAlphaBlendingForMesh(mesh)) {
  21189. this._transparentSubMeshes.push(subMesh);
  21190. }
  21191. else if (material.needAlphaTesting()) {
  21192. if (material.needDepthPrePass) {
  21193. this._depthOnlySubMeshes.push(subMesh);
  21194. }
  21195. this._alphaTestSubMeshes.push(subMesh);
  21196. }
  21197. else {
  21198. if (material.needDepthPrePass) {
  21199. this._depthOnlySubMeshes.push(subMesh);
  21200. }
  21201. this._opaqueSubMeshes.push(subMesh); // Opaque
  21202. }
  21203. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21204. this._edgesRenderers.push(mesh._edgesRenderer);
  21205. }
  21206. };
  21207. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21208. this._spriteManagers.push(spriteManager);
  21209. };
  21210. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21211. this._particleSystems.push(particleSystem);
  21212. };
  21213. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21214. if (this._particleSystems.length === 0) {
  21215. return;
  21216. }
  21217. // Particles
  21218. var activeCamera = this._scene.activeCamera;
  21219. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21220. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21221. var particleSystem = this._particleSystems.data[particleIndex];
  21222. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21223. continue;
  21224. }
  21225. var emitter = particleSystem.emitter;
  21226. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21227. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21228. }
  21229. }
  21230. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21231. };
  21232. RenderingGroup.prototype._renderSprites = function () {
  21233. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21234. return;
  21235. }
  21236. // Sprites
  21237. var activeCamera = this._scene.activeCamera;
  21238. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21239. for (var id = 0; id < this._spriteManagers.length; id++) {
  21240. var spriteManager = this._spriteManagers.data[id];
  21241. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21242. spriteManager.render();
  21243. }
  21244. }
  21245. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21246. };
  21247. return RenderingGroup;
  21248. }());
  21249. BABYLON.RenderingGroup = RenderingGroup;
  21250. })(BABYLON || (BABYLON = {}));
  21251. //# sourceMappingURL=babylon.renderingGroup.js.map
  21252. var BABYLON;
  21253. (function (BABYLON) {
  21254. var ClickInfo = /** @class */ (function () {
  21255. function ClickInfo() {
  21256. this._singleClick = false;
  21257. this._doubleClick = false;
  21258. this._hasSwiped = false;
  21259. this._ignore = false;
  21260. }
  21261. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21262. get: function () {
  21263. return this._singleClick;
  21264. },
  21265. set: function (b) {
  21266. this._singleClick = b;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21272. get: function () {
  21273. return this._doubleClick;
  21274. },
  21275. set: function (b) {
  21276. this._doubleClick = b;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21282. get: function () {
  21283. return this._hasSwiped;
  21284. },
  21285. set: function (b) {
  21286. this._hasSwiped = b;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21292. get: function () {
  21293. return this._ignore;
  21294. },
  21295. set: function (b) {
  21296. this._ignore = b;
  21297. },
  21298. enumerable: true,
  21299. configurable: true
  21300. });
  21301. return ClickInfo;
  21302. }());
  21303. /**
  21304. * This class is used by the onRenderingGroupObservable
  21305. */
  21306. var RenderingGroupInfo = /** @class */ (function () {
  21307. function RenderingGroupInfo() {
  21308. }
  21309. /**
  21310. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21311. * This stage will be fired no matter what
  21312. */
  21313. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21314. /**
  21315. * Called before opaque object are rendered.
  21316. * This stage will be fired only if there's 3D Opaque content to render
  21317. */
  21318. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21319. /**
  21320. * Called after the opaque objects are rendered and before the transparent ones
  21321. * This stage will be fired only if there's 3D transparent content to render
  21322. */
  21323. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21324. /**
  21325. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21326. * This stage will be fired no matter what
  21327. */
  21328. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21329. return RenderingGroupInfo;
  21330. }());
  21331. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21332. /**
  21333. * Represents a scene to be rendered by the engine.
  21334. * @see http://doc.babylonjs.com/page.php?p=21911
  21335. */
  21336. var Scene = /** @class */ (function () {
  21337. /**
  21338. * @constructor
  21339. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21340. */
  21341. function Scene(engine) {
  21342. // Members
  21343. this.autoClear = true;
  21344. this.autoClearDepthAndStencil = true;
  21345. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21346. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21347. this.forceWireframe = false;
  21348. this._forcePointsCloud = false;
  21349. this.forceShowBoundingBoxes = false;
  21350. this.animationsEnabled = true;
  21351. this.useConstantAnimationDeltaTime = false;
  21352. this.constantlyUpdateMeshUnderPointer = false;
  21353. this.hoverCursor = "pointer";
  21354. this.defaultCursor = "";
  21355. /**
  21356. * This is used to call preventDefault() on pointer down
  21357. * in order to block unwanted artifacts like system double clicks
  21358. */
  21359. this.preventDefaultOnPointerDown = true;
  21360. // Metadata
  21361. this.metadata = null;
  21362. /**
  21363. * An event triggered when the scene is disposed.
  21364. * @type {BABYLON.Observable}
  21365. */
  21366. this.onDisposeObservable = new BABYLON.Observable();
  21367. /**
  21368. * An event triggered before rendering the scene (right after animations and physics)
  21369. * @type {BABYLON.Observable}
  21370. */
  21371. this.onBeforeRenderObservable = new BABYLON.Observable();
  21372. /**
  21373. * An event triggered after rendering the scene
  21374. * @type {BABYLON.Observable}
  21375. */
  21376. this.onAfterRenderObservable = new BABYLON.Observable();
  21377. /**
  21378. * An event triggered before animating the scene
  21379. * @type {BABYLON.Observable}
  21380. */
  21381. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21382. /**
  21383. * An event triggered after animations processing
  21384. * @type {BABYLON.Observable}
  21385. */
  21386. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21387. /**
  21388. * An event triggered before draw calls are ready to be sent
  21389. * @type {BABYLON.Observable}
  21390. */
  21391. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21392. /**
  21393. * An event triggered after draw calls have been sent
  21394. * @type {BABYLON.Observable}
  21395. */
  21396. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21397. /**
  21398. * An event triggered when physic simulation is about to be run
  21399. * @type {BABYLON.Observable}
  21400. */
  21401. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21402. /**
  21403. * An event triggered when physic simulation has been done
  21404. * @type {BABYLON.Observable}
  21405. */
  21406. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21407. /**
  21408. * An event triggered when the scene is ready
  21409. * @type {BABYLON.Observable}
  21410. */
  21411. this.onReadyObservable = new BABYLON.Observable();
  21412. /**
  21413. * An event triggered before rendering a camera
  21414. * @type {BABYLON.Observable}
  21415. */
  21416. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21417. /**
  21418. * An event triggered after rendering a camera
  21419. * @type {BABYLON.Observable}
  21420. */
  21421. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21422. /**
  21423. * An event triggered when active meshes evaluation is about to start
  21424. * @type {BABYLON.Observable}
  21425. */
  21426. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21427. /**
  21428. * An event triggered when active meshes evaluation is done
  21429. * @type {BABYLON.Observable}
  21430. */
  21431. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21432. /**
  21433. * An event triggered when particles rendering is about to start
  21434. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21435. * @type {BABYLON.Observable}
  21436. */
  21437. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21438. /**
  21439. * An event triggered when particles rendering is done
  21440. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21441. * @type {BABYLON.Observable}
  21442. */
  21443. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21444. /**
  21445. * An event triggered when sprites rendering is about to start
  21446. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21447. * @type {BABYLON.Observable}
  21448. */
  21449. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21450. /**
  21451. * An event triggered when sprites rendering is done
  21452. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21453. * @type {BABYLON.Observable}
  21454. */
  21455. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21456. /**
  21457. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21458. * @type {BABYLON.Observable}
  21459. */
  21460. this.onDataLoadedObservable = new BABYLON.Observable();
  21461. /**
  21462. * An event triggered when a camera is created
  21463. * @type {BABYLON.Observable}
  21464. */
  21465. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21466. /**
  21467. * An event triggered when a camera is removed
  21468. * @type {BABYLON.Observable}
  21469. */
  21470. this.onCameraRemovedObservable = new BABYLON.Observable();
  21471. /**
  21472. * An event triggered when a light is created
  21473. * @type {BABYLON.Observable}
  21474. */
  21475. this.onNewLightAddedObservable = new BABYLON.Observable();
  21476. /**
  21477. * An event triggered when a light is removed
  21478. * @type {BABYLON.Observable}
  21479. */
  21480. this.onLightRemovedObservable = new BABYLON.Observable();
  21481. /**
  21482. * An event triggered when a geometry is created
  21483. * @type {BABYLON.Observable}
  21484. */
  21485. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21486. /**
  21487. * An event triggered when a geometry is removed
  21488. * @type {BABYLON.Observable}
  21489. */
  21490. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21491. /**
  21492. * An event triggered when a transform node is created
  21493. * @type {BABYLON.Observable}
  21494. */
  21495. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21496. /**
  21497. * An event triggered when a transform node is removed
  21498. * @type {BABYLON.Observable}
  21499. */
  21500. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21501. /**
  21502. * An event triggered when a mesh is created
  21503. * @type {BABYLON.Observable}
  21504. */
  21505. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21506. /**
  21507. * An event triggered when a mesh is removed
  21508. * @type {BABYLON.Observable}
  21509. */
  21510. this.onMeshRemovedObservable = new BABYLON.Observable();
  21511. /**
  21512. * An event triggered when render targets are about to be rendered
  21513. * Can happen multiple times per frame.
  21514. * @type {BABYLON.Observable}
  21515. */
  21516. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21517. /**
  21518. * An event triggered when render targets were rendered.
  21519. * Can happen multiple times per frame.
  21520. * @type {BABYLON.Observable}
  21521. */
  21522. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21523. /**
  21524. * An event triggered before calculating deterministic simulation step
  21525. * @type {BABYLON.Observable}
  21526. */
  21527. this.onBeforeStepObservable = new BABYLON.Observable();
  21528. /**
  21529. * An event triggered after calculating deterministic simulation step
  21530. * @type {BABYLON.Observable}
  21531. */
  21532. this.onAfterStepObservable = new BABYLON.Observable();
  21533. /**
  21534. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21535. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21536. * 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)
  21537. */
  21538. this.onRenderingGroupObservable = new BABYLON.Observable();
  21539. // Animations
  21540. this.animations = [];
  21541. /**
  21542. * 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).
  21543. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21544. */
  21545. this.onPrePointerObservable = new BABYLON.Observable();
  21546. /**
  21547. * Observable event triggered each time an input event is received from the rendering canvas
  21548. */
  21549. this.onPointerObservable = new BABYLON.Observable();
  21550. this._meshPickProceed = false;
  21551. this._currentPickResult = null;
  21552. this._previousPickResult = null;
  21553. this._totalPointersPressed = 0;
  21554. this._doubleClickOccured = false;
  21555. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21556. this.cameraToUseForPointers = null;
  21557. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21558. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21559. this._startingPointerTime = 0;
  21560. this._previousStartingPointerTime = 0;
  21561. // Deterministic lockstep
  21562. this._timeAccumulator = 0;
  21563. this._currentStepId = 0;
  21564. this._currentInternalStep = 0;
  21565. // Keyboard
  21566. /**
  21567. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21568. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21569. */
  21570. this.onPreKeyboardObservable = new BABYLON.Observable();
  21571. /**
  21572. * Observable event triggered each time an keyboard event is received from the hosting window
  21573. */
  21574. this.onKeyboardObservable = new BABYLON.Observable();
  21575. // Coordinate system
  21576. /**
  21577. * use right-handed coordinate system on this scene.
  21578. * @type {boolean}
  21579. */
  21580. this._useRightHandedSystem = false;
  21581. // Fog
  21582. this._fogEnabled = true;
  21583. this._fogMode = Scene.FOGMODE_NONE;
  21584. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21585. this.fogDensity = 0.1;
  21586. this.fogStart = 0;
  21587. this.fogEnd = 1000.0;
  21588. // Lights
  21589. /**
  21590. * is shadow enabled on this scene.
  21591. * @type {boolean}
  21592. */
  21593. this._shadowsEnabled = true;
  21594. /**
  21595. * is light enabled on this scene.
  21596. * @type {boolean}
  21597. */
  21598. this._lightsEnabled = true;
  21599. /**
  21600. * All of the lights added to this scene.
  21601. * @see BABYLON.Light
  21602. * @type {BABYLON.Light[]}
  21603. */
  21604. this.lights = new Array();
  21605. // Cameras
  21606. /** All of the cameras added to this scene. */
  21607. this.cameras = new Array();
  21608. /** All of the active cameras added to this scene. */
  21609. this.activeCameras = new Array();
  21610. // Meshes
  21611. /**
  21612. * All of the tranform nodes added to this scene.
  21613. * @see BABYLON.TransformNode
  21614. * @type {BABYLON.TransformNode[]}
  21615. */
  21616. this.transformNodes = new Array();
  21617. /**
  21618. * All of the (abstract) meshes added to this scene.
  21619. * @see BABYLON.AbstractMesh
  21620. * @type {BABYLON.AbstractMesh[]}
  21621. */
  21622. this.meshes = new Array();
  21623. /**
  21624. * All of the animation groups added to this scene.
  21625. * @see BABYLON.AnimationGroup
  21626. * @type {BABYLON.AnimationGroup[]}
  21627. */
  21628. this.animationGroups = new Array();
  21629. // Geometries
  21630. this._geometries = new Array();
  21631. this.materials = new Array();
  21632. this.multiMaterials = new Array();
  21633. // Textures
  21634. this._texturesEnabled = true;
  21635. this.textures = new Array();
  21636. // Particles
  21637. this.particlesEnabled = true;
  21638. this.particleSystems = new Array();
  21639. // Sprites
  21640. this.spritesEnabled = true;
  21641. this.spriteManagers = new Array();
  21642. /**
  21643. * The list of layers (background and foreground) of the scene.
  21644. */
  21645. this.layers = new Array();
  21646. /**
  21647. * The list of effect layers (highlights/glow) contained in the scene.
  21648. */
  21649. this.effectLayers = new Array();
  21650. // Skeletons
  21651. this._skeletonsEnabled = true;
  21652. this.skeletons = new Array();
  21653. // Morph targets
  21654. this.morphTargetManagers = new Array();
  21655. // Lens flares
  21656. this.lensFlaresEnabled = true;
  21657. this.lensFlareSystems = new Array();
  21658. // Collisions
  21659. this.collisionsEnabled = true;
  21660. /** Defines the gravity applied to this scene */
  21661. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21662. // Postprocesses
  21663. this.postProcesses = new Array();
  21664. this.postProcessesEnabled = true;
  21665. // Customs render targets
  21666. this.renderTargetsEnabled = true;
  21667. this.dumpNextRenderTargets = false;
  21668. this.customRenderTargets = new Array();
  21669. // Imported meshes
  21670. this.importedMeshesFiles = new Array();
  21671. // Probes
  21672. this.probesEnabled = true;
  21673. this.reflectionProbes = new Array();
  21674. this._actionManagers = new Array();
  21675. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21676. // Procedural textures
  21677. this.proceduralTexturesEnabled = true;
  21678. this._proceduralTextures = new Array();
  21679. this.soundTracks = new Array();
  21680. this._audioEnabled = true;
  21681. this._headphone = false;
  21682. // Performance counters
  21683. this._totalVertices = new BABYLON.PerfCounter();
  21684. this._activeIndices = new BABYLON.PerfCounter();
  21685. this._activeParticles = new BABYLON.PerfCounter();
  21686. this._activeBones = new BABYLON.PerfCounter();
  21687. this._animationTime = 0;
  21688. this.animationTimeScale = 1;
  21689. this._renderId = 0;
  21690. this._executeWhenReadyTimeoutId = -1;
  21691. this._intermediateRendering = false;
  21692. this._viewUpdateFlag = -1;
  21693. this._projectionUpdateFlag = -1;
  21694. this._alternateViewUpdateFlag = -1;
  21695. this._alternateProjectionUpdateFlag = -1;
  21696. this._toBeDisposed = new BABYLON.SmartArray(256);
  21697. this._activeRequests = new Array();
  21698. this._pendingData = new Array();
  21699. this._isDisposed = false;
  21700. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21701. this._activeMeshes = new BABYLON.SmartArray(256);
  21702. this._processedMaterials = new BABYLON.SmartArray(256);
  21703. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21704. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21705. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21706. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21707. this._activeAnimatables = new Array();
  21708. this._transformMatrix = BABYLON.Matrix.Zero();
  21709. this._useAlternateCameraConfiguration = false;
  21710. this._alternateRendering = false;
  21711. this.requireLightSorting = false;
  21712. this._depthRenderer = {};
  21713. this._activeMeshesFrozen = false;
  21714. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21715. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21716. this._engine.scenes.push(this);
  21717. this._uid = null;
  21718. this._renderingManager = new BABYLON.RenderingManager(this);
  21719. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21720. if (BABYLON.OutlineRenderer) {
  21721. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21722. }
  21723. if (BABYLON.Tools.IsWindowObjectExist()) {
  21724. this.attachControl();
  21725. }
  21726. //simplification queue
  21727. if (BABYLON.SimplificationQueue) {
  21728. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21729. }
  21730. //collision coordinator initialization. For now legacy per default.
  21731. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21732. // Uniform Buffer
  21733. this._createUbo();
  21734. // Default Image processing definition.
  21735. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21736. }
  21737. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21738. /** The fog is deactivated */
  21739. get: function () {
  21740. return Scene._FOGMODE_NONE;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21746. /** The fog density is following an exponential function */
  21747. get: function () {
  21748. return Scene._FOGMODE_EXP;
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21754. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21755. get: function () {
  21756. return Scene._FOGMODE_EXP2;
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21762. /** The fog density is following a linear function. */
  21763. get: function () {
  21764. return Scene._FOGMODE_LINEAR;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21770. /**
  21771. * Texture used in all pbr material as the reflection texture.
  21772. * As in the majority of the scene they are the same (exception for multi room and so on),
  21773. * this is easier to reference from here than from all the materials.
  21774. */
  21775. get: function () {
  21776. return this._environmentTexture;
  21777. },
  21778. /**
  21779. * Texture used in all pbr material as the reflection texture.
  21780. * As in the majority of the scene they are the same (exception for multi room and so on),
  21781. * this is easier to set here than in all the materials.
  21782. */
  21783. set: function (value) {
  21784. if (this._environmentTexture === value) {
  21785. return;
  21786. }
  21787. this._environmentTexture = value;
  21788. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21794. /**
  21795. * Default image processing configuration used either in the rendering
  21796. * Forward main pass or through the imageProcessingPostProcess if present.
  21797. * As in the majority of the scene they are the same (exception for multi camera),
  21798. * this is easier to reference from here than from all the materials and post process.
  21799. *
  21800. * No setter as we it is a shared configuration, you can set the values instead.
  21801. */
  21802. get: function () {
  21803. return this._imageProcessingConfiguration;
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21809. get: function () {
  21810. return this._forcePointsCloud;
  21811. },
  21812. set: function (value) {
  21813. if (this._forcePointsCloud === value) {
  21814. return;
  21815. }
  21816. this._forcePointsCloud = value;
  21817. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21818. },
  21819. enumerable: true,
  21820. configurable: true
  21821. });
  21822. Object.defineProperty(Scene.prototype, "onDispose", {
  21823. /** A function to be executed when this scene is disposed. */
  21824. set: function (callback) {
  21825. if (this._onDisposeObserver) {
  21826. this.onDisposeObservable.remove(this._onDisposeObserver);
  21827. }
  21828. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Scene.prototype, "beforeRender", {
  21834. /** A function to be executed before rendering this scene */
  21835. set: function (callback) {
  21836. if (this._onBeforeRenderObserver) {
  21837. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21838. }
  21839. if (callback) {
  21840. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21841. }
  21842. },
  21843. enumerable: true,
  21844. configurable: true
  21845. });
  21846. Object.defineProperty(Scene.prototype, "afterRender", {
  21847. /** A function to be executed after rendering this scene */
  21848. set: function (callback) {
  21849. if (this._onAfterRenderObserver) {
  21850. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21851. }
  21852. if (callback) {
  21853. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21854. }
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21860. set: function (callback) {
  21861. if (this._onBeforeCameraRenderObserver) {
  21862. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21863. }
  21864. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21870. set: function (callback) {
  21871. if (this._onAfterCameraRenderObserver) {
  21872. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21873. }
  21874. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21880. get: function () {
  21881. if (!this._gamepadManager) {
  21882. this._gamepadManager = new BABYLON.GamepadManager(this);
  21883. }
  21884. return this._gamepadManager;
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21890. get: function () {
  21891. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21897. get: function () {
  21898. return this._useRightHandedSystem;
  21899. },
  21900. set: function (value) {
  21901. if (this._useRightHandedSystem === value) {
  21902. return;
  21903. }
  21904. this._useRightHandedSystem = value;
  21905. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Scene.prototype.setStepId = function (newStepId) {
  21911. this._currentStepId = newStepId;
  21912. };
  21913. ;
  21914. Scene.prototype.getStepId = function () {
  21915. return this._currentStepId;
  21916. };
  21917. ;
  21918. Scene.prototype.getInternalStep = function () {
  21919. return this._currentInternalStep;
  21920. };
  21921. ;
  21922. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21923. get: function () {
  21924. return this._fogEnabled;
  21925. },
  21926. /**
  21927. * is fog enabled on this scene.
  21928. */
  21929. set: function (value) {
  21930. if (this._fogEnabled === value) {
  21931. return;
  21932. }
  21933. this._fogEnabled = value;
  21934. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Object.defineProperty(Scene.prototype, "fogMode", {
  21940. get: function () {
  21941. return this._fogMode;
  21942. },
  21943. set: function (value) {
  21944. if (this._fogMode === value) {
  21945. return;
  21946. }
  21947. this._fogMode = value;
  21948. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21954. get: function () {
  21955. return this._shadowsEnabled;
  21956. },
  21957. set: function (value) {
  21958. if (this._shadowsEnabled === value) {
  21959. return;
  21960. }
  21961. this._shadowsEnabled = value;
  21962. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21968. get: function () {
  21969. return this._lightsEnabled;
  21970. },
  21971. set: function (value) {
  21972. if (this._lightsEnabled === value) {
  21973. return;
  21974. }
  21975. this._lightsEnabled = value;
  21976. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21982. /** The default material used on meshes when no material is affected */
  21983. get: function () {
  21984. if (!this._defaultMaterial) {
  21985. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21986. }
  21987. return this._defaultMaterial;
  21988. },
  21989. /** The default material used on meshes when no material is affected */
  21990. set: function (value) {
  21991. this._defaultMaterial = value;
  21992. },
  21993. enumerable: true,
  21994. configurable: true
  21995. });
  21996. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21997. get: function () {
  21998. return this._texturesEnabled;
  21999. },
  22000. set: function (value) {
  22001. if (this._texturesEnabled === value) {
  22002. return;
  22003. }
  22004. this._texturesEnabled = value;
  22005. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22011. get: function () {
  22012. return this._skeletonsEnabled;
  22013. },
  22014. set: function (value) {
  22015. if (this._skeletonsEnabled === value) {
  22016. return;
  22017. }
  22018. this._skeletonsEnabled = value;
  22019. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22025. get: function () {
  22026. if (!this._postProcessRenderPipelineManager) {
  22027. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22028. }
  22029. return this._postProcessRenderPipelineManager;
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22035. get: function () {
  22036. if (!this._mainSoundTrack) {
  22037. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22038. }
  22039. return this._mainSoundTrack;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22045. get: function () {
  22046. return this._alternateRendering;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22052. get: function () {
  22053. return this._frustumPlanes;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22059. /**
  22060. * Gets the current geometry buffer associated to the scene.
  22061. */
  22062. get: function () {
  22063. return this._geometryBufferRenderer;
  22064. },
  22065. /**
  22066. * Sets the current geometry buffer for the scene.
  22067. */
  22068. set: function (geometryBufferRenderer) {
  22069. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22070. this._geometryBufferRenderer = geometryBufferRenderer;
  22071. }
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(Scene.prototype, "debugLayer", {
  22077. // Properties
  22078. get: function () {
  22079. if (!this._debugLayer) {
  22080. this._debugLayer = new BABYLON.DebugLayer(this);
  22081. }
  22082. return this._debugLayer;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22088. get: function () {
  22089. return this._workerCollisions;
  22090. },
  22091. set: function (enabled) {
  22092. if (!BABYLON.CollisionCoordinatorLegacy) {
  22093. return;
  22094. }
  22095. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22096. this._workerCollisions = enabled;
  22097. if (this.collisionCoordinator) {
  22098. this.collisionCoordinator.destroy();
  22099. }
  22100. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22101. this.collisionCoordinator.init(this);
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22107. get: function () {
  22108. return this._selectionOctree;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22114. /**
  22115. * The mesh that is currently under the pointer.
  22116. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22117. */
  22118. get: function () {
  22119. return this._pointerOverMesh;
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. Object.defineProperty(Scene.prototype, "pointerX", {
  22125. /**
  22126. * Current on-screen X position of the pointer
  22127. * @return {number} X position of the pointer
  22128. */
  22129. get: function () {
  22130. return this._pointerX;
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Object.defineProperty(Scene.prototype, "pointerY", {
  22136. /**
  22137. * Current on-screen Y position of the pointer
  22138. * @return {number} Y position of the pointer
  22139. */
  22140. get: function () {
  22141. return this._pointerY;
  22142. },
  22143. enumerable: true,
  22144. configurable: true
  22145. });
  22146. Scene.prototype.getCachedMaterial = function () {
  22147. return this._cachedMaterial;
  22148. };
  22149. Scene.prototype.getCachedEffect = function () {
  22150. return this._cachedEffect;
  22151. };
  22152. Scene.prototype.getCachedVisibility = function () {
  22153. return this._cachedVisibility;
  22154. };
  22155. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22156. if (visibility === void 0) { visibility = 1; }
  22157. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22158. };
  22159. Scene.prototype.getBoundingBoxRenderer = function () {
  22160. if (!this._boundingBoxRenderer) {
  22161. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22162. }
  22163. return this._boundingBoxRenderer;
  22164. };
  22165. Scene.prototype.getOutlineRenderer = function () {
  22166. return this._outlineRenderer;
  22167. };
  22168. Scene.prototype.getEngine = function () {
  22169. return this._engine;
  22170. };
  22171. Scene.prototype.getTotalVertices = function () {
  22172. return this._totalVertices.current;
  22173. };
  22174. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22175. get: function () {
  22176. return this._totalVertices;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Scene.prototype.getActiveIndices = function () {
  22182. return this._activeIndices.current;
  22183. };
  22184. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22185. get: function () {
  22186. return this._activeIndices;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Scene.prototype.getActiveParticles = function () {
  22192. return this._activeParticles.current;
  22193. };
  22194. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22195. get: function () {
  22196. return this._activeParticles;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Scene.prototype.getActiveBones = function () {
  22202. return this._activeBones.current;
  22203. };
  22204. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22205. get: function () {
  22206. return this._activeBones;
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. // Stats
  22212. Scene.prototype.getInterFramePerfCounter = function () {
  22213. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22214. return 0;
  22215. };
  22216. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22217. get: function () {
  22218. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22219. return null;
  22220. },
  22221. enumerable: true,
  22222. configurable: true
  22223. });
  22224. Scene.prototype.getLastFrameDuration = function () {
  22225. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22226. return 0;
  22227. };
  22228. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22229. get: function () {
  22230. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22231. return null;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22237. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22238. return 0;
  22239. };
  22240. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22241. get: function () {
  22242. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22243. return null;
  22244. },
  22245. enumerable: true,
  22246. configurable: true
  22247. });
  22248. Scene.prototype.getActiveMeshes = function () {
  22249. return this._activeMeshes;
  22250. };
  22251. Scene.prototype.getRenderTargetsDuration = function () {
  22252. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22253. return 0;
  22254. };
  22255. Scene.prototype.getRenderDuration = function () {
  22256. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22257. return 0;
  22258. };
  22259. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22260. get: function () {
  22261. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22262. return null;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. Scene.prototype.getParticlesDuration = function () {
  22268. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22269. return 0;
  22270. };
  22271. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22272. get: function () {
  22273. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22274. return null;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Scene.prototype.getSpritesDuration = function () {
  22280. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22281. return 0;
  22282. };
  22283. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22284. get: function () {
  22285. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22286. return null;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Scene.prototype.getAnimationRatio = function () {
  22292. return this._animationRatio;
  22293. };
  22294. Scene.prototype.getRenderId = function () {
  22295. return this._renderId;
  22296. };
  22297. Scene.prototype.incrementRenderId = function () {
  22298. this._renderId++;
  22299. };
  22300. Scene.prototype._updatePointerPosition = function (evt) {
  22301. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22302. if (!canvasRect) {
  22303. return;
  22304. }
  22305. this._pointerX = evt.clientX - canvasRect.left;
  22306. this._pointerY = evt.clientY - canvasRect.top;
  22307. this._unTranslatedPointerX = this._pointerX;
  22308. this._unTranslatedPointerY = this._pointerY;
  22309. };
  22310. Scene.prototype._createUbo = function () {
  22311. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22312. this._sceneUbo.addUniform("viewProjection", 16);
  22313. this._sceneUbo.addUniform("view", 16);
  22314. };
  22315. Scene.prototype._createAlternateUbo = function () {
  22316. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22317. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22318. this._alternateSceneUbo.addUniform("view", 16);
  22319. };
  22320. // Pointers handling
  22321. /**
  22322. * Use this method to simulate a pointer move on a mesh
  22323. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22324. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22325. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22326. */
  22327. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22328. var evt = new PointerEvent("pointermove", pointerEventInit);
  22329. return this._processPointerMove(pickResult, evt);
  22330. };
  22331. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22332. var canvas = this._engine.getRenderingCanvas();
  22333. if (!canvas) {
  22334. return this;
  22335. }
  22336. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22337. this.setPointerOverSprite(null);
  22338. this.setPointerOverMesh(pickResult.pickedMesh);
  22339. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22340. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22341. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22342. }
  22343. else {
  22344. canvas.style.cursor = this.hoverCursor;
  22345. }
  22346. }
  22347. else {
  22348. canvas.style.cursor = this.defaultCursor;
  22349. }
  22350. }
  22351. else {
  22352. this.setPointerOverMesh(null);
  22353. // Sprites
  22354. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22355. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22356. this.setPointerOverSprite(pickResult.pickedSprite);
  22357. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22358. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22359. }
  22360. else {
  22361. canvas.style.cursor = this.hoverCursor;
  22362. }
  22363. }
  22364. else {
  22365. this.setPointerOverSprite(null);
  22366. // Restore pointer
  22367. canvas.style.cursor = this.defaultCursor;
  22368. }
  22369. }
  22370. if (pickResult) {
  22371. if (this.onPointerMove) {
  22372. this.onPointerMove(evt, pickResult);
  22373. }
  22374. if (this.onPointerObservable.hasObservers()) {
  22375. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22376. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22377. this.onPointerObservable.notifyObservers(pi, type);
  22378. }
  22379. }
  22380. return this;
  22381. };
  22382. /**
  22383. * Use this method to simulate a pointer down on a mesh
  22384. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22385. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22386. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22387. */
  22388. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22389. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22390. return this._processPointerDown(pickResult, evt);
  22391. };
  22392. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22393. var _this = this;
  22394. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22395. this._pickedDownMesh = pickResult.pickedMesh;
  22396. var actionManager = pickResult.pickedMesh.actionManager;
  22397. if (actionManager) {
  22398. if (actionManager.hasPickTriggers) {
  22399. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22400. switch (evt.button) {
  22401. case 0:
  22402. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22403. break;
  22404. case 1:
  22405. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22406. break;
  22407. case 2:
  22408. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22409. break;
  22410. }
  22411. }
  22412. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22413. window.setTimeout(function () {
  22414. 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);
  22415. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22416. if (_this._totalPointersPressed !== 0 &&
  22417. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22418. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22419. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22420. _this._startingPointerTime = 0;
  22421. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22422. }
  22423. }
  22424. }, Scene.LongPressDelay);
  22425. }
  22426. }
  22427. }
  22428. if (pickResult) {
  22429. if (this.onPointerDown) {
  22430. this.onPointerDown(evt, pickResult);
  22431. }
  22432. if (this.onPointerObservable.hasObservers()) {
  22433. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22434. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22435. this.onPointerObservable.notifyObservers(pi, type);
  22436. }
  22437. }
  22438. return this;
  22439. };
  22440. /**
  22441. * Use this method to simulate a pointer up on a mesh
  22442. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22443. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22444. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22445. */
  22446. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22447. var evt = new PointerEvent("pointerup", pointerEventInit);
  22448. var clickInfo = new ClickInfo();
  22449. clickInfo.singleClick = true;
  22450. clickInfo.ignore = true;
  22451. return this._processPointerUp(pickResult, evt, clickInfo);
  22452. };
  22453. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22454. if (pickResult && pickResult && pickResult.pickedMesh) {
  22455. this._pickedUpMesh = pickResult.pickedMesh;
  22456. if (this._pickedDownMesh === this._pickedUpMesh) {
  22457. if (this.onPointerPick) {
  22458. this.onPointerPick(evt, pickResult);
  22459. }
  22460. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22461. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22462. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22463. this.onPointerObservable.notifyObservers(pi, type);
  22464. }
  22465. }
  22466. if (pickResult.pickedMesh.actionManager) {
  22467. if (clickInfo.ignore) {
  22468. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22469. }
  22470. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22471. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22472. }
  22473. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22474. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22475. }
  22476. }
  22477. }
  22478. if (this._pickedDownMesh &&
  22479. this._pickedDownMesh.actionManager &&
  22480. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22481. this._pickedDownMesh !== this._pickedUpMesh) {
  22482. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22483. }
  22484. if (this.onPointerUp) {
  22485. this.onPointerUp(evt, pickResult);
  22486. }
  22487. if (this.onPointerObservable.hasObservers()) {
  22488. if (!clickInfo.ignore) {
  22489. if (!clickInfo.hasSwiped) {
  22490. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22491. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22492. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22493. this.onPointerObservable.notifyObservers(pi, type);
  22494. }
  22495. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22496. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22497. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22498. this.onPointerObservable.notifyObservers(pi, type);
  22499. }
  22500. }
  22501. }
  22502. else {
  22503. var type = BABYLON.PointerEventTypes.POINTERUP;
  22504. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22505. this.onPointerObservable.notifyObservers(pi, type);
  22506. }
  22507. }
  22508. return this;
  22509. };
  22510. /**
  22511. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22512. * @param attachUp defines if you want to attach events to pointerup
  22513. * @param attachDown defines if you want to attach events to pointerdown
  22514. * @param attachMove defines if you want to attach events to pointermove
  22515. */
  22516. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22517. var _this = this;
  22518. if (attachUp === void 0) { attachUp = true; }
  22519. if (attachDown === void 0) { attachDown = true; }
  22520. if (attachMove === void 0) { attachMove = true; }
  22521. this._initActionManager = function (act, clickInfo) {
  22522. if (!_this._meshPickProceed) {
  22523. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22524. _this._currentPickResult = pickResult;
  22525. if (pickResult) {
  22526. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22527. }
  22528. _this._meshPickProceed = true;
  22529. }
  22530. return act;
  22531. };
  22532. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22533. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22534. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22535. btn !== _this._previousButtonPressed) {
  22536. _this._doubleClickOccured = false;
  22537. clickInfo.singleClick = true;
  22538. clickInfo.ignore = false;
  22539. cb(clickInfo, _this._currentPickResult);
  22540. }
  22541. };
  22542. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22543. var clickInfo = new ClickInfo();
  22544. _this._currentPickResult = null;
  22545. var act = null;
  22546. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22547. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22548. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22549. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22550. act = _this._initActionManager(act, clickInfo);
  22551. if (act)
  22552. checkPicking = act.hasPickTriggers;
  22553. }
  22554. if (checkPicking) {
  22555. var btn = evt.button;
  22556. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22557. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22558. if (!clickInfo.hasSwiped) {
  22559. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22560. if (!checkSingleClickImmediately) {
  22561. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22562. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22563. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22564. act = _this._initActionManager(act, clickInfo);
  22565. if (act)
  22566. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22567. }
  22568. }
  22569. if (checkSingleClickImmediately) {
  22570. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22571. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22572. btn !== _this._previousButtonPressed) {
  22573. clickInfo.singleClick = true;
  22574. cb(clickInfo, _this._currentPickResult);
  22575. }
  22576. }
  22577. else {
  22578. // wait that no double click has been raised during the double click delay
  22579. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22580. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22581. }
  22582. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22583. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22584. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22585. act = _this._initActionManager(act, clickInfo);
  22586. if (act)
  22587. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22588. }
  22589. if (checkDoubleClick) {
  22590. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22591. if (btn === _this._previousButtonPressed &&
  22592. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22593. !_this._doubleClickOccured) {
  22594. // pointer has not moved for 2 clicks, it's a double click
  22595. if (!clickInfo.hasSwiped &&
  22596. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22597. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22598. _this._previousStartingPointerTime = 0;
  22599. _this._doubleClickOccured = true;
  22600. clickInfo.doubleClick = true;
  22601. clickInfo.ignore = false;
  22602. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22603. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22604. }
  22605. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22606. cb(clickInfo, _this._currentPickResult);
  22607. }
  22608. else {
  22609. _this._doubleClickOccured = false;
  22610. _this._previousStartingPointerTime = _this._startingPointerTime;
  22611. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22612. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22613. _this._previousButtonPressed = btn;
  22614. if (Scene.ExclusiveDoubleClickMode) {
  22615. if (_this._previousDelayedSimpleClickTimeout) {
  22616. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22617. }
  22618. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22619. cb(clickInfo, _this._previousPickResult);
  22620. }
  22621. else {
  22622. cb(clickInfo, _this._currentPickResult);
  22623. }
  22624. }
  22625. }
  22626. else {
  22627. _this._doubleClickOccured = false;
  22628. _this._previousStartingPointerTime = _this._startingPointerTime;
  22629. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22630. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22631. _this._previousButtonPressed = btn;
  22632. }
  22633. }
  22634. }
  22635. }
  22636. clickInfo.ignore = true;
  22637. cb(clickInfo, _this._currentPickResult);
  22638. };
  22639. this._spritePredicate = function (sprite) {
  22640. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22641. };
  22642. this._onPointerMove = function (evt) {
  22643. _this._updatePointerPosition(evt);
  22644. // PreObservable support
  22645. if (_this.onPrePointerObservable.hasObservers()) {
  22646. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22647. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22648. _this.onPrePointerObservable.notifyObservers(pi, type);
  22649. if (pi.skipOnPointerObservable) {
  22650. return;
  22651. }
  22652. }
  22653. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22654. return;
  22655. }
  22656. if (!_this.pointerMovePredicate) {
  22657. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22658. }
  22659. // Meshes
  22660. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22661. _this._processPointerMove(pickResult, evt);
  22662. };
  22663. this._onPointerDown = function (evt) {
  22664. _this._totalPointersPressed++;
  22665. _this._pickedDownMesh = null;
  22666. _this._meshPickProceed = false;
  22667. _this._updatePointerPosition(evt);
  22668. if (_this.preventDefaultOnPointerDown && canvas) {
  22669. evt.preventDefault();
  22670. canvas.focus();
  22671. }
  22672. // PreObservable support
  22673. if (_this.onPrePointerObservable.hasObservers()) {
  22674. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22675. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22676. _this.onPrePointerObservable.notifyObservers(pi, type);
  22677. if (pi.skipOnPointerObservable) {
  22678. return;
  22679. }
  22680. }
  22681. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22682. return;
  22683. }
  22684. _this._startingPointerPosition.x = _this._pointerX;
  22685. _this._startingPointerPosition.y = _this._pointerY;
  22686. _this._startingPointerTime = new Date().getTime();
  22687. if (!_this.pointerDownPredicate) {
  22688. _this.pointerDownPredicate = function (mesh) {
  22689. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22690. };
  22691. }
  22692. // Meshes
  22693. _this._pickedDownMesh = null;
  22694. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22695. _this._processPointerDown(pickResult, evt);
  22696. // Sprites
  22697. _this._pickedDownSprite = null;
  22698. if (_this.spriteManagers.length > 0) {
  22699. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22700. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22701. if (pickResult.pickedSprite.actionManager) {
  22702. _this._pickedDownSprite = pickResult.pickedSprite;
  22703. switch (evt.button) {
  22704. case 0:
  22705. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22706. break;
  22707. case 1:
  22708. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22709. break;
  22710. case 2:
  22711. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22712. break;
  22713. }
  22714. if (pickResult.pickedSprite.actionManager) {
  22715. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22716. }
  22717. }
  22718. }
  22719. }
  22720. };
  22721. this._onPointerUp = function (evt) {
  22722. if (_this._totalPointersPressed === 0) {
  22723. return; // So we need to test it the pointer down was pressed before.
  22724. }
  22725. _this._totalPointersPressed--;
  22726. _this._pickedUpMesh = null;
  22727. _this._meshPickProceed = false;
  22728. _this._updatePointerPosition(evt);
  22729. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22730. // PreObservable support
  22731. if (_this.onPrePointerObservable.hasObservers()) {
  22732. if (!clickInfo.ignore) {
  22733. if (!clickInfo.hasSwiped) {
  22734. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22735. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22736. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22737. _this.onPrePointerObservable.notifyObservers(pi, type);
  22738. if (pi.skipOnPointerObservable) {
  22739. return;
  22740. }
  22741. }
  22742. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22743. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22744. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22745. _this.onPrePointerObservable.notifyObservers(pi, type);
  22746. if (pi.skipOnPointerObservable) {
  22747. return;
  22748. }
  22749. }
  22750. }
  22751. }
  22752. else {
  22753. var type = BABYLON.PointerEventTypes.POINTERUP;
  22754. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22755. _this.onPrePointerObservable.notifyObservers(pi, type);
  22756. if (pi.skipOnPointerObservable) {
  22757. return;
  22758. }
  22759. }
  22760. }
  22761. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22762. return;
  22763. }
  22764. if (!_this.pointerUpPredicate) {
  22765. _this.pointerUpPredicate = function (mesh) {
  22766. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22767. };
  22768. }
  22769. // Meshes
  22770. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22771. _this._initActionManager(null, clickInfo);
  22772. }
  22773. if (!pickResult) {
  22774. pickResult = _this._currentPickResult;
  22775. }
  22776. _this._processPointerUp(pickResult, evt, clickInfo);
  22777. // Sprites
  22778. if (_this.spriteManagers.length > 0) {
  22779. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22780. if (spritePickResult) {
  22781. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22782. if (spritePickResult.pickedSprite.actionManager) {
  22783. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22784. if (spritePickResult.pickedSprite.actionManager) {
  22785. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22786. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22787. }
  22788. }
  22789. }
  22790. }
  22791. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22792. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22793. }
  22794. }
  22795. }
  22796. _this._previousPickResult = _this._currentPickResult;
  22797. });
  22798. };
  22799. this._onKeyDown = function (evt) {
  22800. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22801. if (_this.onPreKeyboardObservable.hasObservers()) {
  22802. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22803. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22804. if (pi.skipOnPointerObservable) {
  22805. return;
  22806. }
  22807. }
  22808. if (_this.onKeyboardObservable.hasObservers()) {
  22809. var pi = new BABYLON.KeyboardInfo(type, evt);
  22810. _this.onKeyboardObservable.notifyObservers(pi, type);
  22811. }
  22812. if (_this.actionManager) {
  22813. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22814. }
  22815. };
  22816. this._onKeyUp = function (evt) {
  22817. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22818. if (_this.onPreKeyboardObservable.hasObservers()) {
  22819. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22820. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22821. if (pi.skipOnPointerObservable) {
  22822. return;
  22823. }
  22824. }
  22825. if (_this.onKeyboardObservable.hasObservers()) {
  22826. var pi = new BABYLON.KeyboardInfo(type, evt);
  22827. _this.onKeyboardObservable.notifyObservers(pi, type);
  22828. }
  22829. if (_this.actionManager) {
  22830. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22831. }
  22832. };
  22833. var engine = this.getEngine();
  22834. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22835. if (!canvas) {
  22836. return;
  22837. }
  22838. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22839. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22840. });
  22841. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22842. if (!canvas) {
  22843. return;
  22844. }
  22845. canvas.removeEventListener("keydown", _this._onKeyDown);
  22846. canvas.removeEventListener("keyup", _this._onKeyUp);
  22847. });
  22848. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22849. var canvas = this._engine.getRenderingCanvas();
  22850. if (!canvas) {
  22851. return;
  22852. }
  22853. if (attachMove) {
  22854. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22855. // Wheel
  22856. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22857. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22858. }
  22859. if (attachDown) {
  22860. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22861. }
  22862. if (attachUp) {
  22863. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22864. }
  22865. canvas.tabIndex = 1;
  22866. };
  22867. Scene.prototype.detachControl = function () {
  22868. var engine = this.getEngine();
  22869. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22870. var canvas = engine.getRenderingCanvas();
  22871. if (!canvas) {
  22872. return;
  22873. }
  22874. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22875. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22876. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22877. if (this._onCanvasBlurObserver) {
  22878. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22879. }
  22880. if (this._onCanvasFocusObserver) {
  22881. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22882. }
  22883. // Wheel
  22884. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22885. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22886. // Keyboard
  22887. canvas.removeEventListener("keydown", this._onKeyDown);
  22888. canvas.removeEventListener("keyup", this._onKeyUp);
  22889. // Observables
  22890. this.onKeyboardObservable.clear();
  22891. this.onPreKeyboardObservable.clear();
  22892. this.onPointerObservable.clear();
  22893. this.onPrePointerObservable.clear();
  22894. };
  22895. /**
  22896. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22897. * Delay loaded resources are not taking in account
  22898. * @return true if all required resources are ready
  22899. */
  22900. Scene.prototype.isReady = function () {
  22901. if (this._isDisposed) {
  22902. return false;
  22903. }
  22904. if (this._pendingData.length > 0) {
  22905. return false;
  22906. }
  22907. var index;
  22908. var engine = this.getEngine();
  22909. // Geometries
  22910. for (index = 0; index < this._geometries.length; index++) {
  22911. var geometry = this._geometries[index];
  22912. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22913. return false;
  22914. }
  22915. }
  22916. // Meshes
  22917. for (index = 0; index < this.meshes.length; index++) {
  22918. var mesh = this.meshes[index];
  22919. if (!mesh.isEnabled()) {
  22920. continue;
  22921. }
  22922. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22923. continue;
  22924. }
  22925. if (!mesh.isReady(true)) {
  22926. return false;
  22927. }
  22928. // Effect layers
  22929. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22930. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22931. var layer = _a[_i];
  22932. if (!layer.hasMesh(mesh)) {
  22933. continue;
  22934. }
  22935. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22936. var subMesh = _c[_b];
  22937. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22938. return false;
  22939. }
  22940. }
  22941. }
  22942. }
  22943. return true;
  22944. };
  22945. Scene.prototype.resetCachedMaterial = function () {
  22946. this._cachedMaterial = null;
  22947. this._cachedEffect = null;
  22948. this._cachedVisibility = null;
  22949. };
  22950. Scene.prototype.registerBeforeRender = function (func) {
  22951. this.onBeforeRenderObservable.add(func);
  22952. };
  22953. Scene.prototype.unregisterBeforeRender = function (func) {
  22954. this.onBeforeRenderObservable.removeCallback(func);
  22955. };
  22956. Scene.prototype.registerAfterRender = function (func) {
  22957. this.onAfterRenderObservable.add(func);
  22958. };
  22959. Scene.prototype.unregisterAfterRender = function (func) {
  22960. this.onAfterRenderObservable.removeCallback(func);
  22961. };
  22962. Scene.prototype._executeOnceBeforeRender = function (func) {
  22963. var _this = this;
  22964. var execFunc = function () {
  22965. func();
  22966. setTimeout(function () {
  22967. _this.unregisterBeforeRender(execFunc);
  22968. });
  22969. };
  22970. this.registerBeforeRender(execFunc);
  22971. };
  22972. /**
  22973. * The provided function will run before render once and will be disposed afterwards.
  22974. * A timeout delay can be provided so that the function will be executed in N ms.
  22975. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22976. * @param func The function to be executed.
  22977. * @param timeout optional delay in ms
  22978. */
  22979. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22980. var _this = this;
  22981. if (timeout !== undefined) {
  22982. setTimeout(function () {
  22983. _this._executeOnceBeforeRender(func);
  22984. }, timeout);
  22985. }
  22986. else {
  22987. this._executeOnceBeforeRender(func);
  22988. }
  22989. };
  22990. Scene.prototype._addPendingData = function (data) {
  22991. this._pendingData.push(data);
  22992. };
  22993. Scene.prototype._removePendingData = function (data) {
  22994. var wasLoading = this.isLoading;
  22995. var index = this._pendingData.indexOf(data);
  22996. if (index !== -1) {
  22997. this._pendingData.splice(index, 1);
  22998. }
  22999. if (wasLoading && !this.isLoading) {
  23000. this.onDataLoadedObservable.notifyObservers(this);
  23001. }
  23002. };
  23003. Scene.prototype.getWaitingItemsCount = function () {
  23004. return this._pendingData.length;
  23005. };
  23006. Object.defineProperty(Scene.prototype, "isLoading", {
  23007. get: function () {
  23008. return this._pendingData.length > 0;
  23009. },
  23010. enumerable: true,
  23011. configurable: true
  23012. });
  23013. /**
  23014. * Registers a function to be executed when the scene is ready.
  23015. * @param {Function} func - the function to be executed.
  23016. */
  23017. Scene.prototype.executeWhenReady = function (func) {
  23018. var _this = this;
  23019. this.onReadyObservable.add(func);
  23020. if (this._executeWhenReadyTimeoutId !== -1) {
  23021. return;
  23022. }
  23023. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23024. _this._checkIsReady();
  23025. }, 150);
  23026. };
  23027. /**
  23028. * Returns a promise that resolves when the scene is ready.
  23029. * @returns A promise that resolves when the scene is ready.
  23030. */
  23031. Scene.prototype.whenReadyAsync = function () {
  23032. var _this = this;
  23033. return new Promise(function (resolve) {
  23034. _this.executeWhenReady(function () {
  23035. resolve();
  23036. });
  23037. });
  23038. };
  23039. Scene.prototype._checkIsReady = function () {
  23040. var _this = this;
  23041. if (this.isReady()) {
  23042. this.onReadyObservable.notifyObservers(this);
  23043. this.onReadyObservable.clear();
  23044. this._executeWhenReadyTimeoutId = -1;
  23045. return;
  23046. }
  23047. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23048. _this._checkIsReady();
  23049. }, 150);
  23050. };
  23051. // Animations
  23052. /**
  23053. * Will start the animation sequence of a given target
  23054. * @param target - the target
  23055. * @param {number} from - from which frame should animation start
  23056. * @param {number} to - till which frame should animation run.
  23057. * @param {boolean} [loop] - should the animation loop
  23058. * @param {number} [speedRatio] - the speed in which to run the animation
  23059. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23060. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23061. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23062. * See BABYLON.Animatable
  23063. */
  23064. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23065. if (speedRatio === void 0) { speedRatio = 1.0; }
  23066. if (from > to && speedRatio > 0) {
  23067. speedRatio *= -1;
  23068. }
  23069. this.stopAnimation(target);
  23070. if (!animatable) {
  23071. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23072. }
  23073. // Local animations
  23074. if (target.animations) {
  23075. animatable.appendAnimations(target, target.animations);
  23076. }
  23077. // Children animations
  23078. if (target.getAnimatables) {
  23079. var animatables = target.getAnimatables();
  23080. for (var index = 0; index < animatables.length; index++) {
  23081. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23082. }
  23083. }
  23084. animatable.reset();
  23085. return animatable;
  23086. };
  23087. /**
  23088. * Begin a new animation on a given node
  23089. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23090. * @param {BABYLON.Animation[]} defines the list of animations to start
  23091. * @param {number} from defines the initial value
  23092. * @param {number} to defines the final value
  23093. * @param {boolean} loop defines if you want animation to loop (off by default)
  23094. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23095. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23096. * @returns the list of created animatables
  23097. */
  23098. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23099. if (speedRatio === undefined) {
  23100. speedRatio = 1.0;
  23101. }
  23102. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23103. return animatable;
  23104. };
  23105. /**
  23106. * Begin a new animation on a given node and its hierarchy
  23107. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23108. * @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.
  23109. * @param {BABYLON.Animation[]} defines the list of animations to start
  23110. * @param {number} from defines the initial value
  23111. * @param {number} to defines the final value
  23112. * @param {boolean} loop defines if you want animation to loop (off by default)
  23113. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23114. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23115. * @returns the list of animatables created for all nodes
  23116. */
  23117. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23118. var children = target.getDescendants(directDescendantsOnly);
  23119. var result = [];
  23120. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23121. var child = children_1[_i];
  23122. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23123. }
  23124. return result;
  23125. };
  23126. Scene.prototype.getAnimatableByTarget = function (target) {
  23127. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23128. if (this._activeAnimatables[index].target === target) {
  23129. return this._activeAnimatables[index];
  23130. }
  23131. }
  23132. return null;
  23133. };
  23134. Object.defineProperty(Scene.prototype, "animatables", {
  23135. get: function () {
  23136. return this._activeAnimatables;
  23137. },
  23138. enumerable: true,
  23139. configurable: true
  23140. });
  23141. /**
  23142. * Will stop the animation of the given target
  23143. * @param target - the target
  23144. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23145. * @see beginAnimation
  23146. */
  23147. Scene.prototype.stopAnimation = function (target, animationName) {
  23148. var animatable = this.getAnimatableByTarget(target);
  23149. if (animatable) {
  23150. animatable.stop(animationName);
  23151. }
  23152. };
  23153. /**
  23154. * Stops and removes all animations that have been applied to the scene
  23155. */
  23156. Scene.prototype.stopAllAnimations = function () {
  23157. if (this._activeAnimatables) {
  23158. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23159. this._activeAnimatables[i].stop();
  23160. }
  23161. this._activeAnimatables = [];
  23162. }
  23163. };
  23164. Scene.prototype._animate = function () {
  23165. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23166. return;
  23167. }
  23168. // Getting time
  23169. var now = BABYLON.Tools.Now;
  23170. if (!this._animationTimeLast) {
  23171. if (this._pendingData.length > 0) {
  23172. return;
  23173. }
  23174. this._animationTimeLast = now;
  23175. }
  23176. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23177. this._animationTime += deltaTime;
  23178. this._animationTimeLast = now;
  23179. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23180. this._activeAnimatables[index]._animate(this._animationTime);
  23181. }
  23182. };
  23183. // Matrix
  23184. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23185. this._useAlternateCameraConfiguration = active;
  23186. };
  23187. Scene.prototype.getViewMatrix = function () {
  23188. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23189. };
  23190. Scene.prototype.getProjectionMatrix = function () {
  23191. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23192. };
  23193. Scene.prototype.getTransformMatrix = function () {
  23194. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23195. };
  23196. Scene.prototype.setTransformMatrix = function (view, projection) {
  23197. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23198. return;
  23199. }
  23200. this._viewUpdateFlag = view.updateFlag;
  23201. this._projectionUpdateFlag = projection.updateFlag;
  23202. this._viewMatrix = view;
  23203. this._projectionMatrix = projection;
  23204. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23205. // Update frustum
  23206. if (!this._frustumPlanes) {
  23207. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23208. }
  23209. else {
  23210. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23211. }
  23212. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23213. var otherCamera = this.activeCamera._alternateCamera;
  23214. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23215. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23216. }
  23217. if (this._sceneUbo.useUbo) {
  23218. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23219. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23220. this._sceneUbo.update();
  23221. }
  23222. };
  23223. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23224. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23225. return;
  23226. }
  23227. this._alternateViewUpdateFlag = view.updateFlag;
  23228. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23229. this._alternateViewMatrix = view;
  23230. this._alternateProjectionMatrix = projection;
  23231. if (!this._alternateTransformMatrix) {
  23232. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23233. }
  23234. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23235. if (!this._alternateSceneUbo) {
  23236. this._createAlternateUbo();
  23237. }
  23238. if (this._alternateSceneUbo.useUbo) {
  23239. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23240. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23241. this._alternateSceneUbo.update();
  23242. }
  23243. };
  23244. Scene.prototype.getSceneUniformBuffer = function () {
  23245. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23246. };
  23247. // Methods
  23248. Scene.prototype.getUniqueId = function () {
  23249. var result = Scene._uniqueIdCounter;
  23250. Scene._uniqueIdCounter++;
  23251. return result;
  23252. };
  23253. Scene.prototype.addMesh = function (newMesh) {
  23254. this.meshes.push(newMesh);
  23255. //notify the collision coordinator
  23256. if (this.collisionCoordinator) {
  23257. this.collisionCoordinator.onMeshAdded(newMesh);
  23258. }
  23259. newMesh._resyncLightSources();
  23260. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23261. };
  23262. Scene.prototype.removeMesh = function (toRemove) {
  23263. var index = this.meshes.indexOf(toRemove);
  23264. if (index !== -1) {
  23265. // Remove from the scene if mesh found
  23266. this.meshes.splice(index, 1);
  23267. }
  23268. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23269. return index;
  23270. };
  23271. Scene.prototype.addTransformNode = function (newTransformNode) {
  23272. this.transformNodes.push(newTransformNode);
  23273. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23274. };
  23275. Scene.prototype.removeTransformNode = function (toRemove) {
  23276. var index = this.transformNodes.indexOf(toRemove);
  23277. if (index !== -1) {
  23278. // Remove from the scene if found
  23279. this.transformNodes.splice(index, 1);
  23280. }
  23281. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23282. return index;
  23283. };
  23284. Scene.prototype.removeSkeleton = function (toRemove) {
  23285. var index = this.skeletons.indexOf(toRemove);
  23286. if (index !== -1) {
  23287. // Remove from the scene if found
  23288. this.skeletons.splice(index, 1);
  23289. }
  23290. return index;
  23291. };
  23292. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23293. var index = this.morphTargetManagers.indexOf(toRemove);
  23294. if (index !== -1) {
  23295. // Remove from the scene if found
  23296. this.morphTargetManagers.splice(index, 1);
  23297. }
  23298. return index;
  23299. };
  23300. Scene.prototype.removeLight = function (toRemove) {
  23301. var index = this.lights.indexOf(toRemove);
  23302. if (index !== -1) {
  23303. // Remove from meshes
  23304. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23305. var mesh = _a[_i];
  23306. mesh._removeLightSource(toRemove);
  23307. }
  23308. // Remove from the scene if mesh found
  23309. this.lights.splice(index, 1);
  23310. this.sortLightsByPriority();
  23311. }
  23312. this.onLightRemovedObservable.notifyObservers(toRemove);
  23313. return index;
  23314. };
  23315. Scene.prototype.removeCamera = function (toRemove) {
  23316. var index = this.cameras.indexOf(toRemove);
  23317. if (index !== -1) {
  23318. // Remove from the scene if mesh found
  23319. this.cameras.splice(index, 1);
  23320. }
  23321. // Remove from activeCameras
  23322. var index2 = this.activeCameras.indexOf(toRemove);
  23323. if (index2 !== -1) {
  23324. // Remove from the scene if mesh found
  23325. this.activeCameras.splice(index2, 1);
  23326. }
  23327. // Reset the activeCamera
  23328. if (this.activeCamera === toRemove) {
  23329. if (this.cameras.length > 0) {
  23330. this.activeCamera = this.cameras[0];
  23331. }
  23332. else {
  23333. this.activeCamera = null;
  23334. }
  23335. }
  23336. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23337. return index;
  23338. };
  23339. Scene.prototype.removeParticleSystem = function (toRemove) {
  23340. var index = this.particleSystems.indexOf(toRemove);
  23341. if (index !== -1) {
  23342. this.particleSystems.splice(index, 1);
  23343. }
  23344. return index;
  23345. };
  23346. ;
  23347. Scene.prototype.removeAnimation = function (toRemove) {
  23348. var index = this.animations.indexOf(toRemove);
  23349. if (index !== -1) {
  23350. this.animations.splice(index, 1);
  23351. }
  23352. return index;
  23353. };
  23354. ;
  23355. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23356. var index = this.multiMaterials.indexOf(toRemove);
  23357. if (index !== -1) {
  23358. this.multiMaterials.splice(index, 1);
  23359. }
  23360. return index;
  23361. };
  23362. ;
  23363. Scene.prototype.removeMaterial = function (toRemove) {
  23364. var index = this.materials.indexOf(toRemove);
  23365. if (index !== -1) {
  23366. this.materials.splice(index, 1);
  23367. }
  23368. return index;
  23369. };
  23370. ;
  23371. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23372. var index = this.lensFlareSystems.indexOf(toRemove);
  23373. if (index !== -1) {
  23374. this.lensFlareSystems.splice(index, 1);
  23375. }
  23376. return index;
  23377. };
  23378. ;
  23379. Scene.prototype.removeActionManager = function (toRemove) {
  23380. var index = this._actionManagers.indexOf(toRemove);
  23381. if (index !== -1) {
  23382. this._actionManagers.splice(index, 1);
  23383. }
  23384. return index;
  23385. };
  23386. ;
  23387. Scene.prototype.addLight = function (newLight) {
  23388. this.lights.push(newLight);
  23389. this.sortLightsByPriority();
  23390. // Add light to all meshes (To support if the light is removed and then readded)
  23391. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23392. var mesh = _a[_i];
  23393. if (mesh._lightSources.indexOf(newLight) === -1) {
  23394. mesh._lightSources.push(newLight);
  23395. mesh._resyncLightSources();
  23396. }
  23397. }
  23398. this.onNewLightAddedObservable.notifyObservers(newLight);
  23399. };
  23400. Scene.prototype.sortLightsByPriority = function () {
  23401. if (this.requireLightSorting) {
  23402. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23403. }
  23404. };
  23405. Scene.prototype.addCamera = function (newCamera) {
  23406. this.cameras.push(newCamera);
  23407. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23408. };
  23409. Scene.prototype.addSkeleton = function (newSkeleton) {
  23410. this.skeletons.push(newSkeleton);
  23411. };
  23412. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23413. this.particleSystems.push(newParticleSystem);
  23414. };
  23415. Scene.prototype.addAnimation = function (newAnimation) {
  23416. this.animations.push(newAnimation);
  23417. };
  23418. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23419. this.multiMaterials.push(newMultiMaterial);
  23420. };
  23421. Scene.prototype.addMaterial = function (newMaterial) {
  23422. this.materials.push(newMaterial);
  23423. };
  23424. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23425. this.morphTargetManagers.push(newMorphTargetManager);
  23426. };
  23427. Scene.prototype.addGeometry = function (newGeometrie) {
  23428. this._geometries.push(newGeometrie);
  23429. };
  23430. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23431. this.lensFlareSystems.push(newLensFlareSystem);
  23432. };
  23433. Scene.prototype.addActionManager = function (newActionManager) {
  23434. this._actionManagers.push(newActionManager);
  23435. };
  23436. /**
  23437. * Switch active camera
  23438. * @param {Camera} newCamera - new active camera
  23439. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23440. */
  23441. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23442. if (attachControl === void 0) { attachControl = true; }
  23443. var canvas = this._engine.getRenderingCanvas();
  23444. if (!canvas) {
  23445. return;
  23446. }
  23447. if (this.activeCamera) {
  23448. this.activeCamera.detachControl(canvas);
  23449. }
  23450. this.activeCamera = newCamera;
  23451. if (attachControl) {
  23452. newCamera.attachControl(canvas);
  23453. }
  23454. };
  23455. /**
  23456. * sets the active camera of the scene using its ID
  23457. * @param {string} id - the camera's ID
  23458. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23459. * @see activeCamera
  23460. */
  23461. Scene.prototype.setActiveCameraByID = function (id) {
  23462. var camera = this.getCameraByID(id);
  23463. if (camera) {
  23464. this.activeCamera = camera;
  23465. return camera;
  23466. }
  23467. return null;
  23468. };
  23469. /**
  23470. * sets the active camera of the scene using its name
  23471. * @param {string} name - the camera's name
  23472. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23473. * @see activeCamera
  23474. */
  23475. Scene.prototype.setActiveCameraByName = function (name) {
  23476. var camera = this.getCameraByName(name);
  23477. if (camera) {
  23478. this.activeCamera = camera;
  23479. return camera;
  23480. }
  23481. return null;
  23482. };
  23483. /**
  23484. * get an animation group using its name
  23485. * @param {string} the material's name
  23486. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23487. */
  23488. Scene.prototype.getAnimationGroupByName = function (name) {
  23489. for (var index = 0; index < this.animationGroups.length; index++) {
  23490. if (this.animationGroups[index].name === name) {
  23491. return this.animationGroups[index];
  23492. }
  23493. }
  23494. return null;
  23495. };
  23496. /**
  23497. * get a material using its id
  23498. * @param {string} the material's ID
  23499. * @return {BABYLON.Material|null} the material or null if none found.
  23500. */
  23501. Scene.prototype.getMaterialByID = function (id) {
  23502. for (var index = 0; index < this.materials.length; index++) {
  23503. if (this.materials[index].id === id) {
  23504. return this.materials[index];
  23505. }
  23506. }
  23507. return null;
  23508. };
  23509. /**
  23510. * get a material using its name
  23511. * @param {string} the material's name
  23512. * @return {BABYLON.Material|null} the material or null if none found.
  23513. */
  23514. Scene.prototype.getMaterialByName = function (name) {
  23515. for (var index = 0; index < this.materials.length; index++) {
  23516. if (this.materials[index].name === name) {
  23517. return this.materials[index];
  23518. }
  23519. }
  23520. return null;
  23521. };
  23522. Scene.prototype.getLensFlareSystemByName = function (name) {
  23523. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23524. if (this.lensFlareSystems[index].name === name) {
  23525. return this.lensFlareSystems[index];
  23526. }
  23527. }
  23528. return null;
  23529. };
  23530. Scene.prototype.getLensFlareSystemByID = function (id) {
  23531. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23532. if (this.lensFlareSystems[index].id === id) {
  23533. return this.lensFlareSystems[index];
  23534. }
  23535. }
  23536. return null;
  23537. };
  23538. Scene.prototype.getCameraByID = function (id) {
  23539. for (var index = 0; index < this.cameras.length; index++) {
  23540. if (this.cameras[index].id === id) {
  23541. return this.cameras[index];
  23542. }
  23543. }
  23544. return null;
  23545. };
  23546. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23547. for (var index = 0; index < this.cameras.length; index++) {
  23548. if (this.cameras[index].uniqueId === uniqueId) {
  23549. return this.cameras[index];
  23550. }
  23551. }
  23552. return null;
  23553. };
  23554. /**
  23555. * get a camera using its name
  23556. * @param {string} the camera's name
  23557. * @return {BABYLON.Camera|null} the camera or null if none found.
  23558. */
  23559. Scene.prototype.getCameraByName = function (name) {
  23560. for (var index = 0; index < this.cameras.length; index++) {
  23561. if (this.cameras[index].name === name) {
  23562. return this.cameras[index];
  23563. }
  23564. }
  23565. return null;
  23566. };
  23567. /**
  23568. * get a bone using its id
  23569. * @param {string} the bone's id
  23570. * @return {BABYLON.Bone|null} the bone or null if not found
  23571. */
  23572. Scene.prototype.getBoneByID = function (id) {
  23573. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23574. var skeleton = this.skeletons[skeletonIndex];
  23575. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23576. if (skeleton.bones[boneIndex].id === id) {
  23577. return skeleton.bones[boneIndex];
  23578. }
  23579. }
  23580. }
  23581. return null;
  23582. };
  23583. /**
  23584. * get a bone using its id
  23585. * @param {string} the bone's name
  23586. * @return {BABYLON.Bone|null} the bone or null if not found
  23587. */
  23588. Scene.prototype.getBoneByName = function (name) {
  23589. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23590. var skeleton = this.skeletons[skeletonIndex];
  23591. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23592. if (skeleton.bones[boneIndex].name === name) {
  23593. return skeleton.bones[boneIndex];
  23594. }
  23595. }
  23596. }
  23597. return null;
  23598. };
  23599. /**
  23600. * get a light node using its name
  23601. * @param {string} the light's name
  23602. * @return {BABYLON.Light|null} the light or null if none found.
  23603. */
  23604. Scene.prototype.getLightByName = function (name) {
  23605. for (var index = 0; index < this.lights.length; index++) {
  23606. if (this.lights[index].name === name) {
  23607. return this.lights[index];
  23608. }
  23609. }
  23610. return null;
  23611. };
  23612. /**
  23613. * get a light node using its ID
  23614. * @param {string} the light's id
  23615. * @return {BABYLON.Light|null} the light or null if none found.
  23616. */
  23617. Scene.prototype.getLightByID = function (id) {
  23618. for (var index = 0; index < this.lights.length; index++) {
  23619. if (this.lights[index].id === id) {
  23620. return this.lights[index];
  23621. }
  23622. }
  23623. return null;
  23624. };
  23625. /**
  23626. * get a light node using its scene-generated unique ID
  23627. * @param {number} the light's unique id
  23628. * @return {BABYLON.Light|null} the light or null if none found.
  23629. */
  23630. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23631. for (var index = 0; index < this.lights.length; index++) {
  23632. if (this.lights[index].uniqueId === uniqueId) {
  23633. return this.lights[index];
  23634. }
  23635. }
  23636. return null;
  23637. };
  23638. /**
  23639. * get a particle system by id
  23640. * @param id {number} the particle system id
  23641. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23642. */
  23643. Scene.prototype.getParticleSystemByID = function (id) {
  23644. for (var index = 0; index < this.particleSystems.length; index++) {
  23645. if (this.particleSystems[index].id === id) {
  23646. return this.particleSystems[index];
  23647. }
  23648. }
  23649. return null;
  23650. };
  23651. /**
  23652. * get a geometry using its ID
  23653. * @param {string} the geometry's id
  23654. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23655. */
  23656. Scene.prototype.getGeometryByID = function (id) {
  23657. for (var index = 0; index < this._geometries.length; index++) {
  23658. if (this._geometries[index].id === id) {
  23659. return this._geometries[index];
  23660. }
  23661. }
  23662. return null;
  23663. };
  23664. /**
  23665. * add a new geometry to this scene.
  23666. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23667. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23668. * @return {boolean} was the geometry added or not
  23669. */
  23670. Scene.prototype.pushGeometry = function (geometry, force) {
  23671. if (!force && this.getGeometryByID(geometry.id)) {
  23672. return false;
  23673. }
  23674. this._geometries.push(geometry);
  23675. //notify the collision coordinator
  23676. if (this.collisionCoordinator) {
  23677. this.collisionCoordinator.onGeometryAdded(geometry);
  23678. }
  23679. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23680. return true;
  23681. };
  23682. /**
  23683. * Removes an existing geometry
  23684. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23685. * @return {boolean} was the geometry removed or not
  23686. */
  23687. Scene.prototype.removeGeometry = function (geometry) {
  23688. var index = this._geometries.indexOf(geometry);
  23689. if (index > -1) {
  23690. this._geometries.splice(index, 1);
  23691. //notify the collision coordinator
  23692. if (this.collisionCoordinator) {
  23693. this.collisionCoordinator.onGeometryDeleted(geometry);
  23694. }
  23695. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23696. return true;
  23697. }
  23698. return false;
  23699. };
  23700. Scene.prototype.getGeometries = function () {
  23701. return this._geometries;
  23702. };
  23703. /**
  23704. * Get the first added mesh found of a given ID
  23705. * @param {string} id - the id to search for
  23706. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23707. */
  23708. Scene.prototype.getMeshByID = function (id) {
  23709. for (var index = 0; index < this.meshes.length; index++) {
  23710. if (this.meshes[index].id === id) {
  23711. return this.meshes[index];
  23712. }
  23713. }
  23714. return null;
  23715. };
  23716. Scene.prototype.getMeshesByID = function (id) {
  23717. return this.meshes.filter(function (m) {
  23718. return m.id === id;
  23719. });
  23720. };
  23721. /**
  23722. * Get the first added transform node found of a given ID
  23723. * @param {string} id - the id to search for
  23724. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23725. */
  23726. Scene.prototype.getTransformNodeByID = function (id) {
  23727. for (var index = 0; index < this.transformNodes.length; index++) {
  23728. if (this.transformNodes[index].id === id) {
  23729. return this.transformNodes[index];
  23730. }
  23731. }
  23732. return null;
  23733. };
  23734. Scene.prototype.getTransformNodesByID = function (id) {
  23735. return this.transformNodes.filter(function (m) {
  23736. return m.id === id;
  23737. });
  23738. };
  23739. /**
  23740. * Get a mesh with its auto-generated unique id
  23741. * @param {number} uniqueId - the unique id to search for
  23742. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23743. */
  23744. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23745. for (var index = 0; index < this.meshes.length; index++) {
  23746. if (this.meshes[index].uniqueId === uniqueId) {
  23747. return this.meshes[index];
  23748. }
  23749. }
  23750. return null;
  23751. };
  23752. /**
  23753. * Get a the last added mesh found of a given ID
  23754. * @param {string} id - the id to search for
  23755. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23756. */
  23757. Scene.prototype.getLastMeshByID = function (id) {
  23758. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23759. if (this.meshes[index].id === id) {
  23760. return this.meshes[index];
  23761. }
  23762. }
  23763. return null;
  23764. };
  23765. /**
  23766. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23767. * @param {string} id - the id to search for
  23768. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23769. */
  23770. Scene.prototype.getLastEntryByID = function (id) {
  23771. var index;
  23772. for (index = this.meshes.length - 1; index >= 0; index--) {
  23773. if (this.meshes[index].id === id) {
  23774. return this.meshes[index];
  23775. }
  23776. }
  23777. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23778. if (this.transformNodes[index].id === id) {
  23779. return this.transformNodes[index];
  23780. }
  23781. }
  23782. for (index = this.cameras.length - 1; index >= 0; index--) {
  23783. if (this.cameras[index].id === id) {
  23784. return this.cameras[index];
  23785. }
  23786. }
  23787. for (index = this.lights.length - 1; index >= 0; index--) {
  23788. if (this.lights[index].id === id) {
  23789. return this.lights[index];
  23790. }
  23791. }
  23792. return null;
  23793. };
  23794. Scene.prototype.getNodeByID = function (id) {
  23795. var mesh = this.getMeshByID(id);
  23796. if (mesh) {
  23797. return mesh;
  23798. }
  23799. var light = this.getLightByID(id);
  23800. if (light) {
  23801. return light;
  23802. }
  23803. var camera = this.getCameraByID(id);
  23804. if (camera) {
  23805. return camera;
  23806. }
  23807. var bone = this.getBoneByID(id);
  23808. return bone;
  23809. };
  23810. Scene.prototype.getNodeByName = function (name) {
  23811. var mesh = this.getMeshByName(name);
  23812. if (mesh) {
  23813. return mesh;
  23814. }
  23815. var light = this.getLightByName(name);
  23816. if (light) {
  23817. return light;
  23818. }
  23819. var camera = this.getCameraByName(name);
  23820. if (camera) {
  23821. return camera;
  23822. }
  23823. var bone = this.getBoneByName(name);
  23824. return bone;
  23825. };
  23826. Scene.prototype.getMeshByName = function (name) {
  23827. for (var index = 0; index < this.meshes.length; index++) {
  23828. if (this.meshes[index].name === name) {
  23829. return this.meshes[index];
  23830. }
  23831. }
  23832. return null;
  23833. };
  23834. Scene.prototype.getTransformNodeByName = function (name) {
  23835. for (var index = 0; index < this.transformNodes.length; index++) {
  23836. if (this.transformNodes[index].name === name) {
  23837. return this.transformNodes[index];
  23838. }
  23839. }
  23840. return null;
  23841. };
  23842. Scene.prototype.getSoundByName = function (name) {
  23843. var index;
  23844. if (BABYLON.AudioEngine) {
  23845. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23846. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23847. return this.mainSoundTrack.soundCollection[index];
  23848. }
  23849. }
  23850. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23851. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23852. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23853. return this.soundTracks[sdIndex].soundCollection[index];
  23854. }
  23855. }
  23856. }
  23857. }
  23858. return null;
  23859. };
  23860. Scene.prototype.getLastSkeletonByID = function (id) {
  23861. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23862. if (this.skeletons[index].id === id) {
  23863. return this.skeletons[index];
  23864. }
  23865. }
  23866. return null;
  23867. };
  23868. Scene.prototype.getSkeletonById = function (id) {
  23869. for (var index = 0; index < this.skeletons.length; index++) {
  23870. if (this.skeletons[index].id === id) {
  23871. return this.skeletons[index];
  23872. }
  23873. }
  23874. return null;
  23875. };
  23876. Scene.prototype.getSkeletonByName = function (name) {
  23877. for (var index = 0; index < this.skeletons.length; index++) {
  23878. if (this.skeletons[index].name === name) {
  23879. return this.skeletons[index];
  23880. }
  23881. }
  23882. return null;
  23883. };
  23884. Scene.prototype.getMorphTargetManagerById = function (id) {
  23885. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23886. if (this.morphTargetManagers[index].uniqueId === id) {
  23887. return this.morphTargetManagers[index];
  23888. }
  23889. }
  23890. return null;
  23891. };
  23892. Scene.prototype.isActiveMesh = function (mesh) {
  23893. return (this._activeMeshes.indexOf(mesh) !== -1);
  23894. };
  23895. /**
  23896. * Return a the first highlight layer of the scene with a given name.
  23897. * @param name The name of the highlight layer to look for.
  23898. * @return The highlight layer if found otherwise null.
  23899. */
  23900. Scene.prototype.getHighlightLayerByName = function (name) {
  23901. for (var index = 0; index < this.effectLayers.length; index++) {
  23902. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23903. return this.effectLayers[index];
  23904. }
  23905. }
  23906. return null;
  23907. };
  23908. /**
  23909. * Return a the first highlight layer of the scene with a given name.
  23910. * @param name The name of the highlight layer to look for.
  23911. * @return The highlight layer if found otherwise null.
  23912. */
  23913. Scene.prototype.getGlowLayerByName = function (name) {
  23914. for (var index = 0; index < this.effectLayers.length; index++) {
  23915. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23916. return this.effectLayers[index];
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. Object.defineProperty(Scene.prototype, "uid", {
  23922. /**
  23923. * Return a unique id as a string which can serve as an identifier for the scene
  23924. */
  23925. get: function () {
  23926. if (!this._uid) {
  23927. this._uid = BABYLON.Tools.RandomId();
  23928. }
  23929. return this._uid;
  23930. },
  23931. enumerable: true,
  23932. configurable: true
  23933. });
  23934. /**
  23935. * Add an externaly attached data from its key.
  23936. * This method call will fail and return false, if such key already exists.
  23937. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23938. * @param key the unique key that identifies the data
  23939. * @param data the data object to associate to the key for this Engine instance
  23940. * @return true if no such key were already present and the data was added successfully, false otherwise
  23941. */
  23942. Scene.prototype.addExternalData = function (key, data) {
  23943. if (!this._externalData) {
  23944. this._externalData = new BABYLON.StringDictionary();
  23945. }
  23946. return this._externalData.add(key, data);
  23947. };
  23948. /**
  23949. * Get an externaly attached data from its key
  23950. * @param key the unique key that identifies the data
  23951. * @return the associated data, if present (can be null), or undefined if not present
  23952. */
  23953. Scene.prototype.getExternalData = function (key) {
  23954. if (!this._externalData) {
  23955. return null;
  23956. }
  23957. return this._externalData.get(key);
  23958. };
  23959. /**
  23960. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23961. * @param key the unique key that identifies the data
  23962. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23963. * @return the associated data, can be null if the factory returned null.
  23964. */
  23965. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23966. if (!this._externalData) {
  23967. this._externalData = new BABYLON.StringDictionary();
  23968. }
  23969. return this._externalData.getOrAddWithFactory(key, factory);
  23970. };
  23971. /**
  23972. * Remove an externaly attached data from the Engine instance
  23973. * @param key the unique key that identifies the data
  23974. * @return true if the data was successfully removed, false if it doesn't exist
  23975. */
  23976. Scene.prototype.removeExternalData = function (key) {
  23977. return this._externalData.remove(key);
  23978. };
  23979. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23980. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23981. if (mesh.showSubMeshesBoundingBox) {
  23982. var boundingInfo = subMesh.getBoundingInfo();
  23983. if (boundingInfo !== null && boundingInfo !== undefined) {
  23984. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23985. }
  23986. }
  23987. var material = subMesh.getMaterial();
  23988. if (material !== null && material !== undefined) {
  23989. // Render targets
  23990. if (material.getRenderTargetTextures !== undefined) {
  23991. if (this._processedMaterials.indexOf(material) === -1) {
  23992. this._processedMaterials.push(material);
  23993. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23994. }
  23995. }
  23996. // Dispatch
  23997. this._activeIndices.addCount(subMesh.indexCount, false);
  23998. this._renderingManager.dispatch(subMesh, mesh, material);
  23999. }
  24000. }
  24001. };
  24002. Scene.prototype._isInIntermediateRendering = function () {
  24003. return this._intermediateRendering;
  24004. };
  24005. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24006. this._activeMeshCandidateProvider = provider;
  24007. };
  24008. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24009. return this._activeMeshCandidateProvider;
  24010. };
  24011. /**
  24012. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24013. */
  24014. Scene.prototype.freezeActiveMeshes = function () {
  24015. this._evaluateActiveMeshes();
  24016. this._activeMeshesFrozen = true;
  24017. return this;
  24018. };
  24019. /**
  24020. * Use this function to restart evaluating active meshes on every frame
  24021. */
  24022. Scene.prototype.unfreezeActiveMeshes = function () {
  24023. this._activeMeshesFrozen = false;
  24024. return this;
  24025. };
  24026. Scene.prototype._evaluateActiveMeshes = function () {
  24027. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24028. return;
  24029. }
  24030. if (!this.activeCamera) {
  24031. return;
  24032. }
  24033. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24034. this.activeCamera._activeMeshes.reset();
  24035. this._activeMeshes.reset();
  24036. this._renderingManager.reset();
  24037. this._processedMaterials.reset();
  24038. this._activeParticleSystems.reset();
  24039. this._activeSkeletons.reset();
  24040. this._softwareSkinnedMeshes.reset();
  24041. if (this._boundingBoxRenderer) {
  24042. this._boundingBoxRenderer.reset();
  24043. }
  24044. // Meshes
  24045. var meshes;
  24046. var len;
  24047. var checkIsEnabled = true;
  24048. // Determine mesh candidates
  24049. if (this._activeMeshCandidateProvider !== undefined) {
  24050. // Use _activeMeshCandidateProvider
  24051. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24052. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24053. if (meshes !== undefined) {
  24054. len = meshes.length;
  24055. }
  24056. else {
  24057. len = 0;
  24058. }
  24059. }
  24060. else if (this._selectionOctree !== undefined) {
  24061. // Octree
  24062. var selection = this._selectionOctree.select(this._frustumPlanes);
  24063. meshes = selection.data;
  24064. len = selection.length;
  24065. }
  24066. else {
  24067. // Full scene traversal
  24068. len = this.meshes.length;
  24069. meshes = this.meshes;
  24070. }
  24071. // Check each mesh
  24072. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24073. mesh = meshes[meshIndex];
  24074. if (mesh.isBlocked) {
  24075. continue;
  24076. }
  24077. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24078. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24079. continue;
  24080. }
  24081. mesh.computeWorldMatrix();
  24082. // Intersections
  24083. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24084. this._meshesForIntersections.pushNoDuplicate(mesh);
  24085. }
  24086. // Switch to current LOD
  24087. meshLOD = mesh.getLOD(this.activeCamera);
  24088. if (meshLOD === undefined || meshLOD === null) {
  24089. continue;
  24090. }
  24091. mesh._preActivate();
  24092. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24093. this._activeMeshes.push(mesh);
  24094. this.activeCamera._activeMeshes.push(mesh);
  24095. mesh._activate(this._renderId);
  24096. if (meshLOD !== mesh) {
  24097. meshLOD._activate(this._renderId);
  24098. }
  24099. this._activeMesh(mesh, meshLOD);
  24100. }
  24101. }
  24102. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24103. // Particle systems
  24104. if (this.particlesEnabled) {
  24105. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24106. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24107. var particleSystem = this.particleSystems[particleIndex];
  24108. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24109. continue;
  24110. }
  24111. var emitter = particleSystem.emitter;
  24112. if (!emitter.position || emitter.isEnabled()) {
  24113. this._activeParticleSystems.push(particleSystem);
  24114. particleSystem.animate();
  24115. this._renderingManager.dispatchParticles(particleSystem);
  24116. }
  24117. }
  24118. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24119. }
  24120. };
  24121. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24122. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24123. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24124. mesh.skeleton.prepare();
  24125. }
  24126. if (!mesh.computeBonesUsingShaders) {
  24127. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24128. }
  24129. }
  24130. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24131. var boundingInfo = sourceMesh.getBoundingInfo();
  24132. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24133. }
  24134. if (mesh !== undefined && mesh !== null
  24135. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24136. // Submeshes Octrees
  24137. var len;
  24138. var subMeshes;
  24139. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24140. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24141. len = intersections.length;
  24142. subMeshes = intersections.data;
  24143. }
  24144. else {
  24145. subMeshes = mesh.subMeshes;
  24146. len = subMeshes.length;
  24147. }
  24148. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24149. subMesh = subMeshes[subIndex];
  24150. this._evaluateSubMesh(subMesh, mesh);
  24151. }
  24152. }
  24153. };
  24154. Scene.prototype.updateTransformMatrix = function (force) {
  24155. if (!this.activeCamera) {
  24156. return;
  24157. }
  24158. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24159. };
  24160. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24161. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24162. };
  24163. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24164. if (camera && camera._skipRendering) {
  24165. return;
  24166. }
  24167. var engine = this._engine;
  24168. this.activeCamera = camera;
  24169. if (!this.activeCamera)
  24170. throw new Error("Active camera not set");
  24171. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24172. // Viewport
  24173. engine.setViewport(this.activeCamera.viewport);
  24174. // Camera
  24175. this.resetCachedMaterial();
  24176. this._renderId++;
  24177. this.updateTransformMatrix();
  24178. if (camera._alternateCamera) {
  24179. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24180. this._alternateRendering = true;
  24181. }
  24182. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24183. // Meshes
  24184. this._evaluateActiveMeshes();
  24185. // Software skinning
  24186. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24187. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24188. mesh.applySkeleton(mesh.skeleton);
  24189. }
  24190. // Render targets
  24191. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24192. var needsRestoreFrameBuffer = false;
  24193. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24194. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24195. }
  24196. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24197. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24198. }
  24199. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24200. this._intermediateRendering = true;
  24201. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24202. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24203. var renderTarget = this._renderTargets.data[renderIndex];
  24204. if (renderTarget._shouldRender()) {
  24205. this._renderId++;
  24206. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24207. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24208. }
  24209. }
  24210. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24211. this._intermediateRendering = false;
  24212. this._renderId++;
  24213. needsRestoreFrameBuffer = true; // Restore back buffer
  24214. }
  24215. // Render EffecttLayer Texture
  24216. var stencilState = this._engine.getStencilBuffer();
  24217. var renderEffects = false;
  24218. var needStencil = false;
  24219. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24220. this._intermediateRendering = true;
  24221. for (var i = 0; i < this.effectLayers.length; i++) {
  24222. var effectLayer = this.effectLayers[i];
  24223. if (effectLayer.shouldRender() &&
  24224. (!effectLayer.camera ||
  24225. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24226. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24227. renderEffects = true;
  24228. needStencil = needStencil || effectLayer.needStencil();
  24229. var renderTarget = effectLayer._mainTexture;
  24230. if (renderTarget._shouldRender()) {
  24231. this._renderId++;
  24232. renderTarget.render(false, false);
  24233. needsRestoreFrameBuffer = true;
  24234. }
  24235. }
  24236. }
  24237. this._intermediateRendering = false;
  24238. this._renderId++;
  24239. }
  24240. if (needsRestoreFrameBuffer) {
  24241. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24242. }
  24243. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24244. // Prepare Frame
  24245. this.postProcessManager._prepareFrame();
  24246. // Backgrounds
  24247. var layerIndex;
  24248. var layer;
  24249. if (this.layers.length) {
  24250. engine.setDepthBuffer(false);
  24251. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24252. layer = this.layers[layerIndex];
  24253. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24254. layer.render();
  24255. }
  24256. }
  24257. engine.setDepthBuffer(true);
  24258. }
  24259. // Activate effect Layer stencil
  24260. if (needStencil) {
  24261. this._engine.setStencilBuffer(true);
  24262. }
  24263. // Render
  24264. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24265. this._renderingManager.render(null, null, true, true);
  24266. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24267. // Restore effect Layer stencil
  24268. if (needStencil) {
  24269. this._engine.setStencilBuffer(stencilState);
  24270. }
  24271. // Bounding boxes
  24272. if (this._boundingBoxRenderer) {
  24273. this._boundingBoxRenderer.render();
  24274. }
  24275. // Lens flares
  24276. if (this.lensFlaresEnabled) {
  24277. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24278. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24279. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24280. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24281. lensFlareSystem.render();
  24282. }
  24283. }
  24284. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24285. }
  24286. // Foregrounds
  24287. if (this.layers.length) {
  24288. engine.setDepthBuffer(false);
  24289. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24290. layer = this.layers[layerIndex];
  24291. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24292. layer.render();
  24293. }
  24294. }
  24295. engine.setDepthBuffer(true);
  24296. }
  24297. // Effect Layer
  24298. if (renderEffects) {
  24299. engine.setDepthBuffer(false);
  24300. for (var i = 0; i < this.effectLayers.length; i++) {
  24301. if (this.effectLayers[i].shouldRender()) {
  24302. this.effectLayers[i].render();
  24303. }
  24304. }
  24305. engine.setDepthBuffer(true);
  24306. }
  24307. // Finalize frame
  24308. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24309. // Reset some special arrays
  24310. this._renderTargets.reset();
  24311. this._alternateRendering = false;
  24312. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24313. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24314. };
  24315. Scene.prototype._processSubCameras = function (camera) {
  24316. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24317. this._renderForCamera(camera);
  24318. return;
  24319. }
  24320. // rig cameras
  24321. for (var index = 0; index < camera._rigCameras.length; index++) {
  24322. this._renderForCamera(camera._rigCameras[index], camera);
  24323. }
  24324. this.activeCamera = camera;
  24325. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24326. };
  24327. Scene.prototype._checkIntersections = function () {
  24328. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24329. var sourceMesh = this._meshesForIntersections.data[index];
  24330. if (!sourceMesh.actionManager) {
  24331. continue;
  24332. }
  24333. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24334. var action = sourceMesh.actionManager.actions[actionIndex];
  24335. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24336. var parameters = action.getTriggerParameter();
  24337. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24338. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24339. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24340. if (areIntersecting && currentIntersectionInProgress === -1) {
  24341. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24342. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24343. sourceMesh._intersectionsInProgress.push(otherMesh);
  24344. }
  24345. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24346. sourceMesh._intersectionsInProgress.push(otherMesh);
  24347. }
  24348. }
  24349. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24350. //They intersected, and now they don't.
  24351. //is this trigger an exit trigger? execute an event.
  24352. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24353. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24354. }
  24355. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24356. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24357. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24358. }
  24359. }
  24360. }
  24361. }
  24362. }
  24363. };
  24364. Scene.prototype.render = function () {
  24365. if (this.isDisposed) {
  24366. return;
  24367. }
  24368. this._activeParticles.fetchNewFrame();
  24369. this._totalVertices.fetchNewFrame();
  24370. this._activeIndices.fetchNewFrame();
  24371. this._activeBones.fetchNewFrame();
  24372. this._meshesForIntersections.reset();
  24373. this.resetCachedMaterial();
  24374. this.onBeforeAnimationsObservable.notifyObservers(this);
  24375. // Actions
  24376. if (this.actionManager) {
  24377. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24378. }
  24379. //Simplification Queue
  24380. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24381. this.simplificationQueue.executeNext();
  24382. }
  24383. if (this._engine.isDeterministicLockStep()) {
  24384. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24385. var defaultFPS = (60.0 / 1000.0);
  24386. var defaultFrameTime = 1000 / 60; // frame time in MS
  24387. if (this._physicsEngine) {
  24388. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24389. }
  24390. var stepsTaken = 0;
  24391. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24392. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24393. internalSteps = Math.min(internalSteps, maxSubSteps);
  24394. do {
  24395. this.onBeforeStepObservable.notifyObservers(this);
  24396. // Animations
  24397. this._animationRatio = defaultFrameTime * defaultFPS;
  24398. this._animate();
  24399. this.onAfterAnimationsObservable.notifyObservers(this);
  24400. // Physics
  24401. if (this._physicsEngine) {
  24402. this.onBeforePhysicsObservable.notifyObservers(this);
  24403. this._physicsEngine._step(defaultFrameTime / 1000);
  24404. this.onAfterPhysicsObservable.notifyObservers(this);
  24405. }
  24406. this.onAfterStepObservable.notifyObservers(this);
  24407. this._currentStepId++;
  24408. stepsTaken++;
  24409. deltaTime -= defaultFrameTime;
  24410. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24411. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24412. }
  24413. else {
  24414. // Animations
  24415. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24416. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24417. this._animate();
  24418. this.onAfterAnimationsObservable.notifyObservers(this);
  24419. // Physics
  24420. if (this._physicsEngine) {
  24421. this.onBeforePhysicsObservable.notifyObservers(this);
  24422. this._physicsEngine._step(deltaTime / 1000.0);
  24423. this.onAfterPhysicsObservable.notifyObservers(this);
  24424. }
  24425. }
  24426. // update gamepad manager
  24427. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24428. this._gamepadManager._checkGamepadsStatus();
  24429. }
  24430. // Update Cameras
  24431. if (this.activeCameras.length > 0) {
  24432. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24433. var camera = this.activeCameras[cameraIndex];
  24434. camera.update();
  24435. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24436. // rig cameras
  24437. for (var index = 0; index < camera._rigCameras.length; index++) {
  24438. camera._rigCameras[index].update();
  24439. }
  24440. }
  24441. }
  24442. }
  24443. else if (this.activeCamera) {
  24444. this.activeCamera.update();
  24445. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24446. // rig cameras
  24447. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24448. this.activeCamera._rigCameras[index].update();
  24449. }
  24450. }
  24451. }
  24452. // Before render
  24453. this.onBeforeRenderObservable.notifyObservers(this);
  24454. // Customs render targets
  24455. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24456. var engine = this.getEngine();
  24457. var currentActiveCamera = this.activeCamera;
  24458. if (this.renderTargetsEnabled) {
  24459. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24460. this._intermediateRendering = true;
  24461. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24462. var renderTarget = this.customRenderTargets[customIndex];
  24463. if (renderTarget._shouldRender()) {
  24464. this._renderId++;
  24465. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24466. if (!this.activeCamera)
  24467. throw new Error("Active camera not set");
  24468. // Viewport
  24469. engine.setViewport(this.activeCamera.viewport);
  24470. // Camera
  24471. this.updateTransformMatrix();
  24472. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24473. }
  24474. }
  24475. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24476. this._intermediateRendering = false;
  24477. this._renderId++;
  24478. }
  24479. // Restore back buffer
  24480. if (this.customRenderTargets.length > 0) {
  24481. engine.restoreDefaultFramebuffer();
  24482. }
  24483. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24484. this.activeCamera = currentActiveCamera;
  24485. // Procedural textures
  24486. if (this.proceduralTexturesEnabled) {
  24487. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24488. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24489. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24490. if (proceduralTexture._shouldRender()) {
  24491. proceduralTexture.render();
  24492. }
  24493. }
  24494. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24495. }
  24496. // Clear
  24497. if (this.autoClearDepthAndStencil || this.autoClear) {
  24498. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24499. }
  24500. // Shadows
  24501. if (this.shadowsEnabled) {
  24502. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24503. var light = this.lights[lightIndex];
  24504. var shadowGenerator = light.getShadowGenerator();
  24505. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24506. var shadowMap = (shadowGenerator.getShadowMap());
  24507. if (this.textures.indexOf(shadowMap) !== -1) {
  24508. this._renderTargets.push(shadowMap);
  24509. }
  24510. }
  24511. }
  24512. }
  24513. // Depth renderer
  24514. for (var key in this._depthRenderer) {
  24515. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24516. }
  24517. // Geometry renderer
  24518. if (this._geometryBufferRenderer) {
  24519. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24520. }
  24521. // RenderPipeline
  24522. if (this._postProcessRenderPipelineManager) {
  24523. this._postProcessRenderPipelineManager.update();
  24524. }
  24525. // Multi-cameras?
  24526. if (this.activeCameras.length > 0) {
  24527. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24528. if (cameraIndex > 0) {
  24529. this._engine.clear(null, false, true, true);
  24530. }
  24531. this._processSubCameras(this.activeCameras[cameraIndex]);
  24532. }
  24533. }
  24534. else {
  24535. if (!this.activeCamera) {
  24536. throw new Error("No camera defined");
  24537. }
  24538. this._processSubCameras(this.activeCamera);
  24539. }
  24540. // Intersection checks
  24541. this._checkIntersections();
  24542. // Update the audio listener attached to the camera
  24543. if (BABYLON.AudioEngine) {
  24544. this._updateAudioParameters();
  24545. }
  24546. // After render
  24547. if (this.afterRender) {
  24548. this.afterRender();
  24549. }
  24550. this.onAfterRenderObservable.notifyObservers(this);
  24551. // Cleaning
  24552. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24553. var data = this._toBeDisposed.data[index];
  24554. if (data) {
  24555. data.dispose();
  24556. }
  24557. this._toBeDisposed[index] = null;
  24558. }
  24559. this._toBeDisposed.reset();
  24560. if (this.dumpNextRenderTargets) {
  24561. this.dumpNextRenderTargets = false;
  24562. }
  24563. this._activeBones.addCount(0, true);
  24564. this._activeIndices.addCount(0, true);
  24565. this._activeParticles.addCount(0, true);
  24566. };
  24567. Scene.prototype._updateAudioParameters = function () {
  24568. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24569. return;
  24570. }
  24571. var listeningCamera;
  24572. var audioEngine = BABYLON.Engine.audioEngine;
  24573. if (this.activeCameras.length > 0) {
  24574. listeningCamera = this.activeCameras[0];
  24575. }
  24576. else {
  24577. listeningCamera = this.activeCamera;
  24578. }
  24579. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24580. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24581. // for VR cameras
  24582. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24583. listeningCamera = listeningCamera.rigCameras[0];
  24584. }
  24585. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24586. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24587. cameraDirection.normalize();
  24588. // To avoid some errors on GearVR
  24589. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24590. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24591. }
  24592. var i;
  24593. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24594. var sound = this.mainSoundTrack.soundCollection[i];
  24595. if (sound.useCustomAttenuation) {
  24596. sound.updateDistanceFromListener();
  24597. }
  24598. }
  24599. for (i = 0; i < this.soundTracks.length; i++) {
  24600. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24601. sound = this.soundTracks[i].soundCollection[j];
  24602. if (sound.useCustomAttenuation) {
  24603. sound.updateDistanceFromListener();
  24604. }
  24605. }
  24606. }
  24607. }
  24608. };
  24609. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24610. // Audio
  24611. get: function () {
  24612. return this._audioEnabled;
  24613. },
  24614. set: function (value) {
  24615. this._audioEnabled = value;
  24616. if (BABYLON.AudioEngine) {
  24617. if (this._audioEnabled) {
  24618. this._enableAudio();
  24619. }
  24620. else {
  24621. this._disableAudio();
  24622. }
  24623. }
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Scene.prototype._disableAudio = function () {
  24629. var i;
  24630. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24631. this.mainSoundTrack.soundCollection[i].pause();
  24632. }
  24633. for (i = 0; i < this.soundTracks.length; i++) {
  24634. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24635. this.soundTracks[i].soundCollection[j].pause();
  24636. }
  24637. }
  24638. };
  24639. Scene.prototype._enableAudio = function () {
  24640. var i;
  24641. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24642. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24643. this.mainSoundTrack.soundCollection[i].play();
  24644. }
  24645. }
  24646. for (i = 0; i < this.soundTracks.length; i++) {
  24647. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24648. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24649. this.soundTracks[i].soundCollection[j].play();
  24650. }
  24651. }
  24652. }
  24653. };
  24654. Object.defineProperty(Scene.prototype, "headphone", {
  24655. get: function () {
  24656. return this._headphone;
  24657. },
  24658. set: function (value) {
  24659. this._headphone = value;
  24660. if (BABYLON.AudioEngine) {
  24661. if (this._headphone) {
  24662. this._switchAudioModeForHeadphones();
  24663. }
  24664. else {
  24665. this._switchAudioModeForNormalSpeakers();
  24666. }
  24667. }
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Scene.prototype._switchAudioModeForHeadphones = function () {
  24673. this.mainSoundTrack.switchPanningModelToHRTF();
  24674. for (var i = 0; i < this.soundTracks.length; i++) {
  24675. this.soundTracks[i].switchPanningModelToHRTF();
  24676. }
  24677. };
  24678. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24679. this.mainSoundTrack.switchPanningModelToEqualPower();
  24680. for (var i = 0; i < this.soundTracks.length; i++) {
  24681. this.soundTracks[i].switchPanningModelToEqualPower();
  24682. }
  24683. };
  24684. /**
  24685. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24686. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24687. * @returns the created depth renderer
  24688. */
  24689. Scene.prototype.enableDepthRenderer = function (camera) {
  24690. camera = camera || this.activeCamera;
  24691. if (!camera) {
  24692. throw "No camera available to enable depth renderer";
  24693. }
  24694. if (!this._depthRenderer[camera.id]) {
  24695. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24696. }
  24697. return this._depthRenderer[camera.id];
  24698. };
  24699. /**
  24700. * Disables a depth renderer for a given camera
  24701. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24702. */
  24703. Scene.prototype.disableDepthRenderer = function (camera) {
  24704. camera = camera || this.activeCamera;
  24705. if (!camera || !this._depthRenderer[camera.id]) {
  24706. return;
  24707. }
  24708. this._depthRenderer[camera.id].dispose();
  24709. delete this._depthRenderer[camera.id];
  24710. };
  24711. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24712. if (ratio === void 0) { ratio = 1; }
  24713. if (this._geometryBufferRenderer) {
  24714. return this._geometryBufferRenderer;
  24715. }
  24716. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24717. if (!this._geometryBufferRenderer.isSupported) {
  24718. this._geometryBufferRenderer = null;
  24719. }
  24720. return this._geometryBufferRenderer;
  24721. };
  24722. Scene.prototype.disableGeometryBufferRenderer = function () {
  24723. if (!this._geometryBufferRenderer) {
  24724. return;
  24725. }
  24726. this._geometryBufferRenderer.dispose();
  24727. this._geometryBufferRenderer = null;
  24728. };
  24729. Scene.prototype.freezeMaterials = function () {
  24730. for (var i = 0; i < this.materials.length; i++) {
  24731. this.materials[i].freeze();
  24732. }
  24733. };
  24734. Scene.prototype.unfreezeMaterials = function () {
  24735. for (var i = 0; i < this.materials.length; i++) {
  24736. this.materials[i].unfreeze();
  24737. }
  24738. };
  24739. Scene.prototype.dispose = function () {
  24740. this.beforeRender = null;
  24741. this.afterRender = null;
  24742. this.skeletons = [];
  24743. this.morphTargetManagers = [];
  24744. this.importedMeshesFiles = new Array();
  24745. this.stopAllAnimations();
  24746. this.resetCachedMaterial();
  24747. for (var key in this._depthRenderer) {
  24748. this._depthRenderer[key].dispose();
  24749. }
  24750. if (this._gamepadManager) {
  24751. this._gamepadManager.dispose();
  24752. this._gamepadManager = null;
  24753. }
  24754. // Smart arrays
  24755. if (this.activeCamera) {
  24756. this.activeCamera._activeMeshes.dispose();
  24757. this.activeCamera = null;
  24758. }
  24759. this._activeMeshes.dispose();
  24760. this._renderingManager.dispose();
  24761. this._processedMaterials.dispose();
  24762. this._activeParticleSystems.dispose();
  24763. this._activeSkeletons.dispose();
  24764. this._softwareSkinnedMeshes.dispose();
  24765. this._renderTargets.dispose();
  24766. if (this._boundingBoxRenderer) {
  24767. this._boundingBoxRenderer.dispose();
  24768. }
  24769. this._meshesForIntersections.dispose();
  24770. this._toBeDisposed.dispose();
  24771. // Abort active requests
  24772. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24773. var request = _a[_i];
  24774. request.abort();
  24775. }
  24776. // Debug layer
  24777. if (this._debugLayer) {
  24778. this._debugLayer.hide();
  24779. }
  24780. // Events
  24781. this.onDisposeObservable.notifyObservers(this);
  24782. this.onDisposeObservable.clear();
  24783. this.onBeforeRenderObservable.clear();
  24784. this.onAfterRenderObservable.clear();
  24785. this.OnBeforeRenderTargetsRenderObservable.clear();
  24786. this.OnAfterRenderTargetsRenderObservable.clear();
  24787. this.onAfterStepObservable.clear();
  24788. this.onBeforeStepObservable.clear();
  24789. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24790. this.onAfterActiveMeshesEvaluationObservable.clear();
  24791. this.onBeforeParticlesRenderingObservable.clear();
  24792. this.onAfterParticlesRenderingObservable.clear();
  24793. this.onBeforeSpritesRenderingObservable.clear();
  24794. this.onAfterSpritesRenderingObservable.clear();
  24795. this.onBeforeDrawPhaseObservable.clear();
  24796. this.onAfterDrawPhaseObservable.clear();
  24797. this.onBeforePhysicsObservable.clear();
  24798. this.onAfterPhysicsObservable.clear();
  24799. this.onBeforeAnimationsObservable.clear();
  24800. this.onAfterAnimationsObservable.clear();
  24801. this.onDataLoadedObservable.clear();
  24802. this.detachControl();
  24803. // Release sounds & sounds tracks
  24804. if (BABYLON.AudioEngine) {
  24805. this.disposeSounds();
  24806. }
  24807. // VR Helper
  24808. if (this.VRHelper) {
  24809. this.VRHelper.dispose();
  24810. }
  24811. // Detach cameras
  24812. var canvas = this._engine.getRenderingCanvas();
  24813. if (canvas) {
  24814. var index;
  24815. for (index = 0; index < this.cameras.length; index++) {
  24816. this.cameras[index].detachControl(canvas);
  24817. }
  24818. }
  24819. // Release animation groups
  24820. while (this.animationGroups.length) {
  24821. this.animationGroups[0].dispose();
  24822. }
  24823. // Release lights
  24824. while (this.lights.length) {
  24825. this.lights[0].dispose();
  24826. }
  24827. // Release meshes
  24828. while (this.meshes.length) {
  24829. this.meshes[0].dispose(true);
  24830. }
  24831. while (this.transformNodes.length) {
  24832. this.removeTransformNode(this.transformNodes[0]);
  24833. }
  24834. // Release cameras
  24835. while (this.cameras.length) {
  24836. this.cameras[0].dispose();
  24837. }
  24838. // Release materials
  24839. if (this.defaultMaterial) {
  24840. this.defaultMaterial.dispose();
  24841. }
  24842. while (this.multiMaterials.length) {
  24843. this.multiMaterials[0].dispose();
  24844. }
  24845. while (this.materials.length) {
  24846. this.materials[0].dispose();
  24847. }
  24848. // Release particles
  24849. while (this.particleSystems.length) {
  24850. this.particleSystems[0].dispose();
  24851. }
  24852. // Release sprites
  24853. while (this.spriteManagers.length) {
  24854. this.spriteManagers[0].dispose();
  24855. }
  24856. // Release postProcesses
  24857. while (this.postProcesses.length) {
  24858. this.postProcesses[0].dispose();
  24859. }
  24860. // Release layers
  24861. while (this.layers.length) {
  24862. this.layers[0].dispose();
  24863. }
  24864. while (this.effectLayers.length) {
  24865. this.effectLayers[0].dispose();
  24866. }
  24867. // Release textures
  24868. while (this.textures.length) {
  24869. this.textures[0].dispose();
  24870. }
  24871. // Release UBO
  24872. this._sceneUbo.dispose();
  24873. if (this._alternateSceneUbo) {
  24874. this._alternateSceneUbo.dispose();
  24875. }
  24876. // Post-processes
  24877. this.postProcessManager.dispose();
  24878. if (this._postProcessRenderPipelineManager) {
  24879. this._postProcessRenderPipelineManager.dispose();
  24880. }
  24881. // Physics
  24882. if (this._physicsEngine) {
  24883. this.disablePhysicsEngine();
  24884. }
  24885. // Remove from engine
  24886. index = this._engine.scenes.indexOf(this);
  24887. if (index > -1) {
  24888. this._engine.scenes.splice(index, 1);
  24889. }
  24890. this._engine.wipeCaches(true);
  24891. this._isDisposed = true;
  24892. };
  24893. Object.defineProperty(Scene.prototype, "isDisposed", {
  24894. get: function () {
  24895. return this._isDisposed;
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. // Release sounds & sounds tracks
  24901. Scene.prototype.disposeSounds = function () {
  24902. if (!this._mainSoundTrack) {
  24903. return;
  24904. }
  24905. this.mainSoundTrack.dispose();
  24906. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24907. this.soundTracks[scIndex].dispose();
  24908. }
  24909. };
  24910. // Octrees
  24911. /**
  24912. * Get the world extend vectors with an optional filter
  24913. *
  24914. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24915. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24916. */
  24917. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24918. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24919. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24920. filterPredicate = filterPredicate || (function () { return true; });
  24921. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24922. mesh.computeWorldMatrix(true);
  24923. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24924. return;
  24925. }
  24926. var boundingInfo = mesh.getBoundingInfo();
  24927. var minBox = boundingInfo.boundingBox.minimumWorld;
  24928. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24929. BABYLON.Tools.CheckExtends(minBox, min, max);
  24930. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24931. });
  24932. return {
  24933. min: min,
  24934. max: max
  24935. };
  24936. };
  24937. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24938. if (maxCapacity === void 0) { maxCapacity = 64; }
  24939. if (maxDepth === void 0) { maxDepth = 2; }
  24940. if (!this._selectionOctree) {
  24941. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24942. }
  24943. var worldExtends = this.getWorldExtends();
  24944. // Update octree
  24945. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24946. return this._selectionOctree;
  24947. };
  24948. // Picking
  24949. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24950. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24951. var result = BABYLON.Ray.Zero();
  24952. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24953. return result;
  24954. };
  24955. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24956. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24957. var engine = this._engine;
  24958. if (!camera) {
  24959. if (!this.activeCamera)
  24960. throw new Error("Active camera not set");
  24961. camera = this.activeCamera;
  24962. }
  24963. var cameraViewport = camera.viewport;
  24964. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24965. // Moving coordinates to local viewport world
  24966. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24967. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24968. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24969. return this;
  24970. };
  24971. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24972. var result = BABYLON.Ray.Zero();
  24973. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24974. return result;
  24975. };
  24976. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24977. if (!BABYLON.PickingInfo) {
  24978. return this;
  24979. }
  24980. var engine = this._engine;
  24981. if (!camera) {
  24982. if (!this.activeCamera)
  24983. throw new Error("Active camera not set");
  24984. camera = this.activeCamera;
  24985. }
  24986. var cameraViewport = camera.viewport;
  24987. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24988. var identity = BABYLON.Matrix.Identity();
  24989. // Moving coordinates to local viewport world
  24990. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24991. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24992. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24993. return this;
  24994. };
  24995. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24996. if (!BABYLON.PickingInfo) {
  24997. return null;
  24998. }
  24999. var pickingInfo = null;
  25000. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25001. var mesh = this.meshes[meshIndex];
  25002. if (predicate) {
  25003. if (!predicate(mesh)) {
  25004. continue;
  25005. }
  25006. }
  25007. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25008. continue;
  25009. }
  25010. var world = mesh.getWorldMatrix();
  25011. var ray = rayFunction(world);
  25012. var result = mesh.intersects(ray, fastCheck);
  25013. if (!result || !result.hit)
  25014. continue;
  25015. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25016. continue;
  25017. pickingInfo = result;
  25018. if (fastCheck) {
  25019. break;
  25020. }
  25021. }
  25022. return pickingInfo || new BABYLON.PickingInfo();
  25023. };
  25024. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25025. if (!BABYLON.PickingInfo) {
  25026. return null;
  25027. }
  25028. var pickingInfos = new Array();
  25029. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25030. var mesh = this.meshes[meshIndex];
  25031. if (predicate) {
  25032. if (!predicate(mesh)) {
  25033. continue;
  25034. }
  25035. }
  25036. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25037. continue;
  25038. }
  25039. var world = mesh.getWorldMatrix();
  25040. var ray = rayFunction(world);
  25041. var result = mesh.intersects(ray, false);
  25042. if (!result || !result.hit)
  25043. continue;
  25044. pickingInfos.push(result);
  25045. }
  25046. return pickingInfos;
  25047. };
  25048. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25049. if (!BABYLON.PickingInfo) {
  25050. return null;
  25051. }
  25052. var pickingInfo = null;
  25053. if (!camera) {
  25054. if (!this.activeCamera) {
  25055. return null;
  25056. }
  25057. camera = this.activeCamera;
  25058. }
  25059. if (this.spriteManagers.length > 0) {
  25060. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25061. var spriteManager = this.spriteManagers[spriteIndex];
  25062. if (!spriteManager.isPickable) {
  25063. continue;
  25064. }
  25065. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25066. if (!result || !result.hit)
  25067. continue;
  25068. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25069. continue;
  25070. pickingInfo = result;
  25071. if (fastCheck) {
  25072. break;
  25073. }
  25074. }
  25075. }
  25076. return pickingInfo || new BABYLON.PickingInfo();
  25077. };
  25078. /** Launch a ray to try to pick a mesh in the scene
  25079. * @param x position on screen
  25080. * @param y position on screen
  25081. * @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
  25082. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25083. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25084. */
  25085. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25086. var _this = this;
  25087. if (!BABYLON.PickingInfo) {
  25088. return null;
  25089. }
  25090. return this._internalPick(function (world) {
  25091. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25092. return _this._tempPickingRay;
  25093. }, predicate, fastCheck);
  25094. };
  25095. /** Launch a ray to try to pick a sprite in the scene
  25096. * @param x position on screen
  25097. * @param y position on screen
  25098. * @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
  25099. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25100. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25101. */
  25102. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25103. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25104. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25105. };
  25106. /** Use the given ray to pick a mesh in the scene
  25107. * @param ray The ray to use to pick meshes
  25108. * @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
  25109. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25110. */
  25111. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25112. var _this = this;
  25113. return this._internalPick(function (world) {
  25114. if (!_this._pickWithRayInverseMatrix) {
  25115. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25116. }
  25117. world.invertToRef(_this._pickWithRayInverseMatrix);
  25118. if (!_this._cachedRayForTransform) {
  25119. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25120. }
  25121. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25122. return _this._cachedRayForTransform;
  25123. }, predicate, fastCheck);
  25124. };
  25125. /**
  25126. * Launch a ray to try to pick a mesh in the scene
  25127. * @param x X position on screen
  25128. * @param y Y position on screen
  25129. * @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
  25130. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25131. */
  25132. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25133. var _this = this;
  25134. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25135. };
  25136. /**
  25137. * Launch a ray to try to pick a mesh in the scene
  25138. * @param ray Ray to use
  25139. * @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
  25140. */
  25141. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25142. var _this = this;
  25143. return this._internalMultiPick(function (world) {
  25144. if (!_this._pickWithRayInverseMatrix) {
  25145. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25146. }
  25147. world.invertToRef(_this._pickWithRayInverseMatrix);
  25148. if (!_this._cachedRayForTransform) {
  25149. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25150. }
  25151. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25152. return _this._cachedRayForTransform;
  25153. }, predicate);
  25154. };
  25155. Scene.prototype.setPointerOverMesh = function (mesh) {
  25156. if (this._pointerOverMesh === mesh) {
  25157. return;
  25158. }
  25159. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25160. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25161. }
  25162. this._pointerOverMesh = mesh;
  25163. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25164. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25165. }
  25166. };
  25167. Scene.prototype.getPointerOverMesh = function () {
  25168. return this._pointerOverMesh;
  25169. };
  25170. Scene.prototype.setPointerOverSprite = function (sprite) {
  25171. if (this._pointerOverSprite === sprite) {
  25172. return;
  25173. }
  25174. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25175. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25176. }
  25177. this._pointerOverSprite = sprite;
  25178. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25179. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25180. }
  25181. };
  25182. Scene.prototype.getPointerOverSprite = function () {
  25183. return this._pointerOverSprite;
  25184. };
  25185. // Physics
  25186. Scene.prototype.getPhysicsEngine = function () {
  25187. return this._physicsEngine;
  25188. };
  25189. /**
  25190. * Enables physics to the current scene
  25191. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25192. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25193. * @return {boolean} was the physics engine initialized
  25194. */
  25195. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25196. if (gravity === void 0) { gravity = null; }
  25197. if (this._physicsEngine) {
  25198. return true;
  25199. }
  25200. try {
  25201. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25202. return true;
  25203. }
  25204. catch (e) {
  25205. BABYLON.Tools.Error(e.message);
  25206. return false;
  25207. }
  25208. };
  25209. Scene.prototype.disablePhysicsEngine = function () {
  25210. if (!this._physicsEngine) {
  25211. return;
  25212. }
  25213. this._physicsEngine.dispose();
  25214. this._physicsEngine = null;
  25215. };
  25216. Scene.prototype.isPhysicsEnabled = function () {
  25217. return this._physicsEngine !== undefined;
  25218. };
  25219. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25220. var mesh = compound.parts[0].mesh;
  25221. if (mesh.physicsImpostor) {
  25222. mesh.physicsImpostor.dispose();
  25223. mesh.physicsImpostor = null;
  25224. }
  25225. };
  25226. // Misc.
  25227. Scene.prototype._rebuildGeometries = function () {
  25228. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25229. var geometry = _a[_i];
  25230. geometry._rebuild();
  25231. }
  25232. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25233. var mesh = _c[_b];
  25234. mesh._rebuild();
  25235. }
  25236. if (this.postProcessManager) {
  25237. this.postProcessManager._rebuild();
  25238. }
  25239. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25240. var layer = _e[_d];
  25241. layer._rebuild();
  25242. }
  25243. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25244. var effectLayer = _g[_f];
  25245. effectLayer._rebuild();
  25246. }
  25247. if (this._boundingBoxRenderer) {
  25248. this._boundingBoxRenderer._rebuild();
  25249. }
  25250. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25251. var system = _j[_h];
  25252. system.rebuild();
  25253. }
  25254. if (this._postProcessRenderPipelineManager) {
  25255. this._postProcessRenderPipelineManager._rebuild();
  25256. }
  25257. };
  25258. Scene.prototype._rebuildTextures = function () {
  25259. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25260. var texture = _a[_i];
  25261. texture._rebuild();
  25262. }
  25263. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25264. };
  25265. /**
  25266. * Creates a default light for the scene.
  25267. * @param replace Whether to replace the existing lights in the scene.
  25268. */
  25269. Scene.prototype.createDefaultLight = function (replace) {
  25270. if (replace === void 0) { replace = false; }
  25271. // Dispose existing light in replace mode.
  25272. if (replace) {
  25273. if (this.lights) {
  25274. for (var i = 0; i < this.lights.length; i++) {
  25275. this.lights[i].dispose();
  25276. }
  25277. }
  25278. }
  25279. // Light
  25280. if (this.lights.length === 0) {
  25281. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25282. }
  25283. };
  25284. /**
  25285. * Creates a default camera for the scene.
  25286. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25287. * @param replace Whether to replace the existing active camera in the scene.
  25288. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25289. */
  25290. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25291. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25292. if (replace === void 0) { replace = false; }
  25293. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25294. // Dispose existing camera in replace mode.
  25295. if (replace) {
  25296. if (this.activeCamera) {
  25297. this.activeCamera.dispose();
  25298. this.activeCamera = null;
  25299. }
  25300. }
  25301. // Camera
  25302. if (!this.activeCamera) {
  25303. var worldExtends = this.getWorldExtends();
  25304. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25305. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25306. var camera;
  25307. var radius = worldSize.length() * 1.5;
  25308. // empty scene scenario!
  25309. if (!isFinite(radius)) {
  25310. radius = 1;
  25311. worldCenter.copyFromFloats(0, 0, 0);
  25312. }
  25313. if (createArcRotateCamera) {
  25314. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25315. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25316. arcRotateCamera.wheelPrecision = 100 / radius;
  25317. camera = arcRotateCamera;
  25318. }
  25319. else {
  25320. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25321. freeCamera.setTarget(worldCenter);
  25322. camera = freeCamera;
  25323. }
  25324. camera.minZ = radius * 0.01;
  25325. camera.maxZ = radius * 1000;
  25326. camera.speed = radius * 0.2;
  25327. this.activeCamera = camera;
  25328. var canvas = this.getEngine().getRenderingCanvas();
  25329. if (attachCameraControls && canvas) {
  25330. camera.attachControl(canvas);
  25331. }
  25332. }
  25333. };
  25334. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25335. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25336. if (replace === void 0) { replace = false; }
  25337. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25338. this.createDefaultLight(replace);
  25339. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25340. };
  25341. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25342. if (pbr === void 0) { pbr = false; }
  25343. if (scale === void 0) { scale = 1000; }
  25344. if (blur === void 0) { blur = 0; }
  25345. if (environmentTexture) {
  25346. this.environmentTexture = environmentTexture;
  25347. }
  25348. if (!this.environmentTexture) {
  25349. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25350. return null;
  25351. }
  25352. // Skybox
  25353. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25354. if (pbr) {
  25355. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25356. hdrSkyboxMaterial.backFaceCulling = false;
  25357. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25358. if (hdrSkyboxMaterial.reflectionTexture) {
  25359. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25360. }
  25361. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25362. hdrSkyboxMaterial.disableLighting = true;
  25363. hdrSkyboxMaterial.twoSidedLighting = true;
  25364. hdrSkybox.infiniteDistance = true;
  25365. hdrSkybox.material = hdrSkyboxMaterial;
  25366. }
  25367. else {
  25368. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25369. skyboxMaterial.backFaceCulling = false;
  25370. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25371. if (skyboxMaterial.reflectionTexture) {
  25372. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25373. }
  25374. skyboxMaterial.disableLighting = true;
  25375. hdrSkybox.infiniteDistance = true;
  25376. hdrSkybox.material = skyboxMaterial;
  25377. }
  25378. return hdrSkybox;
  25379. };
  25380. Scene.prototype.createDefaultEnvironment = function (options) {
  25381. if (BABYLON.EnvironmentHelper) {
  25382. return new BABYLON.EnvironmentHelper(options, this);
  25383. }
  25384. return null;
  25385. };
  25386. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25387. if (webVROptions === void 0) { webVROptions = {}; }
  25388. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25389. };
  25390. // Tags
  25391. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25392. if (tagsQuery === undefined) {
  25393. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25394. return list;
  25395. }
  25396. var listByTags = [];
  25397. forEach = forEach || (function (item) { return; });
  25398. for (var i in list) {
  25399. var item = list[i];
  25400. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25401. listByTags.push(item);
  25402. forEach(item);
  25403. }
  25404. }
  25405. return listByTags;
  25406. };
  25407. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25408. return this._getByTags(this.meshes, tagsQuery, forEach);
  25409. };
  25410. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25411. return this._getByTags(this.cameras, tagsQuery, forEach);
  25412. };
  25413. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25414. return this._getByTags(this.lights, tagsQuery, forEach);
  25415. };
  25416. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25417. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25418. };
  25419. /**
  25420. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25421. * This allowed control for front to back rendering or reversly depending of the special needs.
  25422. *
  25423. * @param renderingGroupId The rendering group id corresponding to its index
  25424. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25425. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25426. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25427. */
  25428. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25429. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25430. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25431. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25432. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25433. };
  25434. /**
  25435. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25436. *
  25437. * @param renderingGroupId The rendering group id corresponding to its index
  25438. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25439. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25440. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25441. */
  25442. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25443. if (depth === void 0) { depth = true; }
  25444. if (stencil === void 0) { stencil = true; }
  25445. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25446. };
  25447. /**
  25448. * Will flag all materials as dirty to trigger new shader compilation
  25449. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25450. */
  25451. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25452. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25453. var material = _a[_i];
  25454. if (predicate && !predicate(material)) {
  25455. continue;
  25456. }
  25457. material.markAsDirty(flag);
  25458. }
  25459. };
  25460. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25461. var _this = this;
  25462. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25463. this._activeRequests.push(request);
  25464. request.onCompleteObservable.add(function (request) {
  25465. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25466. });
  25467. return request;
  25468. };
  25469. /** @ignore */
  25470. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25471. var _this = this;
  25472. return new Promise(function (resolve, reject) {
  25473. _this._loadFile(url, function (data) {
  25474. resolve(data);
  25475. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25476. reject(exception);
  25477. });
  25478. });
  25479. };
  25480. // Statics
  25481. Scene._FOGMODE_NONE = 0;
  25482. Scene._FOGMODE_EXP = 1;
  25483. Scene._FOGMODE_EXP2 = 2;
  25484. Scene._FOGMODE_LINEAR = 3;
  25485. Scene._uniqueIdCounter = 0;
  25486. Scene.MinDeltaTime = 1.0;
  25487. Scene.MaxDeltaTime = 1000.0;
  25488. /** The distance in pixel that you have to move to prevent some events */
  25489. Scene.DragMovementThreshold = 10; // in pixels
  25490. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25491. Scene.LongPressDelay = 500; // in milliseconds
  25492. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25493. Scene.DoubleClickDelay = 300; // in milliseconds
  25494. /** If you need to check double click without raising a single click at first click, enable this flag */
  25495. Scene.ExclusiveDoubleClickMode = false;
  25496. return Scene;
  25497. }());
  25498. BABYLON.Scene = Scene;
  25499. })(BABYLON || (BABYLON = {}));
  25500. //# sourceMappingURL=babylon.scene.js.map
  25501. var BABYLON;
  25502. (function (BABYLON) {
  25503. /**
  25504. * Set of assets to keep when moving a scene into an asset container.
  25505. */
  25506. var KeepAssets = /** @class */ (function () {
  25507. function KeepAssets() {
  25508. /**
  25509. * Cameras to keep.
  25510. */
  25511. this.cameras = new Array();
  25512. /**
  25513. * Lights to keep.
  25514. */
  25515. this.lights = new Array();
  25516. /**
  25517. * Meshes to keep.
  25518. */
  25519. this.meshes = new Array();
  25520. /**
  25521. * Skeletons to keep.
  25522. */
  25523. this.skeletons = new Array();
  25524. /**
  25525. * ParticleSystems to keep.
  25526. */
  25527. this.particleSystems = new Array();
  25528. /**
  25529. * Animations to keep.
  25530. */
  25531. this.animations = new Array();
  25532. /**
  25533. * MultiMaterials to keep.
  25534. */
  25535. this.multiMaterials = new Array();
  25536. /**
  25537. * Materials to keep.
  25538. */
  25539. this.materials = new Array();
  25540. /**
  25541. * MorphTargetManagers to keep.
  25542. */
  25543. this.morphTargetManagers = new Array();
  25544. /**
  25545. * Geometries to keep.
  25546. */
  25547. this.geometries = new Array();
  25548. /**
  25549. * TransformNodes to keep.
  25550. */
  25551. this.transformNodes = new Array();
  25552. /**
  25553. * LensFlareSystems to keep.
  25554. */
  25555. this.lensFlareSystems = new Array();
  25556. /**
  25557. * ShadowGenerators to keep.
  25558. */
  25559. this.shadowGenerators = new Array();
  25560. /**
  25561. * ActionManagers to keep.
  25562. */
  25563. this.actionManagers = new Array();
  25564. /**
  25565. * Sounds to keep.
  25566. */
  25567. this.sounds = new Array();
  25568. }
  25569. return KeepAssets;
  25570. }());
  25571. BABYLON.KeepAssets = KeepAssets;
  25572. /**
  25573. * Container with a set of assets that can be added or removed from a scene.
  25574. */
  25575. var AssetContainer = /** @class */ (function () {
  25576. /**
  25577. * Instantiates an AssetContainer.
  25578. * @param scene The scene the AssetContainer belongs to.
  25579. */
  25580. function AssetContainer(scene) {
  25581. // Objects
  25582. /**
  25583. * Cameras populated in the container.
  25584. */
  25585. this.cameras = new Array();
  25586. /**
  25587. * Lights populated in the container.
  25588. */
  25589. this.lights = new Array();
  25590. /**
  25591. * Meshes populated in the container.
  25592. */
  25593. this.meshes = new Array();
  25594. /**
  25595. * Skeletons populated in the container.
  25596. */
  25597. this.skeletons = new Array();
  25598. /**
  25599. * ParticleSystems populated in the container.
  25600. */
  25601. this.particleSystems = new Array();
  25602. /**
  25603. * Animations populated in the container.
  25604. */
  25605. this.animations = new Array();
  25606. /**
  25607. * MultiMaterials populated in the container.
  25608. */
  25609. this.multiMaterials = new Array();
  25610. /**
  25611. * Materials populated in the container.
  25612. */
  25613. this.materials = new Array();
  25614. /**
  25615. * MorphTargetManagers populated in the container.
  25616. */
  25617. this.morphTargetManagers = new Array();
  25618. /**
  25619. * Geometries populated in the container.
  25620. */
  25621. this.geometries = new Array();
  25622. /**
  25623. * TransformNodes populated in the container.
  25624. */
  25625. this.transformNodes = new Array();
  25626. /**
  25627. * LensFlareSystems populated in the container.
  25628. */
  25629. this.lensFlareSystems = new Array();
  25630. /**
  25631. * ShadowGenerators populated in the container.
  25632. */
  25633. this.shadowGenerators = new Array();
  25634. /**
  25635. * ActionManagers populated in the container.
  25636. */
  25637. this.actionManagers = new Array();
  25638. /**
  25639. * Sounds populated in the container.
  25640. */
  25641. this.sounds = new Array();
  25642. this.scene = scene;
  25643. }
  25644. /**
  25645. * Adds all the assets from the container to the scene.
  25646. */
  25647. AssetContainer.prototype.addAllToScene = function () {
  25648. var _this = this;
  25649. this.cameras.forEach(function (o) {
  25650. _this.scene.addCamera(o);
  25651. });
  25652. this.lights.forEach(function (o) {
  25653. _this.scene.addLight(o);
  25654. });
  25655. this.meshes.forEach(function (o) {
  25656. _this.scene.addMesh(o);
  25657. });
  25658. this.skeletons.forEach(function (o) {
  25659. _this.scene.addSkeleton(o);
  25660. });
  25661. this.particleSystems.forEach(function (o) {
  25662. _this.scene.addParticleSystem(o);
  25663. });
  25664. this.animations.forEach(function (o) {
  25665. _this.scene.addAnimation(o);
  25666. });
  25667. this.multiMaterials.forEach(function (o) {
  25668. _this.scene.addMultiMaterial(o);
  25669. });
  25670. this.materials.forEach(function (o) {
  25671. _this.scene.addMaterial(o);
  25672. });
  25673. this.morphTargetManagers.forEach(function (o) {
  25674. _this.scene.addMorphTargetManager(o);
  25675. });
  25676. this.geometries.forEach(function (o) {
  25677. _this.scene.addGeometry(o);
  25678. });
  25679. this.transformNodes.forEach(function (o) {
  25680. _this.scene.addTransformNode(o);
  25681. });
  25682. this.lensFlareSystems.forEach(function (o) {
  25683. _this.scene.addLensFlareSystem(o);
  25684. });
  25685. this.actionManagers.forEach(function (o) {
  25686. _this.scene.addActionManager(o);
  25687. });
  25688. this.sounds.forEach(function (o) {
  25689. o.play();
  25690. o.autoplay = true;
  25691. _this.scene.mainSoundTrack.AddSound(o);
  25692. });
  25693. };
  25694. /**
  25695. * Removes all the assets in the container from the scene
  25696. */
  25697. AssetContainer.prototype.removeAllFromScene = function () {
  25698. var _this = this;
  25699. this.cameras.forEach(function (o) {
  25700. _this.scene.removeCamera(o);
  25701. });
  25702. this.lights.forEach(function (o) {
  25703. _this.scene.removeLight(o);
  25704. });
  25705. this.meshes.forEach(function (o) {
  25706. _this.scene.removeMesh(o);
  25707. });
  25708. this.skeletons.forEach(function (o) {
  25709. _this.scene.removeSkeleton(o);
  25710. });
  25711. this.particleSystems.forEach(function (o) {
  25712. _this.scene.removeParticleSystem(o);
  25713. });
  25714. this.animations.forEach(function (o) {
  25715. _this.scene.removeAnimation(o);
  25716. });
  25717. this.multiMaterials.forEach(function (o) {
  25718. _this.scene.removeMultiMaterial(o);
  25719. });
  25720. this.materials.forEach(function (o) {
  25721. _this.scene.removeMaterial(o);
  25722. });
  25723. this.morphTargetManagers.forEach(function (o) {
  25724. _this.scene.removeMorphTargetManager(o);
  25725. });
  25726. this.geometries.forEach(function (o) {
  25727. _this.scene.removeGeometry(o);
  25728. });
  25729. this.transformNodes.forEach(function (o) {
  25730. _this.scene.removeTransformNode(o);
  25731. });
  25732. this.lensFlareSystems.forEach(function (o) {
  25733. _this.scene.removeLensFlareSystem(o);
  25734. });
  25735. this.actionManagers.forEach(function (o) {
  25736. _this.scene.removeActionManager(o);
  25737. });
  25738. this.sounds.forEach(function (o) {
  25739. o.stop();
  25740. o.autoplay = false;
  25741. _this.scene.mainSoundTrack.RemoveSound(o);
  25742. });
  25743. };
  25744. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25745. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25746. var asset = sourceAssets_1[_i];
  25747. var move = true;
  25748. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25749. var keepAsset = keepAssets_1[_a];
  25750. if (asset === keepAsset) {
  25751. move = false;
  25752. break;
  25753. }
  25754. }
  25755. if (move) {
  25756. targetAssets.push(asset);
  25757. }
  25758. }
  25759. };
  25760. /**
  25761. * Removes all the assets contained in the scene and adds them to the container.
  25762. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25763. */
  25764. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25765. if (keepAssets === undefined) {
  25766. keepAssets = new KeepAssets();
  25767. }
  25768. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25769. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25770. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25771. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25772. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25773. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25774. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25775. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25776. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25777. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25778. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25779. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25780. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25781. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25782. this.removeAllFromScene();
  25783. };
  25784. return AssetContainer;
  25785. }());
  25786. BABYLON.AssetContainer = AssetContainer;
  25787. })(BABYLON || (BABYLON = {}));
  25788. //# sourceMappingURL=babylon.assetContainer.js.map
  25789. var BABYLON;
  25790. (function (BABYLON) {
  25791. var Buffer = /** @class */ (function () {
  25792. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25793. if (instanced === void 0) { instanced = false; }
  25794. if (engine instanceof BABYLON.Mesh) {
  25795. this._engine = engine.getScene().getEngine();
  25796. }
  25797. else {
  25798. this._engine = engine;
  25799. }
  25800. this._updatable = updatable;
  25801. this._instanced = instanced;
  25802. this._data = data;
  25803. this._strideSize = stride;
  25804. if (!postponeInternalCreation) {
  25805. this.create();
  25806. }
  25807. }
  25808. /**
  25809. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25810. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25811. * @param offset defines offset in the buffer (0 by default)
  25812. * @param size defines the size in floats of attributes (position is 3 for instance)
  25813. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25814. * @param instanced defines if the vertex buffer contains indexed data
  25815. * @returns the new vertex buffer
  25816. */
  25817. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25818. // a lot of these parameters are ignored as they are overriden by the buffer
  25819. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25820. };
  25821. // Properties
  25822. Buffer.prototype.isUpdatable = function () {
  25823. return this._updatable;
  25824. };
  25825. Buffer.prototype.getData = function () {
  25826. return this._data;
  25827. };
  25828. Buffer.prototype.getBuffer = function () {
  25829. return this._buffer;
  25830. };
  25831. Buffer.prototype.getStrideSize = function () {
  25832. return this._strideSize;
  25833. };
  25834. // public getIsInstanced(): boolean {
  25835. // return this._instanced;
  25836. // }
  25837. // public get instanceDivisor(): number {
  25838. // return this._instanceDivisor;
  25839. // }
  25840. // public set instanceDivisor(value: number) {
  25841. // this._instanceDivisor = value;
  25842. // if (value == 0) {
  25843. // this._instanced = false;
  25844. // } else {
  25845. // this._instanced = true;
  25846. // }
  25847. // }
  25848. // Methods
  25849. Buffer.prototype.create = function (data) {
  25850. if (data === void 0) { data = null; }
  25851. if (!data && this._buffer) {
  25852. return; // nothing to do
  25853. }
  25854. data = data || this._data;
  25855. if (!data) {
  25856. return;
  25857. }
  25858. if (!this._buffer) {
  25859. if (this._updatable) {
  25860. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25861. this._data = data;
  25862. }
  25863. else {
  25864. this._buffer = this._engine.createVertexBuffer(data);
  25865. }
  25866. }
  25867. else if (this._updatable) {
  25868. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25869. this._data = data;
  25870. }
  25871. };
  25872. Buffer.prototype._rebuild = function () {
  25873. this._buffer = null;
  25874. this.create(this._data);
  25875. };
  25876. Buffer.prototype.update = function (data) {
  25877. this.create(data);
  25878. };
  25879. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25880. if (!this._buffer) {
  25881. return;
  25882. }
  25883. if (this._updatable) {
  25884. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25885. this._data = null;
  25886. }
  25887. };
  25888. Buffer.prototype.dispose = function () {
  25889. if (!this._buffer) {
  25890. return;
  25891. }
  25892. if (this._engine._releaseBuffer(this._buffer)) {
  25893. this._buffer = null;
  25894. }
  25895. };
  25896. return Buffer;
  25897. }());
  25898. BABYLON.Buffer = Buffer;
  25899. })(BABYLON || (BABYLON = {}));
  25900. //# sourceMappingURL=babylon.buffer.js.map
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. var VertexBuffer = /** @class */ (function () {
  25904. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25905. if (data instanceof BABYLON.Buffer) {
  25906. if (!stride) {
  25907. stride = data.getStrideSize();
  25908. }
  25909. this._buffer = data;
  25910. this._ownsBuffer = false;
  25911. }
  25912. else {
  25913. if (!stride) {
  25914. stride = VertexBuffer.DeduceStride(kind);
  25915. }
  25916. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25917. this._ownsBuffer = true;
  25918. }
  25919. this._stride = stride;
  25920. this._instanced = instanced !== undefined ? instanced : false;
  25921. this._instanceDivisor = instanced ? 1 : 0;
  25922. this._offset = offset ? offset : 0;
  25923. this._size = size ? size : stride;
  25924. this._kind = kind;
  25925. }
  25926. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25927. /**
  25928. * Gets or sets the instance divisor when in instanced mode
  25929. */
  25930. get: function () {
  25931. return this._instanceDivisor;
  25932. },
  25933. set: function (value) {
  25934. this._instanceDivisor = value;
  25935. if (value == 0) {
  25936. this._instanced = false;
  25937. }
  25938. else {
  25939. this._instanced = true;
  25940. }
  25941. },
  25942. enumerable: true,
  25943. configurable: true
  25944. });
  25945. VertexBuffer.prototype._rebuild = function () {
  25946. if (!this._buffer) {
  25947. return;
  25948. }
  25949. this._buffer._rebuild();
  25950. };
  25951. /**
  25952. * Returns the kind of the VertexBuffer (string).
  25953. */
  25954. VertexBuffer.prototype.getKind = function () {
  25955. return this._kind;
  25956. };
  25957. // Properties
  25958. /**
  25959. * Boolean : is the VertexBuffer updatable ?
  25960. */
  25961. VertexBuffer.prototype.isUpdatable = function () {
  25962. return this._buffer.isUpdatable();
  25963. };
  25964. /**
  25965. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25966. */
  25967. VertexBuffer.prototype.getData = function () {
  25968. return this._buffer.getData();
  25969. };
  25970. /**
  25971. * Returns the WebGLBuffer associated to the VertexBuffer.
  25972. */
  25973. VertexBuffer.prototype.getBuffer = function () {
  25974. return this._buffer.getBuffer();
  25975. };
  25976. /**
  25977. * Returns the stride of the VertexBuffer (integer).
  25978. */
  25979. VertexBuffer.prototype.getStrideSize = function () {
  25980. return this._stride;
  25981. };
  25982. /**
  25983. * Returns the offset (integer).
  25984. */
  25985. VertexBuffer.prototype.getOffset = function () {
  25986. return this._offset;
  25987. };
  25988. /**
  25989. * Returns the VertexBuffer total size (integer).
  25990. */
  25991. VertexBuffer.prototype.getSize = function () {
  25992. return this._size;
  25993. };
  25994. /**
  25995. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25996. */
  25997. VertexBuffer.prototype.getIsInstanced = function () {
  25998. return this._instanced;
  25999. };
  26000. /**
  26001. * Returns the instancing divisor, zero for non-instanced (integer).
  26002. */
  26003. VertexBuffer.prototype.getInstanceDivisor = function () {
  26004. return this._instanceDivisor;
  26005. };
  26006. // Methods
  26007. /**
  26008. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26009. * Returns the created WebGLBuffer.
  26010. */
  26011. VertexBuffer.prototype.create = function (data) {
  26012. return this._buffer.create(data);
  26013. };
  26014. /**
  26015. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26016. * This function will create a new buffer if the current one is not updatable
  26017. * Returns the updated WebGLBuffer.
  26018. */
  26019. VertexBuffer.prototype.update = function (data) {
  26020. return this._buffer.update(data);
  26021. };
  26022. /**
  26023. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26024. * Returns the directly updated WebGLBuffer.
  26025. */
  26026. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26027. return this._buffer.updateDirectly(data, offset);
  26028. };
  26029. /**
  26030. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26031. */
  26032. VertexBuffer.prototype.dispose = function () {
  26033. if (this._ownsBuffer) {
  26034. this._buffer.dispose();
  26035. }
  26036. };
  26037. Object.defineProperty(VertexBuffer, "PositionKind", {
  26038. get: function () {
  26039. return VertexBuffer._PositionKind;
  26040. },
  26041. enumerable: true,
  26042. configurable: true
  26043. });
  26044. Object.defineProperty(VertexBuffer, "NormalKind", {
  26045. get: function () {
  26046. return VertexBuffer._NormalKind;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(VertexBuffer, "TangentKind", {
  26052. get: function () {
  26053. return VertexBuffer._TangentKind;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. Object.defineProperty(VertexBuffer, "UVKind", {
  26059. get: function () {
  26060. return VertexBuffer._UVKind;
  26061. },
  26062. enumerable: true,
  26063. configurable: true
  26064. });
  26065. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26066. get: function () {
  26067. return VertexBuffer._UV2Kind;
  26068. },
  26069. enumerable: true,
  26070. configurable: true
  26071. });
  26072. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26073. get: function () {
  26074. return VertexBuffer._UV3Kind;
  26075. },
  26076. enumerable: true,
  26077. configurable: true
  26078. });
  26079. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26080. get: function () {
  26081. return VertexBuffer._UV4Kind;
  26082. },
  26083. enumerable: true,
  26084. configurable: true
  26085. });
  26086. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26087. get: function () {
  26088. return VertexBuffer._UV5Kind;
  26089. },
  26090. enumerable: true,
  26091. configurable: true
  26092. });
  26093. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26094. get: function () {
  26095. return VertexBuffer._UV6Kind;
  26096. },
  26097. enumerable: true,
  26098. configurable: true
  26099. });
  26100. Object.defineProperty(VertexBuffer, "ColorKind", {
  26101. get: function () {
  26102. return VertexBuffer._ColorKind;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26108. get: function () {
  26109. return VertexBuffer._MatricesIndicesKind;
  26110. },
  26111. enumerable: true,
  26112. configurable: true
  26113. });
  26114. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26115. get: function () {
  26116. return VertexBuffer._MatricesWeightsKind;
  26117. },
  26118. enumerable: true,
  26119. configurable: true
  26120. });
  26121. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26122. get: function () {
  26123. return VertexBuffer._MatricesIndicesExtraKind;
  26124. },
  26125. enumerable: true,
  26126. configurable: true
  26127. });
  26128. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26129. get: function () {
  26130. return VertexBuffer._MatricesWeightsExtraKind;
  26131. },
  26132. enumerable: true,
  26133. configurable: true
  26134. });
  26135. /**
  26136. * Deduces the stride given a kind.
  26137. * @param kind The kind string to deduce
  26138. * @returns The deduced stride
  26139. */
  26140. VertexBuffer.DeduceStride = function (kind) {
  26141. switch (kind) {
  26142. case VertexBuffer.UVKind:
  26143. case VertexBuffer.UV2Kind:
  26144. case VertexBuffer.UV3Kind:
  26145. case VertexBuffer.UV4Kind:
  26146. case VertexBuffer.UV5Kind:
  26147. case VertexBuffer.UV6Kind:
  26148. return 2;
  26149. case VertexBuffer.NormalKind:
  26150. case VertexBuffer.PositionKind:
  26151. return 3;
  26152. case VertexBuffer.ColorKind:
  26153. case VertexBuffer.MatricesIndicesKind:
  26154. case VertexBuffer.MatricesIndicesExtraKind:
  26155. case VertexBuffer.MatricesWeightsKind:
  26156. case VertexBuffer.MatricesWeightsExtraKind:
  26157. case VertexBuffer.TangentKind:
  26158. return 4;
  26159. default:
  26160. throw new Error("Invalid kind '" + kind + "'");
  26161. }
  26162. };
  26163. // Enums
  26164. VertexBuffer._PositionKind = "position";
  26165. VertexBuffer._NormalKind = "normal";
  26166. VertexBuffer._TangentKind = "tangent";
  26167. VertexBuffer._UVKind = "uv";
  26168. VertexBuffer._UV2Kind = "uv2";
  26169. VertexBuffer._UV3Kind = "uv3";
  26170. VertexBuffer._UV4Kind = "uv4";
  26171. VertexBuffer._UV5Kind = "uv5";
  26172. VertexBuffer._UV6Kind = "uv6";
  26173. VertexBuffer._ColorKind = "color";
  26174. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26175. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26176. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26177. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26178. return VertexBuffer;
  26179. }());
  26180. BABYLON.VertexBuffer = VertexBuffer;
  26181. })(BABYLON || (BABYLON = {}));
  26182. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26183. var BABYLON;
  26184. (function (BABYLON) {
  26185. /**
  26186. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26187. */
  26188. var DummyInternalTextureTracker = /** @class */ (function () {
  26189. function DummyInternalTextureTracker() {
  26190. /**
  26191. * Gets or set the previous tracker in the list
  26192. */
  26193. this.previous = null;
  26194. /**
  26195. * Gets or set the next tracker in the list
  26196. */
  26197. this.next = null;
  26198. }
  26199. return DummyInternalTextureTracker;
  26200. }());
  26201. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26202. })(BABYLON || (BABYLON = {}));
  26203. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26204. var BABYLON;
  26205. (function (BABYLON) {
  26206. /**
  26207. * Class used to store data associated with WebGL texture data for the engine
  26208. * This class should not be used directly
  26209. */
  26210. var InternalTexture = /** @class */ (function () {
  26211. /**
  26212. * Creates a new InternalTexture
  26213. * @param engine defines the engine to use
  26214. * @param dataSource defines the type of data that will be used
  26215. */
  26216. function InternalTexture(engine, dataSource) {
  26217. /**
  26218. * Observable called when the texture is loaded
  26219. */
  26220. this.onLoadedObservable = new BABYLON.Observable();
  26221. /**
  26222. * Gets or set the previous tracker in the list
  26223. */
  26224. this.previous = null;
  26225. /**
  26226. * Gets or set the next tracker in the list
  26227. */
  26228. this.next = null;
  26229. // Private
  26230. /** @ignore */
  26231. this._initialSlot = -1;
  26232. /** @ignore */
  26233. this._designatedSlot = -1;
  26234. /** @ignore */
  26235. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26236. /** @ignore */
  26237. this._comparisonFunction = 0;
  26238. /** @ignore */
  26239. this._references = 1;
  26240. this._engine = engine;
  26241. this._dataSource = dataSource;
  26242. this._webGLTexture = engine._createTexture();
  26243. }
  26244. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26245. /**
  26246. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26247. */
  26248. get: function () {
  26249. return this._dataSource;
  26250. },
  26251. enumerable: true,
  26252. configurable: true
  26253. });
  26254. /**
  26255. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26256. */
  26257. InternalTexture.prototype.incrementReferences = function () {
  26258. this._references++;
  26259. };
  26260. /**
  26261. * Change the size of the texture (not the size of the content)
  26262. * @param width defines the new width
  26263. * @param height defines the new height
  26264. * @param depth defines the new depth (1 by default)
  26265. */
  26266. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26267. if (depth === void 0) { depth = 1; }
  26268. this.width = width;
  26269. this.height = height;
  26270. this.depth = depth;
  26271. this.baseWidth = width;
  26272. this.baseHeight = height;
  26273. this.baseDepth = depth;
  26274. this._size = width * height * depth;
  26275. };
  26276. /** @ignore */
  26277. InternalTexture.prototype._rebuild = function () {
  26278. var _this = this;
  26279. var proxy;
  26280. this.isReady = false;
  26281. this._cachedCoordinatesMode = null;
  26282. this._cachedWrapU = null;
  26283. this._cachedWrapV = null;
  26284. this._cachedAnisotropicFilteringLevel = null;
  26285. switch (this._dataSource) {
  26286. case InternalTexture.DATASOURCE_TEMP:
  26287. return;
  26288. case InternalTexture.DATASOURCE_URL:
  26289. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26290. _this.isReady = true;
  26291. }, null, this._buffer, undefined, this.format);
  26292. proxy._swapAndDie(this);
  26293. return;
  26294. case InternalTexture.DATASOURCE_RAW:
  26295. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26296. proxy._swapAndDie(this);
  26297. this.isReady = true;
  26298. return;
  26299. case InternalTexture.DATASOURCE_RAW3D:
  26300. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26301. proxy._swapAndDie(this);
  26302. this.isReady = true;
  26303. return;
  26304. case InternalTexture.DATASOURCE_DYNAMIC:
  26305. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26306. proxy._swapAndDie(this);
  26307. // The engine will make sure to update content so no need to flag it as isReady = true
  26308. return;
  26309. case InternalTexture.DATASOURCE_RENDERTARGET:
  26310. var options = new BABYLON.RenderTargetCreationOptions();
  26311. options.generateDepthBuffer = this._generateDepthBuffer;
  26312. options.generateMipMaps = this.generateMipMaps;
  26313. options.generateStencilBuffer = this._generateStencilBuffer;
  26314. options.samplingMode = this.samplingMode;
  26315. options.type = this.type;
  26316. if (this.isCube) {
  26317. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26318. }
  26319. else {
  26320. var size = {
  26321. width: this.width,
  26322. height: this.height
  26323. };
  26324. proxy = this._engine.createRenderTargetTexture(size, options);
  26325. }
  26326. proxy._swapAndDie(this);
  26327. this.isReady = true;
  26328. return;
  26329. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26330. var depthTextureOptions = {
  26331. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26332. comparisonFunction: this._comparisonFunction,
  26333. generateStencil: this._generateStencilBuffer,
  26334. };
  26335. if (this.isCube) {
  26336. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26337. }
  26338. else {
  26339. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26340. }
  26341. proxy._swapAndDie(this);
  26342. this.isReady = true;
  26343. return;
  26344. case InternalTexture.DATASOURCE_CUBE:
  26345. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26346. _this.isReady = true;
  26347. }, null, this.format, this._extension);
  26348. proxy._swapAndDie(this);
  26349. return;
  26350. case InternalTexture.DATASOURCE_CUBERAW:
  26351. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26352. proxy._swapAndDie(this);
  26353. this.isReady = true;
  26354. return;
  26355. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26356. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26357. if (proxy) {
  26358. proxy._swapAndDie(_this);
  26359. }
  26360. _this.isReady = true;
  26361. }, null, this.format, this._extension);
  26362. return;
  26363. }
  26364. };
  26365. InternalTexture.prototype._swapAndDie = function (target) {
  26366. target._webGLTexture = this._webGLTexture;
  26367. if (this._framebuffer) {
  26368. target._framebuffer = this._framebuffer;
  26369. }
  26370. if (this._depthStencilBuffer) {
  26371. target._depthStencilBuffer = this._depthStencilBuffer;
  26372. }
  26373. if (this._lodTextureHigh) {
  26374. if (target._lodTextureHigh) {
  26375. target._lodTextureHigh.dispose();
  26376. }
  26377. target._lodTextureHigh = this._lodTextureHigh;
  26378. }
  26379. if (this._lodTextureMid) {
  26380. if (target._lodTextureMid) {
  26381. target._lodTextureMid.dispose();
  26382. }
  26383. target._lodTextureMid = this._lodTextureMid;
  26384. }
  26385. if (this._lodTextureLow) {
  26386. if (target._lodTextureLow) {
  26387. target._lodTextureLow.dispose();
  26388. }
  26389. target._lodTextureLow = this._lodTextureLow;
  26390. }
  26391. var cache = this._engine.getLoadedTexturesCache();
  26392. var index = cache.indexOf(this);
  26393. if (index !== -1) {
  26394. cache.splice(index, 1);
  26395. }
  26396. };
  26397. /**
  26398. * Dispose the current allocated resources
  26399. */
  26400. InternalTexture.prototype.dispose = function () {
  26401. if (!this._webGLTexture) {
  26402. return;
  26403. }
  26404. this._references--;
  26405. if (this._references === 0) {
  26406. this._engine._releaseTexture(this);
  26407. this._webGLTexture = null;
  26408. this.previous = null;
  26409. this.next = null;
  26410. }
  26411. };
  26412. /**
  26413. * The source of the texture data is unknown
  26414. */
  26415. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26416. /**
  26417. * Texture data comes from an URL
  26418. */
  26419. InternalTexture.DATASOURCE_URL = 1;
  26420. /**
  26421. * Texture data is only used for temporary storage
  26422. */
  26423. InternalTexture.DATASOURCE_TEMP = 2;
  26424. /**
  26425. * Texture data comes from raw data (ArrayBuffer)
  26426. */
  26427. InternalTexture.DATASOURCE_RAW = 3;
  26428. /**
  26429. * Texture content is dynamic (video or dynamic texture)
  26430. */
  26431. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26432. /**
  26433. * Texture content is generated by rendering to it
  26434. */
  26435. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26436. /**
  26437. * Texture content is part of a multi render target process
  26438. */
  26439. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26440. /**
  26441. * Texture data comes from a cube data file
  26442. */
  26443. InternalTexture.DATASOURCE_CUBE = 7;
  26444. /**
  26445. * Texture data comes from a raw cube data
  26446. */
  26447. InternalTexture.DATASOURCE_CUBERAW = 8;
  26448. /**
  26449. * Texture data come from a prefiltered cube data file
  26450. */
  26451. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26452. /**
  26453. * Texture content is raw 3D data
  26454. */
  26455. InternalTexture.DATASOURCE_RAW3D = 10;
  26456. /**
  26457. * Texture content is a depth texture
  26458. */
  26459. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26460. return InternalTexture;
  26461. }());
  26462. BABYLON.InternalTexture = InternalTexture;
  26463. })(BABYLON || (BABYLON = {}));
  26464. //# sourceMappingURL=babylon.internalTexture.js.map
  26465. var BABYLON;
  26466. (function (BABYLON) {
  26467. var BaseTexture = /** @class */ (function () {
  26468. function BaseTexture(scene) {
  26469. this._hasAlpha = false;
  26470. this.getAlphaFromRGB = false;
  26471. this.level = 1;
  26472. this.coordinatesIndex = 0;
  26473. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26474. /**
  26475. * | Value | Type | Description |
  26476. * | ----- | ------------------ | ----------- |
  26477. * | 0 | CLAMP_ADDRESSMODE | |
  26478. * | 1 | WRAP_ADDRESSMODE | |
  26479. * | 2 | MIRROR_ADDRESSMODE | |
  26480. */
  26481. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26482. /**
  26483. * | Value | Type | Description |
  26484. * | ----- | ------------------ | ----------- |
  26485. * | 0 | CLAMP_ADDRESSMODE | |
  26486. * | 1 | WRAP_ADDRESSMODE | |
  26487. * | 2 | MIRROR_ADDRESSMODE | |
  26488. */
  26489. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26490. /**
  26491. * | Value | Type | Description |
  26492. * | ----- | ------------------ | ----------- |
  26493. * | 0 | CLAMP_ADDRESSMODE | |
  26494. * | 1 | WRAP_ADDRESSMODE | |
  26495. * | 2 | MIRROR_ADDRESSMODE | |
  26496. */
  26497. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26498. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26499. this.isCube = false;
  26500. this.is3D = false;
  26501. this.gammaSpace = true;
  26502. this.invertZ = false;
  26503. this.lodLevelInAlpha = false;
  26504. this.lodGenerationOffset = 0.0;
  26505. this.lodGenerationScale = 0.8;
  26506. this.isRenderTarget = false;
  26507. this.animations = new Array();
  26508. /**
  26509. * An event triggered when the texture is disposed.
  26510. * @type {BABYLON.Observable}
  26511. */
  26512. this.onDisposeObservable = new BABYLON.Observable();
  26513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26515. if (this._scene) {
  26516. this._scene.textures.push(this);
  26517. }
  26518. this._uid = null;
  26519. }
  26520. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26521. get: function () {
  26522. return this._hasAlpha;
  26523. },
  26524. set: function (value) {
  26525. if (this._hasAlpha === value) {
  26526. return;
  26527. }
  26528. this._hasAlpha = value;
  26529. if (this._scene) {
  26530. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26531. }
  26532. },
  26533. enumerable: true,
  26534. configurable: true
  26535. });
  26536. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26537. get: function () {
  26538. return this._coordinatesMode;
  26539. },
  26540. /**
  26541. * How a texture is mapped.
  26542. *
  26543. * | Value | Type | Description |
  26544. * | ----- | ----------------------------------- | ----------- |
  26545. * | 0 | EXPLICIT_MODE | |
  26546. * | 1 | SPHERICAL_MODE | |
  26547. * | 2 | PLANAR_MODE | |
  26548. * | 3 | CUBIC_MODE | |
  26549. * | 4 | PROJECTION_MODE | |
  26550. * | 5 | SKYBOX_MODE | |
  26551. * | 6 | INVCUBIC_MODE | |
  26552. * | 7 | EQUIRECTANGULAR_MODE | |
  26553. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26554. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26555. */
  26556. set: function (value) {
  26557. if (this._coordinatesMode === value) {
  26558. return;
  26559. }
  26560. this._coordinatesMode = value;
  26561. if (this._scene) {
  26562. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26563. }
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. Object.defineProperty(BaseTexture.prototype, "uid", {
  26569. get: function () {
  26570. if (!this._uid) {
  26571. this._uid = BABYLON.Tools.RandomId();
  26572. }
  26573. return this._uid;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. BaseTexture.prototype.toString = function () {
  26579. return this.name;
  26580. };
  26581. BaseTexture.prototype.getClassName = function () {
  26582. return "BaseTexture";
  26583. };
  26584. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26585. set: function (callback) {
  26586. if (this._onDisposeObserver) {
  26587. this.onDisposeObservable.remove(this._onDisposeObserver);
  26588. }
  26589. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26590. },
  26591. enumerable: true,
  26592. configurable: true
  26593. });
  26594. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26595. get: function () {
  26596. return true;
  26597. },
  26598. enumerable: true,
  26599. configurable: true
  26600. });
  26601. BaseTexture.prototype.getScene = function () {
  26602. return this._scene;
  26603. };
  26604. BaseTexture.prototype.getTextureMatrix = function () {
  26605. return BABYLON.Matrix.IdentityReadOnly;
  26606. };
  26607. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26608. return BABYLON.Matrix.IdentityReadOnly;
  26609. };
  26610. BaseTexture.prototype.getInternalTexture = function () {
  26611. return this._texture;
  26612. };
  26613. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26614. return !this.isBlocking || this.isReady();
  26615. };
  26616. BaseTexture.prototype.isReady = function () {
  26617. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26618. this.delayLoad();
  26619. return false;
  26620. }
  26621. if (this._texture) {
  26622. return this._texture.isReady;
  26623. }
  26624. return false;
  26625. };
  26626. BaseTexture.prototype.getSize = function () {
  26627. if (this._texture && this._texture.width) {
  26628. return new BABYLON.Size(this._texture.width, this._texture.height);
  26629. }
  26630. if (this._texture && this._texture._size) {
  26631. return new BABYLON.Size(this._texture._size, this._texture._size);
  26632. }
  26633. return BABYLON.Size.Zero();
  26634. };
  26635. BaseTexture.prototype.getBaseSize = function () {
  26636. if (!this.isReady() || !this._texture)
  26637. return BABYLON.Size.Zero();
  26638. if (this._texture._size) {
  26639. return new BABYLON.Size(this._texture._size, this._texture._size);
  26640. }
  26641. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26642. };
  26643. BaseTexture.prototype.scale = function (ratio) {
  26644. };
  26645. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26646. get: function () {
  26647. return false;
  26648. },
  26649. enumerable: true,
  26650. configurable: true
  26651. });
  26652. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26653. if (!this._scene) {
  26654. return null;
  26655. }
  26656. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26657. for (var index = 0; index < texturesCache.length; index++) {
  26658. var texturesCacheEntry = texturesCache[index];
  26659. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26660. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26661. texturesCacheEntry.incrementReferences();
  26662. return texturesCacheEntry;
  26663. }
  26664. }
  26665. }
  26666. return null;
  26667. };
  26668. BaseTexture.prototype._rebuild = function () {
  26669. };
  26670. BaseTexture.prototype.delayLoad = function () {
  26671. };
  26672. BaseTexture.prototype.clone = function () {
  26673. return null;
  26674. };
  26675. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26676. get: function () {
  26677. if (!this._texture) {
  26678. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26679. }
  26680. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26681. },
  26682. enumerable: true,
  26683. configurable: true
  26684. });
  26685. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26686. get: function () {
  26687. if (!this._texture) {
  26688. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26689. }
  26690. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. BaseTexture.prototype.readPixels = function (faceIndex) {
  26696. if (faceIndex === void 0) { faceIndex = 0; }
  26697. if (!this._texture) {
  26698. return null;
  26699. }
  26700. var size = this.getSize();
  26701. var scene = this.getScene();
  26702. if (!scene) {
  26703. return null;
  26704. }
  26705. var engine = scene.getEngine();
  26706. if (this._texture.isCube) {
  26707. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26708. }
  26709. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26710. };
  26711. BaseTexture.prototype.releaseInternalTexture = function () {
  26712. if (this._texture) {
  26713. this._texture.dispose();
  26714. this._texture = null;
  26715. }
  26716. };
  26717. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26718. get: function () {
  26719. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26720. return null;
  26721. }
  26722. if (!this._texture._sphericalPolynomial) {
  26723. this._texture._sphericalPolynomial =
  26724. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26725. }
  26726. return this._texture._sphericalPolynomial;
  26727. },
  26728. set: function (value) {
  26729. if (this._texture) {
  26730. this._texture._sphericalPolynomial = value;
  26731. }
  26732. },
  26733. enumerable: true,
  26734. configurable: true
  26735. });
  26736. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26737. get: function () {
  26738. if (this._texture) {
  26739. return this._texture._lodTextureHigh;
  26740. }
  26741. return null;
  26742. },
  26743. enumerable: true,
  26744. configurable: true
  26745. });
  26746. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26747. get: function () {
  26748. if (this._texture) {
  26749. return this._texture._lodTextureMid;
  26750. }
  26751. return null;
  26752. },
  26753. enumerable: true,
  26754. configurable: true
  26755. });
  26756. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26757. get: function () {
  26758. if (this._texture) {
  26759. return this._texture._lodTextureLow;
  26760. }
  26761. return null;
  26762. },
  26763. enumerable: true,
  26764. configurable: true
  26765. });
  26766. BaseTexture.prototype.dispose = function () {
  26767. if (!this._scene) {
  26768. return;
  26769. }
  26770. // Animations
  26771. this._scene.stopAnimation(this);
  26772. // Remove from scene
  26773. this._scene._removePendingData(this);
  26774. var index = this._scene.textures.indexOf(this);
  26775. if (index >= 0) {
  26776. this._scene.textures.splice(index, 1);
  26777. }
  26778. if (this._texture === undefined) {
  26779. return;
  26780. }
  26781. // Release
  26782. this.releaseInternalTexture();
  26783. // Callback
  26784. this.onDisposeObservable.notifyObservers(this);
  26785. this.onDisposeObservable.clear();
  26786. };
  26787. BaseTexture.prototype.serialize = function () {
  26788. if (!this.name) {
  26789. return null;
  26790. }
  26791. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26792. // Animations
  26793. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26794. return serializationObject;
  26795. };
  26796. BaseTexture.WhenAllReady = function (textures, callback) {
  26797. var numRemaining = textures.length;
  26798. if (numRemaining === 0) {
  26799. callback();
  26800. return;
  26801. }
  26802. var _loop_1 = function () {
  26803. texture = textures[i];
  26804. if (texture.isReady()) {
  26805. if (--numRemaining === 0) {
  26806. callback();
  26807. }
  26808. }
  26809. else {
  26810. onLoadObservable = texture.onLoadObservable;
  26811. var onLoadCallback_1 = function () {
  26812. onLoadObservable.removeCallback(onLoadCallback_1);
  26813. if (--numRemaining === 0) {
  26814. callback();
  26815. }
  26816. };
  26817. onLoadObservable.add(onLoadCallback_1);
  26818. }
  26819. };
  26820. var texture, onLoadObservable;
  26821. for (var i = 0; i < textures.length; i++) {
  26822. _loop_1();
  26823. }
  26824. };
  26825. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26826. __decorate([
  26827. BABYLON.serialize()
  26828. ], BaseTexture.prototype, "name", void 0);
  26829. __decorate([
  26830. BABYLON.serialize("hasAlpha")
  26831. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26832. __decorate([
  26833. BABYLON.serialize()
  26834. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26835. __decorate([
  26836. BABYLON.serialize()
  26837. ], BaseTexture.prototype, "level", void 0);
  26838. __decorate([
  26839. BABYLON.serialize()
  26840. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26841. __decorate([
  26842. BABYLON.serialize("coordinatesMode")
  26843. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26844. __decorate([
  26845. BABYLON.serialize()
  26846. ], BaseTexture.prototype, "wrapU", void 0);
  26847. __decorate([
  26848. BABYLON.serialize()
  26849. ], BaseTexture.prototype, "wrapV", void 0);
  26850. __decorate([
  26851. BABYLON.serialize()
  26852. ], BaseTexture.prototype, "wrapR", void 0);
  26853. __decorate([
  26854. BABYLON.serialize()
  26855. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26856. __decorate([
  26857. BABYLON.serialize()
  26858. ], BaseTexture.prototype, "isCube", void 0);
  26859. __decorate([
  26860. BABYLON.serialize()
  26861. ], BaseTexture.prototype, "is3D", void 0);
  26862. __decorate([
  26863. BABYLON.serialize()
  26864. ], BaseTexture.prototype, "gammaSpace", void 0);
  26865. __decorate([
  26866. BABYLON.serialize()
  26867. ], BaseTexture.prototype, "invertZ", void 0);
  26868. __decorate([
  26869. BABYLON.serialize()
  26870. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26871. __decorate([
  26872. BABYLON.serialize()
  26873. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26874. __decorate([
  26875. BABYLON.serialize()
  26876. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26877. __decorate([
  26878. BABYLON.serialize()
  26879. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26880. return BaseTexture;
  26881. }());
  26882. BABYLON.BaseTexture = BaseTexture;
  26883. })(BABYLON || (BABYLON = {}));
  26884. //# sourceMappingURL=babylon.baseTexture.js.map
  26885. var BABYLON;
  26886. (function (BABYLON) {
  26887. var Texture = /** @class */ (function (_super) {
  26888. __extends(Texture, _super);
  26889. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26890. if (noMipmap === void 0) { noMipmap = false; }
  26891. if (invertY === void 0) { invertY = true; }
  26892. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26893. if (onLoad === void 0) { onLoad = null; }
  26894. if (onError === void 0) { onError = null; }
  26895. if (buffer === void 0) { buffer = null; }
  26896. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26897. var _this = _super.call(this, scene) || this;
  26898. _this.uOffset = 0;
  26899. _this.vOffset = 0;
  26900. _this.uScale = 1.0;
  26901. _this.vScale = 1.0;
  26902. _this.uAng = 0;
  26903. _this.vAng = 0;
  26904. _this.wAng = 0;
  26905. _this._isBlocking = true;
  26906. _this.name = url || "";
  26907. _this.url = url;
  26908. _this._noMipmap = noMipmap;
  26909. _this._invertY = invertY;
  26910. _this._samplingMode = samplingMode;
  26911. _this._buffer = buffer;
  26912. _this._deleteBuffer = deleteBuffer;
  26913. if (format) {
  26914. _this._format = format;
  26915. }
  26916. scene = _this.getScene();
  26917. if (!scene) {
  26918. return _this;
  26919. }
  26920. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26921. var load = function () {
  26922. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26923. _this.onLoadObservable.notifyObservers(_this);
  26924. }
  26925. if (onLoad) {
  26926. onLoad();
  26927. }
  26928. if (!_this.isBlocking && scene) {
  26929. scene.resetCachedMaterial();
  26930. }
  26931. };
  26932. if (!_this.url) {
  26933. _this._delayedOnLoad = load;
  26934. _this._delayedOnError = onError;
  26935. return _this;
  26936. }
  26937. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26938. if (!_this._texture) {
  26939. if (!scene.useDelayedTextureLoading) {
  26940. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26941. if (deleteBuffer) {
  26942. delete _this._buffer;
  26943. }
  26944. }
  26945. else {
  26946. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26947. _this._delayedOnLoad = load;
  26948. _this._delayedOnError = onError;
  26949. }
  26950. }
  26951. else {
  26952. if (_this._texture.isReady) {
  26953. BABYLON.Tools.SetImmediate(function () { return load(); });
  26954. }
  26955. else {
  26956. _this._texture.onLoadedObservable.add(load);
  26957. }
  26958. }
  26959. return _this;
  26960. }
  26961. Object.defineProperty(Texture.prototype, "noMipmap", {
  26962. get: function () {
  26963. return this._noMipmap;
  26964. },
  26965. enumerable: true,
  26966. configurable: true
  26967. });
  26968. Object.defineProperty(Texture.prototype, "isBlocking", {
  26969. get: function () {
  26970. return this._isBlocking;
  26971. },
  26972. set: function (value) {
  26973. this._isBlocking = value;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. Object.defineProperty(Texture.prototype, "samplingMode", {
  26979. get: function () {
  26980. return this._samplingMode;
  26981. },
  26982. enumerable: true,
  26983. configurable: true
  26984. });
  26985. Texture.prototype.updateURL = function (url) {
  26986. this.url = url;
  26987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26988. this.delayLoad();
  26989. };
  26990. Texture.prototype.delayLoad = function () {
  26991. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26992. return;
  26993. }
  26994. var scene = this.getScene();
  26995. if (!scene) {
  26996. return;
  26997. }
  26998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26999. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27000. if (!this._texture) {
  27001. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27002. if (this._deleteBuffer) {
  27003. delete this._buffer;
  27004. }
  27005. }
  27006. else {
  27007. if (this._delayedOnLoad) {
  27008. if (this._texture.isReady) {
  27009. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27010. }
  27011. else {
  27012. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27013. }
  27014. }
  27015. }
  27016. this._delayedOnLoad = null;
  27017. this._delayedOnError = null;
  27018. };
  27019. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27020. if (!this._texture) {
  27021. return;
  27022. }
  27023. var scene = this.getScene();
  27024. if (!scene) {
  27025. return;
  27026. }
  27027. this._samplingMode = samplingMode;
  27028. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27029. };
  27030. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27031. x *= this.uScale;
  27032. y *= this.vScale;
  27033. x -= 0.5 * this.uScale;
  27034. y -= 0.5 * this.vScale;
  27035. z -= 0.5;
  27036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27037. t.x += 0.5 * this.uScale + this.uOffset;
  27038. t.y += 0.5 * this.vScale + this.vOffset;
  27039. t.z += 0.5;
  27040. };
  27041. Texture.prototype.getTextureMatrix = function () {
  27042. var _this = this;
  27043. if (this.uOffset === this._cachedUOffset &&
  27044. this.vOffset === this._cachedVOffset &&
  27045. this.uScale === this._cachedUScale &&
  27046. this.vScale === this._cachedVScale &&
  27047. this.uAng === this._cachedUAng &&
  27048. this.vAng === this._cachedVAng &&
  27049. this.wAng === this._cachedWAng) {
  27050. return this._cachedTextureMatrix;
  27051. }
  27052. this._cachedUOffset = this.uOffset;
  27053. this._cachedVOffset = this.vOffset;
  27054. this._cachedUScale = this.uScale;
  27055. this._cachedVScale = this.vScale;
  27056. this._cachedUAng = this.uAng;
  27057. this._cachedVAng = this.vAng;
  27058. this._cachedWAng = this.wAng;
  27059. if (!this._cachedTextureMatrix) {
  27060. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27061. this._rowGenerationMatrix = new BABYLON.Matrix();
  27062. this._t0 = BABYLON.Vector3.Zero();
  27063. this._t1 = BABYLON.Vector3.Zero();
  27064. this._t2 = BABYLON.Vector3.Zero();
  27065. }
  27066. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27067. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27068. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27069. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27070. this._t1.subtractInPlace(this._t0);
  27071. this._t2.subtractInPlace(this._t0);
  27072. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27073. this._cachedTextureMatrix.m[0] = this._t1.x;
  27074. this._cachedTextureMatrix.m[1] = this._t1.y;
  27075. this._cachedTextureMatrix.m[2] = this._t1.z;
  27076. this._cachedTextureMatrix.m[4] = this._t2.x;
  27077. this._cachedTextureMatrix.m[5] = this._t2.y;
  27078. this._cachedTextureMatrix.m[6] = this._t2.z;
  27079. this._cachedTextureMatrix.m[8] = this._t0.x;
  27080. this._cachedTextureMatrix.m[9] = this._t0.y;
  27081. this._cachedTextureMatrix.m[10] = this._t0.z;
  27082. var scene = this.getScene();
  27083. if (!scene) {
  27084. return this._cachedTextureMatrix;
  27085. }
  27086. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27087. return mat.hasTexture(_this);
  27088. });
  27089. return this._cachedTextureMatrix;
  27090. };
  27091. Texture.prototype.getReflectionTextureMatrix = function () {
  27092. var _this = this;
  27093. var scene = this.getScene();
  27094. if (!scene) {
  27095. return this._cachedTextureMatrix;
  27096. }
  27097. if (this.uOffset === this._cachedUOffset &&
  27098. this.vOffset === this._cachedVOffset &&
  27099. this.uScale === this._cachedUScale &&
  27100. this.vScale === this._cachedVScale &&
  27101. this.coordinatesMode === this._cachedCoordinatesMode) {
  27102. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27103. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27104. return this._cachedTextureMatrix;
  27105. }
  27106. }
  27107. else {
  27108. return this._cachedTextureMatrix;
  27109. }
  27110. }
  27111. if (!this._cachedTextureMatrix) {
  27112. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27113. }
  27114. if (!this._projectionModeMatrix) {
  27115. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27116. }
  27117. this._cachedUOffset = this.uOffset;
  27118. this._cachedVOffset = this.vOffset;
  27119. this._cachedUScale = this.uScale;
  27120. this._cachedVScale = this.vScale;
  27121. this._cachedCoordinatesMode = this.coordinatesMode;
  27122. switch (this.coordinatesMode) {
  27123. case Texture.PLANAR_MODE:
  27124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27125. this._cachedTextureMatrix[0] = this.uScale;
  27126. this._cachedTextureMatrix[5] = this.vScale;
  27127. this._cachedTextureMatrix[12] = this.uOffset;
  27128. this._cachedTextureMatrix[13] = this.vOffset;
  27129. break;
  27130. case Texture.PROJECTION_MODE:
  27131. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27132. this._projectionModeMatrix.m[0] = 0.5;
  27133. this._projectionModeMatrix.m[5] = -0.5;
  27134. this._projectionModeMatrix.m[10] = 0.0;
  27135. this._projectionModeMatrix.m[12] = 0.5;
  27136. this._projectionModeMatrix.m[13] = 0.5;
  27137. this._projectionModeMatrix.m[14] = 1.0;
  27138. this._projectionModeMatrix.m[15] = 1.0;
  27139. var projectionMatrix = scene.getProjectionMatrix();
  27140. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27141. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27142. break;
  27143. default:
  27144. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27145. break;
  27146. }
  27147. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27148. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27149. });
  27150. return this._cachedTextureMatrix;
  27151. };
  27152. Texture.prototype.clone = function () {
  27153. var _this = this;
  27154. return BABYLON.SerializationHelper.Clone(function () {
  27155. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27156. }, this);
  27157. };
  27158. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27159. get: function () {
  27160. if (!this._onLoadObservable) {
  27161. this._onLoadObservable = new BABYLON.Observable();
  27162. }
  27163. return this._onLoadObservable;
  27164. },
  27165. enumerable: true,
  27166. configurable: true
  27167. });
  27168. Texture.prototype.serialize = function () {
  27169. var serializationObject = _super.prototype.serialize.call(this);
  27170. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27171. serializationObject.base64String = this._buffer;
  27172. serializationObject.name = serializationObject.name.replace("data:", "");
  27173. }
  27174. return serializationObject;
  27175. };
  27176. Texture.prototype.getClassName = function () {
  27177. return "Texture";
  27178. };
  27179. Texture.prototype.dispose = function () {
  27180. _super.prototype.dispose.call(this);
  27181. if (this.onLoadObservable) {
  27182. this.onLoadObservable.clear();
  27183. this._onLoadObservable = null;
  27184. }
  27185. this._delayedOnLoad = null;
  27186. this._delayedOnError = null;
  27187. };
  27188. // Statics
  27189. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27190. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27191. if (onLoad === void 0) { onLoad = null; }
  27192. if (onError === void 0) { onError = null; }
  27193. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27194. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27195. };
  27196. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27197. if (parsedTexture.customType) {
  27198. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27199. // Update Sampling Mode
  27200. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27201. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27202. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27203. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27204. }
  27205. }
  27206. return parsedCustomTexture;
  27207. }
  27208. if (parsedTexture.isCube) {
  27209. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27210. }
  27211. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27212. return null;
  27213. }
  27214. var texture = BABYLON.SerializationHelper.Parse(function () {
  27215. var generateMipMaps = true;
  27216. if (parsedTexture.noMipmap) {
  27217. generateMipMaps = false;
  27218. }
  27219. if (parsedTexture.mirrorPlane) {
  27220. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27221. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27222. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27223. return mirrorTexture;
  27224. }
  27225. else if (parsedTexture.isRenderTarget) {
  27226. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27227. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27228. return renderTargetTexture;
  27229. }
  27230. else {
  27231. var texture;
  27232. if (parsedTexture.base64String) {
  27233. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27234. }
  27235. else {
  27236. var url = rootUrl + parsedTexture.name;
  27237. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27238. url = parsedTexture.url;
  27239. }
  27240. texture = new Texture(url, scene, !generateMipMaps);
  27241. }
  27242. return texture;
  27243. }
  27244. }, parsedTexture, scene);
  27245. // Update Sampling Mode
  27246. if (parsedTexture.samplingMode) {
  27247. var sampling = parsedTexture.samplingMode;
  27248. if (texture._samplingMode !== sampling) {
  27249. texture.updateSamplingMode(sampling);
  27250. }
  27251. }
  27252. // Animations
  27253. if (parsedTexture.animations) {
  27254. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27255. var parsedAnimation = parsedTexture.animations[animationIndex];
  27256. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27257. }
  27258. }
  27259. return texture;
  27260. };
  27261. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27262. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27263. if (noMipmap === void 0) { noMipmap = false; }
  27264. if (invertY === void 0) { invertY = true; }
  27265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27266. if (onLoad === void 0) { onLoad = null; }
  27267. if (onError === void 0) { onError = null; }
  27268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27269. if (name.substr(0, 5) !== "data:") {
  27270. name = "data:" + name;
  27271. }
  27272. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27273. };
  27274. // Constants
  27275. Texture.NEAREST_SAMPLINGMODE = 1;
  27276. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27277. Texture.BILINEAR_SAMPLINGMODE = 2;
  27278. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27279. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27280. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27281. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27282. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27283. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27284. Texture.NEAREST_LINEAR = 7;
  27285. Texture.NEAREST_NEAREST = 8;
  27286. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27287. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27288. Texture.LINEAR_LINEAR = 11;
  27289. Texture.LINEAR_NEAREST = 12;
  27290. Texture.EXPLICIT_MODE = 0;
  27291. Texture.SPHERICAL_MODE = 1;
  27292. Texture.PLANAR_MODE = 2;
  27293. Texture.CUBIC_MODE = 3;
  27294. Texture.PROJECTION_MODE = 4;
  27295. Texture.SKYBOX_MODE = 5;
  27296. Texture.INVCUBIC_MODE = 6;
  27297. Texture.EQUIRECTANGULAR_MODE = 7;
  27298. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27299. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27300. Texture.CLAMP_ADDRESSMODE = 0;
  27301. Texture.WRAP_ADDRESSMODE = 1;
  27302. Texture.MIRROR_ADDRESSMODE = 2;
  27303. /**
  27304. * 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
  27305. */
  27306. Texture.UseSerializedUrlIfAny = false;
  27307. __decorate([
  27308. BABYLON.serialize()
  27309. ], Texture.prototype, "url", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], Texture.prototype, "uOffset", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], Texture.prototype, "vOffset", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], Texture.prototype, "uScale", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], Texture.prototype, "vScale", void 0);
  27322. __decorate([
  27323. BABYLON.serialize()
  27324. ], Texture.prototype, "uAng", void 0);
  27325. __decorate([
  27326. BABYLON.serialize()
  27327. ], Texture.prototype, "vAng", void 0);
  27328. __decorate([
  27329. BABYLON.serialize()
  27330. ], Texture.prototype, "wAng", void 0);
  27331. __decorate([
  27332. BABYLON.serialize()
  27333. ], Texture.prototype, "isBlocking", null);
  27334. return Texture;
  27335. }(BABYLON.BaseTexture));
  27336. BABYLON.Texture = Texture;
  27337. })(BABYLON || (BABYLON = {}));
  27338. //# sourceMappingURL=babylon.texture.js.map
  27339. var BABYLON;
  27340. (function (BABYLON) {
  27341. var _InstancesBatch = /** @class */ (function () {
  27342. function _InstancesBatch() {
  27343. this.mustReturn = false;
  27344. this.visibleInstances = new Array();
  27345. this.renderSelf = new Array();
  27346. }
  27347. return _InstancesBatch;
  27348. }());
  27349. BABYLON._InstancesBatch = _InstancesBatch;
  27350. var Mesh = /** @class */ (function (_super) {
  27351. __extends(Mesh, _super);
  27352. /**
  27353. * @constructor
  27354. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27355. * @param {Scene} scene The scene to add this mesh to.
  27356. * @param {Node} parent The parent of this mesh, if it has one
  27357. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27358. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27359. * When false, achieved by calling a clone(), also passing False.
  27360. * This will make creation of children, recursive.
  27361. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27362. */
  27363. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27364. if (scene === void 0) { scene = null; }
  27365. if (parent === void 0) { parent = null; }
  27366. if (source === void 0) { source = null; }
  27367. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27368. var _this = _super.call(this, name, scene) || this;
  27369. // Events
  27370. /**
  27371. * An event triggered before rendering the mesh
  27372. * @type {BABYLON.Observable}
  27373. */
  27374. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27375. /**
  27376. * An event triggered after rendering the mesh
  27377. * @type {BABYLON.Observable}
  27378. */
  27379. _this.onAfterRenderObservable = new BABYLON.Observable();
  27380. /**
  27381. * An event triggered before drawing the mesh
  27382. * @type {BABYLON.Observable}
  27383. */
  27384. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27385. // Members
  27386. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27387. _this.instances = new Array();
  27388. _this._LODLevels = new Array();
  27389. _this._visibleInstances = {};
  27390. _this._renderIdForInstances = new Array();
  27391. _this._batchCache = new _InstancesBatch();
  27392. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27393. // Use by builder only to know what orientation were the mesh build in.
  27394. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27395. _this.overrideMaterialSideOrientation = null;
  27396. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27397. // Will be used to save a source mesh reference, If any
  27398. _this._source = null;
  27399. scene = _this.getScene();
  27400. if (source) {
  27401. // Source mesh
  27402. _this._source = source;
  27403. // Geometry
  27404. if (source._geometry) {
  27405. source._geometry.applyToMesh(_this);
  27406. }
  27407. // Deep copy
  27408. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27409. // Metadata
  27410. if (source.metadata && source.metadata.clone) {
  27411. _this.metadata = source.metadata.clone();
  27412. }
  27413. else {
  27414. _this.metadata = source.metadata;
  27415. }
  27416. // Tags
  27417. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27418. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27419. }
  27420. // Parent
  27421. _this.parent = source.parent;
  27422. // Pivot
  27423. _this.setPivotMatrix(source.getPivotMatrix());
  27424. _this.id = name + "." + source.id;
  27425. // Material
  27426. _this.material = source.material;
  27427. var index;
  27428. if (!doNotCloneChildren) {
  27429. // Children
  27430. var directDescendants = source.getDescendants(true);
  27431. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27432. var child = directDescendants[index_1];
  27433. if (child.clone) {
  27434. child.clone(name + "." + child.name, _this);
  27435. }
  27436. }
  27437. }
  27438. // Physics clone
  27439. var physicsEngine = _this.getScene().getPhysicsEngine();
  27440. if (clonePhysicsImpostor && physicsEngine) {
  27441. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27442. if (impostor) {
  27443. _this.physicsImpostor = impostor.clone(_this);
  27444. }
  27445. }
  27446. // Particles
  27447. for (index = 0; index < scene.particleSystems.length; index++) {
  27448. var system = scene.particleSystems[index];
  27449. if (system.emitter === source) {
  27450. system.clone(system.name, _this);
  27451. }
  27452. }
  27453. _this.computeWorldMatrix(true);
  27454. }
  27455. // Parent
  27456. if (parent !== null) {
  27457. _this.parent = parent;
  27458. }
  27459. return _this;
  27460. }
  27461. Object.defineProperty(Mesh, "FRONTSIDE", {
  27462. /**
  27463. * Mesh side orientation : usually the external or front surface
  27464. */
  27465. get: function () {
  27466. return Mesh._FRONTSIDE;
  27467. },
  27468. enumerable: true,
  27469. configurable: true
  27470. });
  27471. Object.defineProperty(Mesh, "BACKSIDE", {
  27472. /**
  27473. * Mesh side orientation : usually the internal or back surface
  27474. */
  27475. get: function () {
  27476. return Mesh._BACKSIDE;
  27477. },
  27478. enumerable: true,
  27479. configurable: true
  27480. });
  27481. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27482. /**
  27483. * Mesh side orientation : both internal and external or front and back surfaces
  27484. */
  27485. get: function () {
  27486. return Mesh._DOUBLESIDE;
  27487. },
  27488. enumerable: true,
  27489. configurable: true
  27490. });
  27491. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27492. /**
  27493. * Mesh side orientation : by default, `FRONTSIDE`
  27494. */
  27495. get: function () {
  27496. return Mesh._DEFAULTSIDE;
  27497. },
  27498. enumerable: true,
  27499. configurable: true
  27500. });
  27501. Object.defineProperty(Mesh, "NO_CAP", {
  27502. /**
  27503. * Mesh cap setting : no cap
  27504. */
  27505. get: function () {
  27506. return Mesh._NO_CAP;
  27507. },
  27508. enumerable: true,
  27509. configurable: true
  27510. });
  27511. Object.defineProperty(Mesh, "CAP_START", {
  27512. /**
  27513. * Mesh cap setting : one cap at the beginning of the mesh
  27514. */
  27515. get: function () {
  27516. return Mesh._CAP_START;
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Object.defineProperty(Mesh, "CAP_END", {
  27522. /**
  27523. * Mesh cap setting : one cap at the end of the mesh
  27524. */
  27525. get: function () {
  27526. return Mesh._CAP_END;
  27527. },
  27528. enumerable: true,
  27529. configurable: true
  27530. });
  27531. Object.defineProperty(Mesh, "CAP_ALL", {
  27532. /**
  27533. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27534. */
  27535. get: function () {
  27536. return Mesh._CAP_ALL;
  27537. },
  27538. enumerable: true,
  27539. configurable: true
  27540. });
  27541. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27542. set: function (callback) {
  27543. if (this._onBeforeDrawObserver) {
  27544. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27545. }
  27546. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27547. },
  27548. enumerable: true,
  27549. configurable: true
  27550. });
  27551. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27552. get: function () {
  27553. return this._morphTargetManager;
  27554. },
  27555. set: function (value) {
  27556. if (this._morphTargetManager === value) {
  27557. return;
  27558. }
  27559. this._morphTargetManager = value;
  27560. this._syncGeometryWithMorphTargetManager();
  27561. },
  27562. enumerable: true,
  27563. configurable: true
  27564. });
  27565. Object.defineProperty(Mesh.prototype, "source", {
  27566. get: function () {
  27567. return this._source;
  27568. },
  27569. enumerable: true,
  27570. configurable: true
  27571. });
  27572. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27573. get: function () {
  27574. return this._unIndexed;
  27575. },
  27576. set: function (value) {
  27577. if (this._unIndexed !== value) {
  27578. this._unIndexed = value;
  27579. this._markSubMeshesAsAttributesDirty();
  27580. }
  27581. },
  27582. enumerable: true,
  27583. configurable: true
  27584. });
  27585. // Methods
  27586. /**
  27587. * Returns the string "Mesh".
  27588. */
  27589. Mesh.prototype.getClassName = function () {
  27590. return "Mesh";
  27591. };
  27592. /**
  27593. * Returns a string.
  27594. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27595. */
  27596. Mesh.prototype.toString = function (fullDetails) {
  27597. var ret = _super.prototype.toString.call(this, fullDetails);
  27598. ret += ", n vertices: " + this.getTotalVertices();
  27599. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27600. if (this.animations) {
  27601. for (var i = 0; i < this.animations.length; i++) {
  27602. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27603. }
  27604. }
  27605. if (fullDetails) {
  27606. if (this._geometry) {
  27607. var ib = this.getIndices();
  27608. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27609. if (vb && ib) {
  27610. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27611. }
  27612. }
  27613. else {
  27614. ret += ", flat shading: UNKNOWN";
  27615. }
  27616. }
  27617. return ret;
  27618. };
  27619. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27620. /**
  27621. * True if the mesh has some Levels Of Details (LOD).
  27622. * Returns a boolean.
  27623. */
  27624. get: function () {
  27625. return this._LODLevels.length > 0;
  27626. },
  27627. enumerable: true,
  27628. configurable: true
  27629. });
  27630. /**
  27631. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27632. * @returns an array of {BABYLON.MeshLODLevel}
  27633. */
  27634. Mesh.prototype.getLODLevels = function () {
  27635. return this._LODLevels;
  27636. };
  27637. Mesh.prototype._sortLODLevels = function () {
  27638. this._LODLevels.sort(function (a, b) {
  27639. if (a.distance < b.distance) {
  27640. return 1;
  27641. }
  27642. if (a.distance > b.distance) {
  27643. return -1;
  27644. }
  27645. return 0;
  27646. });
  27647. };
  27648. /**
  27649. * Add a mesh as LOD level triggered at the given distance.
  27650. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27651. * @param {number} distance The distance from the center of the object to show this level
  27652. * @param {Mesh} mesh The mesh to be added as LOD level
  27653. * @return {Mesh} This mesh (for chaining)
  27654. */
  27655. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27656. if (mesh && mesh._masterMesh) {
  27657. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27658. return this;
  27659. }
  27660. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27661. this._LODLevels.push(level);
  27662. if (mesh) {
  27663. mesh._masterMesh = this;
  27664. }
  27665. this._sortLODLevels();
  27666. return this;
  27667. };
  27668. /**
  27669. * Returns the LOD level mesh at the passed distance or null if not found.
  27670. * It is related to the method `addLODLevel(distance, mesh)`.
  27671. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27672. * Returns an object Mesh or `null`.
  27673. */
  27674. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27675. for (var index = 0; index < this._LODLevels.length; index++) {
  27676. var level = this._LODLevels[index];
  27677. if (level.distance === distance) {
  27678. return level.mesh;
  27679. }
  27680. }
  27681. return null;
  27682. };
  27683. /**
  27684. * Remove a mesh from the LOD array
  27685. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27686. * @param {Mesh} mesh The mesh to be removed.
  27687. * @return {Mesh} This mesh (for chaining)
  27688. */
  27689. Mesh.prototype.removeLODLevel = function (mesh) {
  27690. for (var index = 0; index < this._LODLevels.length; index++) {
  27691. if (this._LODLevels[index].mesh === mesh) {
  27692. this._LODLevels.splice(index, 1);
  27693. if (mesh) {
  27694. mesh._masterMesh = null;
  27695. }
  27696. }
  27697. }
  27698. this._sortLODLevels();
  27699. return this;
  27700. };
  27701. /**
  27702. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27703. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27704. */
  27705. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27706. if (!this._LODLevels || this._LODLevels.length === 0) {
  27707. return this;
  27708. }
  27709. var bSphere;
  27710. if (boundingSphere) {
  27711. bSphere = boundingSphere;
  27712. }
  27713. else {
  27714. var boundingInfo = this.getBoundingInfo();
  27715. bSphere = boundingInfo.boundingSphere;
  27716. }
  27717. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27718. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27719. if (this.onLODLevelSelection) {
  27720. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27721. }
  27722. return this;
  27723. }
  27724. for (var index = 0; index < this._LODLevels.length; index++) {
  27725. var level = this._LODLevels[index];
  27726. if (level.distance < distanceToCamera) {
  27727. if (level.mesh) {
  27728. level.mesh._preActivate();
  27729. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27730. }
  27731. if (this.onLODLevelSelection) {
  27732. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27733. }
  27734. return level.mesh;
  27735. }
  27736. }
  27737. if (this.onLODLevelSelection) {
  27738. this.onLODLevelSelection(distanceToCamera, this, this);
  27739. }
  27740. return this;
  27741. };
  27742. Object.defineProperty(Mesh.prototype, "geometry", {
  27743. /**
  27744. * Returns the mesh internal Geometry object.
  27745. */
  27746. get: function () {
  27747. return this._geometry;
  27748. },
  27749. enumerable: true,
  27750. configurable: true
  27751. });
  27752. /**
  27753. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27754. */
  27755. Mesh.prototype.getTotalVertices = function () {
  27756. if (this._geometry === null || this._geometry === undefined) {
  27757. return 0;
  27758. }
  27759. return this._geometry.getTotalVertices();
  27760. };
  27761. /**
  27762. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27763. * 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.
  27764. * You can force the copy with forceCopy === true
  27765. * Returns null if the mesh has no geometry or no vertex buffer.
  27766. * Possible `kind` values :
  27767. * - BABYLON.VertexBuffer.PositionKind
  27768. * - BABYLON.VertexBuffer.UVKind
  27769. * - BABYLON.VertexBuffer.UV2Kind
  27770. * - BABYLON.VertexBuffer.UV3Kind
  27771. * - BABYLON.VertexBuffer.UV4Kind
  27772. * - BABYLON.VertexBuffer.UV5Kind
  27773. * - BABYLON.VertexBuffer.UV6Kind
  27774. * - BABYLON.VertexBuffer.ColorKind
  27775. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27776. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27777. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27778. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27779. */
  27780. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27781. if (!this._geometry) {
  27782. return null;
  27783. }
  27784. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27785. };
  27786. /**
  27787. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27788. * Returns `null` if the mesh has no geometry.
  27789. * Possible `kind` values :
  27790. * - BABYLON.VertexBuffer.PositionKind
  27791. * - BABYLON.VertexBuffer.UVKind
  27792. * - BABYLON.VertexBuffer.UV2Kind
  27793. * - BABYLON.VertexBuffer.UV3Kind
  27794. * - BABYLON.VertexBuffer.UV4Kind
  27795. * - BABYLON.VertexBuffer.UV5Kind
  27796. * - BABYLON.VertexBuffer.UV6Kind
  27797. * - BABYLON.VertexBuffer.ColorKind
  27798. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27799. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27800. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27801. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27802. */
  27803. Mesh.prototype.getVertexBuffer = function (kind) {
  27804. if (!this._geometry) {
  27805. return null;
  27806. }
  27807. return this._geometry.getVertexBuffer(kind);
  27808. };
  27809. /**
  27810. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27811. * Possible `kind` values :
  27812. * - BABYLON.VertexBuffer.PositionKind
  27813. * - BABYLON.VertexBuffer.UVKind
  27814. * - BABYLON.VertexBuffer.UV2Kind
  27815. * - BABYLON.VertexBuffer.UV3Kind
  27816. * - BABYLON.VertexBuffer.UV4Kind
  27817. * - BABYLON.VertexBuffer.UV5Kind
  27818. * - BABYLON.VertexBuffer.UV6Kind
  27819. * - BABYLON.VertexBuffer.ColorKind
  27820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27824. */
  27825. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27826. if (!this._geometry) {
  27827. if (this._delayInfo) {
  27828. return this._delayInfo.indexOf(kind) !== -1;
  27829. }
  27830. return false;
  27831. }
  27832. return this._geometry.isVerticesDataPresent(kind);
  27833. };
  27834. /**
  27835. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27836. * Possible `kind` values :
  27837. * - BABYLON.VertexBuffer.PositionKind
  27838. * - BABYLON.VertexBuffer.UVKind
  27839. * - BABYLON.VertexBuffer.UV2Kind
  27840. * - BABYLON.VertexBuffer.UV3Kind
  27841. * - BABYLON.VertexBuffer.UV4Kind
  27842. * - BABYLON.VertexBuffer.UV5Kind
  27843. * - BABYLON.VertexBuffer.UV6Kind
  27844. * - BABYLON.VertexBuffer.ColorKind
  27845. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27846. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27847. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27848. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27849. */
  27850. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27851. if (!this._geometry) {
  27852. if (this._delayInfo) {
  27853. return this._delayInfo.indexOf(kind) !== -1;
  27854. }
  27855. return false;
  27856. }
  27857. return this._geometry.isVertexBufferUpdatable(kind);
  27858. };
  27859. /**
  27860. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27861. * Possible `kind` values :
  27862. * - BABYLON.VertexBuffer.PositionKind
  27863. * - BABYLON.VertexBuffer.UVKind
  27864. * - BABYLON.VertexBuffer.UV2Kind
  27865. * - BABYLON.VertexBuffer.UV3Kind
  27866. * - BABYLON.VertexBuffer.UV4Kind
  27867. * - BABYLON.VertexBuffer.UV5Kind
  27868. * - BABYLON.VertexBuffer.UV6Kind
  27869. * - BABYLON.VertexBuffer.ColorKind
  27870. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27871. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27872. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27873. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27874. */
  27875. Mesh.prototype.getVerticesDataKinds = function () {
  27876. if (!this._geometry) {
  27877. var result = new Array();
  27878. if (this._delayInfo) {
  27879. this._delayInfo.forEach(function (kind, index, array) {
  27880. result.push(kind);
  27881. });
  27882. }
  27883. return result;
  27884. }
  27885. return this._geometry.getVerticesDataKinds();
  27886. };
  27887. /**
  27888. * Returns a positive integer : the total number of indices in this mesh geometry.
  27889. * Returns zero if the mesh has no geometry.
  27890. */
  27891. Mesh.prototype.getTotalIndices = function () {
  27892. if (!this._geometry) {
  27893. return 0;
  27894. }
  27895. return this._geometry.getTotalIndices();
  27896. };
  27897. /**
  27898. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27899. * 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.
  27900. * Returns an empty array if the mesh has no geometry.
  27901. */
  27902. Mesh.prototype.getIndices = function (copyWhenShared) {
  27903. if (!this._geometry) {
  27904. return [];
  27905. }
  27906. return this._geometry.getIndices(copyWhenShared);
  27907. };
  27908. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27909. get: function () {
  27910. return this._masterMesh !== null && this._masterMesh !== undefined;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. /**
  27916. * Determine if the current mesh is ready to be rendered
  27917. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27918. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27919. * @returns true if all associated assets are ready (material, textures, shaders)
  27920. */
  27921. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27922. if (completeCheck === void 0) { completeCheck = false; }
  27923. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27924. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27925. return false;
  27926. }
  27927. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27928. return false;
  27929. }
  27930. if (!this.subMeshes || this.subMeshes.length === 0) {
  27931. return true;
  27932. }
  27933. if (!completeCheck) {
  27934. return true;
  27935. }
  27936. var engine = this.getEngine();
  27937. var scene = this.getScene();
  27938. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27939. this.computeWorldMatrix();
  27940. var mat = this.material || scene.defaultMaterial;
  27941. if (mat) {
  27942. if (mat.storeEffectOnSubMeshes) {
  27943. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27944. var subMesh = _a[_i];
  27945. var effectiveMaterial = subMesh.getMaterial();
  27946. if (effectiveMaterial) {
  27947. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27948. return false;
  27949. }
  27950. }
  27951. }
  27952. }
  27953. else {
  27954. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27955. return false;
  27956. }
  27957. }
  27958. }
  27959. // Shadows
  27960. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27961. var light = _c[_b];
  27962. var generator = light.getShadowGenerator();
  27963. if (generator) {
  27964. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27965. var subMesh = _e[_d];
  27966. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27967. return false;
  27968. }
  27969. }
  27970. }
  27971. }
  27972. // LOD
  27973. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27974. var lod = _g[_f];
  27975. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27976. return false;
  27977. }
  27978. }
  27979. return true;
  27980. };
  27981. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27982. /**
  27983. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27984. * This property is pertinent only for updatable parametric shapes.
  27985. */
  27986. get: function () {
  27987. return this._areNormalsFrozen;
  27988. },
  27989. enumerable: true,
  27990. configurable: true
  27991. });
  27992. /**
  27993. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27994. * It has no effect at all on other shapes.
  27995. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27996. * Returns the Mesh.
  27997. */
  27998. Mesh.prototype.freezeNormals = function () {
  27999. this._areNormalsFrozen = true;
  28000. return this;
  28001. };
  28002. /**
  28003. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28004. * It has no effect at all on other shapes.
  28005. * It reactivates the mesh normals computation if it was previously frozen.
  28006. * Returns the Mesh.
  28007. */
  28008. Mesh.prototype.unfreezeNormals = function () {
  28009. this._areNormalsFrozen = false;
  28010. return this;
  28011. };
  28012. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28013. /**
  28014. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28015. */
  28016. set: function (count) {
  28017. this._overridenInstanceCount = count;
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. // Methods
  28023. Mesh.prototype._preActivate = function () {
  28024. var sceneRenderId = this.getScene().getRenderId();
  28025. if (this._preActivateId === sceneRenderId) {
  28026. return this;
  28027. }
  28028. this._preActivateId = sceneRenderId;
  28029. this._visibleInstances = null;
  28030. return this;
  28031. };
  28032. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28033. if (this._visibleInstances) {
  28034. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28035. }
  28036. return this;
  28037. };
  28038. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28039. if (!this._visibleInstances) {
  28040. this._visibleInstances = {};
  28041. this._visibleInstances.defaultRenderId = renderId;
  28042. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28043. }
  28044. if (!this._visibleInstances[renderId]) {
  28045. this._visibleInstances[renderId] = new Array();
  28046. }
  28047. this._visibleInstances[renderId].push(instance);
  28048. return this;
  28049. };
  28050. /**
  28051. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28052. * This means the mesh underlying bounding box and sphere are recomputed.
  28053. * Returns the Mesh.
  28054. */
  28055. Mesh.prototype.refreshBoundingInfo = function () {
  28056. return this._refreshBoundingInfo(false);
  28057. };
  28058. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28059. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28060. return this;
  28061. }
  28062. var data = this._getPositionData(applySkeleton);
  28063. if (data) {
  28064. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28065. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28066. }
  28067. if (this.subMeshes) {
  28068. for (var index = 0; index < this.subMeshes.length; index++) {
  28069. this.subMeshes[index].refreshBoundingInfo();
  28070. }
  28071. }
  28072. this._updateBoundingInfo();
  28073. return this;
  28074. };
  28075. Mesh.prototype._getPositionData = function (applySkeleton) {
  28076. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28077. if (data && applySkeleton && this.skeleton) {
  28078. data = BABYLON.Tools.Slice(data);
  28079. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28080. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28081. if (matricesWeightsData && matricesIndicesData) {
  28082. var needExtras = this.numBoneInfluencers > 4;
  28083. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28084. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28085. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28086. var tempVector = BABYLON.Tmp.Vector3[0];
  28087. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28088. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28089. var matWeightIdx = 0;
  28090. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28091. finalMatrix.reset();
  28092. var inf;
  28093. var weight;
  28094. for (inf = 0; inf < 4; inf++) {
  28095. weight = matricesWeightsData[matWeightIdx + inf];
  28096. if (weight <= 0)
  28097. break;
  28098. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28099. finalMatrix.addToSelf(tempMatrix);
  28100. }
  28101. if (needExtras) {
  28102. for (inf = 0; inf < 4; inf++) {
  28103. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28104. if (weight <= 0)
  28105. break;
  28106. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28107. finalMatrix.addToSelf(tempMatrix);
  28108. }
  28109. }
  28110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28111. tempVector.toArray(data, index);
  28112. }
  28113. }
  28114. }
  28115. return data;
  28116. };
  28117. Mesh.prototype._createGlobalSubMesh = function (force) {
  28118. var totalVertices = this.getTotalVertices();
  28119. if (!totalVertices || !this.getIndices()) {
  28120. return null;
  28121. }
  28122. // Check if we need to recreate the submeshes
  28123. if (this.subMeshes && this.subMeshes.length > 0) {
  28124. var ib = this.getIndices();
  28125. if (!ib) {
  28126. return null;
  28127. }
  28128. var totalIndices = ib.length;
  28129. var needToRecreate = false;
  28130. if (force) {
  28131. needToRecreate = true;
  28132. }
  28133. else {
  28134. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28135. var submesh = _a[_i];
  28136. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28137. needToRecreate = true;
  28138. break;
  28139. }
  28140. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28141. needToRecreate = true;
  28142. break;
  28143. }
  28144. }
  28145. }
  28146. if (!needToRecreate) {
  28147. return this.subMeshes[0];
  28148. }
  28149. }
  28150. this.releaseSubMeshes();
  28151. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28152. };
  28153. Mesh.prototype.subdivide = function (count) {
  28154. if (count < 1) {
  28155. return;
  28156. }
  28157. var totalIndices = this.getTotalIndices();
  28158. var subdivisionSize = (totalIndices / count) | 0;
  28159. var offset = 0;
  28160. // Ensure that subdivisionSize is a multiple of 3
  28161. while (subdivisionSize % 3 !== 0) {
  28162. subdivisionSize++;
  28163. }
  28164. this.releaseSubMeshes();
  28165. for (var index = 0; index < count; index++) {
  28166. if (offset >= totalIndices) {
  28167. break;
  28168. }
  28169. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28170. offset += subdivisionSize;
  28171. }
  28172. this.synchronizeInstances();
  28173. };
  28174. /**
  28175. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28176. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28177. * The `data` are either a numeric array either a Float32Array.
  28178. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28179. * 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).
  28180. * Note that a new underlying VertexBuffer object is created each call.
  28181. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28182. *
  28183. * Possible `kind` values :
  28184. * - BABYLON.VertexBuffer.PositionKind
  28185. * - BABYLON.VertexBuffer.UVKind
  28186. * - BABYLON.VertexBuffer.UV2Kind
  28187. * - BABYLON.VertexBuffer.UV3Kind
  28188. * - BABYLON.VertexBuffer.UV4Kind
  28189. * - BABYLON.VertexBuffer.UV5Kind
  28190. * - BABYLON.VertexBuffer.UV6Kind
  28191. * - BABYLON.VertexBuffer.ColorKind
  28192. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28193. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28194. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28195. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28196. *
  28197. * Returns the Mesh.
  28198. */
  28199. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28200. if (updatable === void 0) { updatable = false; }
  28201. if (!this._geometry) {
  28202. var vertexData = new BABYLON.VertexData();
  28203. vertexData.set(data, kind);
  28204. var scene = this.getScene();
  28205. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28206. }
  28207. else {
  28208. this._geometry.setVerticesData(kind, data, updatable, stride);
  28209. }
  28210. return this;
  28211. };
  28212. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28213. if (updatable === void 0) { updatable = true; }
  28214. var vb = this.getVertexBuffer(kind);
  28215. if (!vb || vb.isUpdatable() === updatable) {
  28216. return;
  28217. }
  28218. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28219. };
  28220. /**
  28221. * Sets the mesh VertexBuffer.
  28222. * Returns the Mesh.
  28223. */
  28224. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28225. if (!this._geometry) {
  28226. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28227. }
  28228. this._geometry.setVerticesBuffer(buffer);
  28229. return this;
  28230. };
  28231. /**
  28232. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28233. * If the mesh has no geometry, it is simply returned as it is.
  28234. * The `data` are either a numeric array either a Float32Array.
  28235. * No new underlying VertexBuffer object is created.
  28236. * 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.
  28237. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28238. *
  28239. * Possible `kind` values :
  28240. * - BABYLON.VertexBuffer.PositionKind
  28241. * - BABYLON.VertexBuffer.UVKind
  28242. * - BABYLON.VertexBuffer.UV2Kind
  28243. * - BABYLON.VertexBuffer.UV3Kind
  28244. * - BABYLON.VertexBuffer.UV4Kind
  28245. * - BABYLON.VertexBuffer.UV5Kind
  28246. * - BABYLON.VertexBuffer.UV6Kind
  28247. * - BABYLON.VertexBuffer.ColorKind
  28248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28252. *
  28253. * Returns the Mesh.
  28254. */
  28255. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28256. if (!this._geometry) {
  28257. return this;
  28258. }
  28259. if (!makeItUnique) {
  28260. this._geometry.updateVerticesData(kind, data, updateExtends);
  28261. }
  28262. else {
  28263. this.makeGeometryUnique();
  28264. this.updateVerticesData(kind, data, updateExtends, false);
  28265. }
  28266. return this;
  28267. };
  28268. /**
  28269. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28270. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28271. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28272. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28273. * Returns the Mesh.
  28274. */
  28275. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28276. if (computeNormals === void 0) { computeNormals = true; }
  28277. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28278. if (!positions) {
  28279. return this;
  28280. }
  28281. positionFunction(positions);
  28282. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28283. if (computeNormals) {
  28284. var indices = this.getIndices();
  28285. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28286. if (!normals) {
  28287. return this;
  28288. }
  28289. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28291. }
  28292. return this;
  28293. };
  28294. /**
  28295. * Creates a un-shared specific occurence of the geometry for the mesh.
  28296. * Returns the Mesh.
  28297. */
  28298. Mesh.prototype.makeGeometryUnique = function () {
  28299. if (!this._geometry) {
  28300. return this;
  28301. }
  28302. var oldGeometry = this._geometry;
  28303. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28304. oldGeometry.releaseForMesh(this, true);
  28305. geometry.applyToMesh(this);
  28306. return this;
  28307. };
  28308. /**
  28309. * Sets the mesh indices.
  28310. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28311. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28312. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28313. * This method creates a new index buffer each call.
  28314. * Returns the Mesh.
  28315. */
  28316. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28317. if (totalVertices === void 0) { totalVertices = null; }
  28318. if (updatable === void 0) { updatable = false; }
  28319. if (!this._geometry) {
  28320. var vertexData = new BABYLON.VertexData();
  28321. vertexData.indices = indices;
  28322. var scene = this.getScene();
  28323. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28324. }
  28325. else {
  28326. this._geometry.setIndices(indices, totalVertices, updatable);
  28327. }
  28328. return this;
  28329. };
  28330. /**
  28331. * Update the current index buffer
  28332. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28333. * Returns the Mesh.
  28334. */
  28335. Mesh.prototype.updateIndices = function (indices, offset) {
  28336. if (!this._geometry) {
  28337. return this;
  28338. }
  28339. this._geometry.updateIndices(indices, offset);
  28340. return this;
  28341. };
  28342. /**
  28343. * Invert the geometry to move from a right handed system to a left handed one.
  28344. * Returns the Mesh.
  28345. */
  28346. Mesh.prototype.toLeftHanded = function () {
  28347. if (!this._geometry) {
  28348. return this;
  28349. }
  28350. this._geometry.toLeftHanded();
  28351. return this;
  28352. };
  28353. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28354. if (!this._geometry) {
  28355. return this;
  28356. }
  28357. var engine = this.getScene().getEngine();
  28358. // Wireframe
  28359. var indexToBind;
  28360. if (this._unIndexed) {
  28361. indexToBind = null;
  28362. }
  28363. else {
  28364. switch (fillMode) {
  28365. case BABYLON.Material.PointFillMode:
  28366. indexToBind = null;
  28367. break;
  28368. case BABYLON.Material.WireFrameFillMode:
  28369. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28370. break;
  28371. default:
  28372. case BABYLON.Material.TriangleFillMode:
  28373. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28374. break;
  28375. }
  28376. }
  28377. // VBOs
  28378. this._geometry._bind(effect, indexToBind);
  28379. return this;
  28380. };
  28381. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28382. if (alternate === void 0) { alternate = false; }
  28383. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28384. return this;
  28385. }
  28386. this.onBeforeDrawObservable.notifyObservers(this);
  28387. var scene = this.getScene();
  28388. var engine = scene.getEngine();
  28389. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28390. // or triangles as points
  28391. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28392. }
  28393. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28394. // Triangles as wireframe
  28395. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28396. }
  28397. else {
  28398. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28399. }
  28400. if (scene._isAlternateRenderingEnabled && !alternate) {
  28401. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28402. if (!effect || !scene.activeCamera) {
  28403. return this;
  28404. }
  28405. scene._switchToAlternateCameraConfiguration(true);
  28406. this._effectiveMaterial.bindView(effect);
  28407. this._effectiveMaterial.bindViewProjection(effect);
  28408. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28409. this._draw(subMesh, fillMode, instancesCount, true);
  28410. engine.setViewport(scene.activeCamera.viewport);
  28411. scene._switchToAlternateCameraConfiguration(false);
  28412. this._effectiveMaterial.bindView(effect);
  28413. this._effectiveMaterial.bindViewProjection(effect);
  28414. }
  28415. return this;
  28416. };
  28417. /**
  28418. * Registers for this mesh a javascript function called just before the rendering process.
  28419. * This function is passed the current mesh.
  28420. * Return the Mesh.
  28421. */
  28422. Mesh.prototype.registerBeforeRender = function (func) {
  28423. this.onBeforeRenderObservable.add(func);
  28424. return this;
  28425. };
  28426. /**
  28427. * Disposes a previously registered javascript function called before the rendering.
  28428. * This function is passed the current mesh.
  28429. * Returns the Mesh.
  28430. */
  28431. Mesh.prototype.unregisterBeforeRender = function (func) {
  28432. this.onBeforeRenderObservable.removeCallback(func);
  28433. return this;
  28434. };
  28435. /**
  28436. * Registers for this mesh a javascript function called just after the rendering is complete.
  28437. * This function is passed the current mesh.
  28438. * Returns the Mesh.
  28439. */
  28440. Mesh.prototype.registerAfterRender = function (func) {
  28441. this.onAfterRenderObservable.add(func);
  28442. return this;
  28443. };
  28444. /**
  28445. * Disposes a previously registered javascript function called after the rendering.
  28446. * This function is passed the current mesh.
  28447. * Return the Mesh.
  28448. */
  28449. Mesh.prototype.unregisterAfterRender = function (func) {
  28450. this.onAfterRenderObservable.removeCallback(func);
  28451. return this;
  28452. };
  28453. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28454. var scene = this.getScene();
  28455. this._batchCache.mustReturn = false;
  28456. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28457. this._batchCache.visibleInstances[subMeshId] = null;
  28458. if (this._visibleInstances) {
  28459. var currentRenderId = scene.getRenderId();
  28460. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28461. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28462. var selfRenderId = this._renderId;
  28463. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28464. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28465. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28466. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28467. }
  28468. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28469. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28470. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28471. this._batchCache.mustReturn = true;
  28472. return this._batchCache;
  28473. }
  28474. if (currentRenderId !== selfRenderId) {
  28475. this._batchCache.renderSelf[subMeshId] = false;
  28476. }
  28477. }
  28478. this._renderIdForInstances[subMeshId] = currentRenderId;
  28479. }
  28480. return this._batchCache;
  28481. };
  28482. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28483. var visibleInstances = batch.visibleInstances[subMesh._id];
  28484. if (!visibleInstances) {
  28485. return this;
  28486. }
  28487. var matricesCount = visibleInstances.length + 1;
  28488. var bufferSize = matricesCount * 16 * 4;
  28489. var currentInstancesBufferSize = this._instancesBufferSize;
  28490. var instancesBuffer = this._instancesBuffer;
  28491. while (this._instancesBufferSize < bufferSize) {
  28492. this._instancesBufferSize *= 2;
  28493. }
  28494. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28495. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28496. }
  28497. var offset = 0;
  28498. var instancesCount = 0;
  28499. var world = this.getWorldMatrix();
  28500. if (batch.renderSelf[subMesh._id]) {
  28501. world.copyToArray(this._instancesData, offset);
  28502. offset += 16;
  28503. instancesCount++;
  28504. }
  28505. if (visibleInstances) {
  28506. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28507. var instance = visibleInstances[instanceIndex];
  28508. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28509. offset += 16;
  28510. instancesCount++;
  28511. }
  28512. }
  28513. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28514. if (instancesBuffer) {
  28515. instancesBuffer.dispose();
  28516. }
  28517. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28518. this._instancesBuffer = instancesBuffer;
  28519. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28520. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28521. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28522. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28523. }
  28524. else {
  28525. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28526. }
  28527. this._bind(subMesh, effect, fillMode);
  28528. this._draw(subMesh, fillMode, instancesCount);
  28529. engine.unbindInstanceAttributes();
  28530. return this;
  28531. };
  28532. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28533. var scene = this.getScene();
  28534. var engine = scene.getEngine();
  28535. if (hardwareInstancedRendering) {
  28536. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28537. }
  28538. else {
  28539. if (batch.renderSelf[subMesh._id]) {
  28540. // Draw
  28541. if (onBeforeDraw) {
  28542. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28543. }
  28544. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28545. }
  28546. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28547. if (visibleInstancesForSubMesh) {
  28548. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28549. var instance = visibleInstancesForSubMesh[instanceIndex];
  28550. // World
  28551. var world = instance.getWorldMatrix();
  28552. if (onBeforeDraw) {
  28553. onBeforeDraw(true, world, effectiveMaterial);
  28554. }
  28555. // Draw
  28556. this._draw(subMesh, fillMode);
  28557. }
  28558. }
  28559. }
  28560. return this;
  28561. };
  28562. /**
  28563. * Triggers the draw call for the mesh.
  28564. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28565. * Returns the Mesh.
  28566. */
  28567. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28568. this.checkOcclusionQuery();
  28569. if (this._isOccluded) {
  28570. return this;
  28571. }
  28572. var scene = this.getScene();
  28573. // Managing instances
  28574. var batch = this._getInstancesRenderList(subMesh._id);
  28575. if (batch.mustReturn) {
  28576. return this;
  28577. }
  28578. // Checking geometry state
  28579. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28580. return this;
  28581. }
  28582. this.onBeforeRenderObservable.notifyObservers(this);
  28583. var engine = scene.getEngine();
  28584. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28585. // Material
  28586. var material = subMesh.getMaterial();
  28587. if (!material) {
  28588. return this;
  28589. }
  28590. this._effectiveMaterial = material;
  28591. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28592. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28593. return this;
  28594. }
  28595. }
  28596. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28597. return this;
  28598. }
  28599. // Alpha mode
  28600. if (enableAlphaMode) {
  28601. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28602. }
  28603. // Outline - step 1
  28604. var savedDepthWrite = engine.getDepthWrite();
  28605. if (this.renderOutline) {
  28606. engine.setDepthWrite(false);
  28607. scene.getOutlineRenderer().render(subMesh, batch);
  28608. engine.setDepthWrite(savedDepthWrite);
  28609. }
  28610. var effect;
  28611. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28612. effect = subMesh.effect;
  28613. }
  28614. else {
  28615. effect = this._effectiveMaterial.getEffect();
  28616. }
  28617. if (!effect) {
  28618. return this;
  28619. }
  28620. var sideOrientation = this.overrideMaterialSideOrientation;
  28621. if (sideOrientation == null) {
  28622. sideOrientation = this._effectiveMaterial.sideOrientation;
  28623. if (this._getWorldMatrixDeterminant() < 0) {
  28624. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28625. }
  28626. }
  28627. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28628. if (this._effectiveMaterial.forceDepthWrite) {
  28629. engine.setDepthWrite(true);
  28630. }
  28631. // Bind
  28632. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28633. if (!hardwareInstancedRendering) {
  28634. this._bind(subMesh, effect, fillMode);
  28635. }
  28636. var world = this.getWorldMatrix();
  28637. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28638. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28639. }
  28640. else {
  28641. this._effectiveMaterial.bind(world, this);
  28642. }
  28643. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28644. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28645. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28646. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28647. }
  28648. // Draw
  28649. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28650. // Unbind
  28651. this._effectiveMaterial.unbind();
  28652. // Outline - step 2
  28653. if (this.renderOutline && savedDepthWrite) {
  28654. engine.setDepthWrite(true);
  28655. engine.setColorWrite(false);
  28656. scene.getOutlineRenderer().render(subMesh, batch);
  28657. engine.setColorWrite(true);
  28658. }
  28659. // Overlay
  28660. if (this.renderOverlay) {
  28661. var currentMode = engine.getAlphaMode();
  28662. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28663. scene.getOutlineRenderer().render(subMesh, batch, true);
  28664. engine.setAlphaMode(currentMode);
  28665. }
  28666. this.onAfterRenderObservable.notifyObservers(this);
  28667. return this;
  28668. };
  28669. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28670. if (isInstance && effectiveMaterial) {
  28671. effectiveMaterial.bindOnlyWorldMatrix(world);
  28672. }
  28673. };
  28674. /**
  28675. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28676. */
  28677. Mesh.prototype.getEmittedParticleSystems = function () {
  28678. var results = new Array();
  28679. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28680. var particleSystem = this.getScene().particleSystems[index];
  28681. if (particleSystem.emitter === this) {
  28682. results.push(particleSystem);
  28683. }
  28684. }
  28685. return results;
  28686. };
  28687. /**
  28688. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28689. */
  28690. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28691. var results = new Array();
  28692. var descendants = this.getDescendants();
  28693. descendants.push(this);
  28694. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28695. var particleSystem = this.getScene().particleSystems[index];
  28696. var emitter = particleSystem.emitter;
  28697. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28698. results.push(particleSystem);
  28699. }
  28700. }
  28701. return results;
  28702. };
  28703. Mesh.prototype._checkDelayState = function () {
  28704. var scene = this.getScene();
  28705. if (this._geometry) {
  28706. this._geometry.load(scene);
  28707. }
  28708. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28709. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28710. this._queueLoad(scene);
  28711. }
  28712. return this;
  28713. };
  28714. Mesh.prototype._queueLoad = function (scene) {
  28715. var _this = this;
  28716. scene._addPendingData(this);
  28717. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28718. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28719. if (data instanceof ArrayBuffer) {
  28720. _this._delayLoadingFunction(data, _this);
  28721. }
  28722. else {
  28723. _this._delayLoadingFunction(JSON.parse(data), _this);
  28724. }
  28725. _this.instances.forEach(function (instance) {
  28726. instance._syncSubMeshes();
  28727. });
  28728. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28729. scene._removePendingData(_this);
  28730. }, function () { }, scene.database, getBinaryData);
  28731. return this;
  28732. };
  28733. /**
  28734. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28735. */
  28736. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28737. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28738. return false;
  28739. }
  28740. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28741. return false;
  28742. }
  28743. this._checkDelayState();
  28744. return true;
  28745. };
  28746. /**
  28747. * Sets the mesh material by the material or multiMaterial `id` property.
  28748. * The material `id` is a string identifying the material or the multiMaterial.
  28749. * This method returns the Mesh.
  28750. */
  28751. Mesh.prototype.setMaterialByID = function (id) {
  28752. var materials = this.getScene().materials;
  28753. var index;
  28754. for (index = materials.length - 1; index > -1; index--) {
  28755. if (materials[index].id === id) {
  28756. this.material = materials[index];
  28757. return this;
  28758. }
  28759. }
  28760. // Multi
  28761. var multiMaterials = this.getScene().multiMaterials;
  28762. for (index = multiMaterials.length - 1; index > -1; index--) {
  28763. if (multiMaterials[index].id === id) {
  28764. this.material = multiMaterials[index];
  28765. return this;
  28766. }
  28767. }
  28768. return this;
  28769. };
  28770. /**
  28771. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28772. */
  28773. Mesh.prototype.getAnimatables = function () {
  28774. var results = new Array();
  28775. if (this.material) {
  28776. results.push(this.material);
  28777. }
  28778. if (this.skeleton) {
  28779. results.push(this.skeleton);
  28780. }
  28781. return results;
  28782. };
  28783. /**
  28784. * Modifies the mesh geometry according to the passed transformation matrix.
  28785. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28786. * The mesh normals are modified accordingly the same transformation.
  28787. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28788. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28789. * Returns the Mesh.
  28790. */
  28791. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28792. // Position
  28793. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28794. return this;
  28795. }
  28796. var submeshes = this.subMeshes.splice(0);
  28797. this._resetPointsArrayCache();
  28798. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28799. var temp = new Array();
  28800. var index;
  28801. for (index = 0; index < data.length; index += 3) {
  28802. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28803. }
  28804. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28805. // Normals
  28806. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28807. return this;
  28808. }
  28809. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28810. temp = [];
  28811. for (index = 0; index < data.length; index += 3) {
  28812. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28813. }
  28814. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28815. // flip faces?
  28816. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28817. this.flipFaces();
  28818. }
  28819. // Restore submeshes
  28820. this.releaseSubMeshes();
  28821. this.subMeshes = submeshes;
  28822. return this;
  28823. };
  28824. /**
  28825. * Modifies the mesh geometry according to its own current World Matrix.
  28826. * The mesh World Matrix is then reset.
  28827. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28828. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28829. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28830. * Returns the Mesh.
  28831. */
  28832. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28833. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28834. this.scaling.copyFromFloats(1, 1, 1);
  28835. this.position.copyFromFloats(0, 0, 0);
  28836. this.rotation.copyFromFloats(0, 0, 0);
  28837. //only if quaternion is already set
  28838. if (this.rotationQuaternion) {
  28839. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28840. }
  28841. this._worldMatrix = BABYLON.Matrix.Identity();
  28842. return this;
  28843. };
  28844. Object.defineProperty(Mesh.prototype, "_positions", {
  28845. // Cache
  28846. get: function () {
  28847. if (this._geometry) {
  28848. return this._geometry._positions;
  28849. }
  28850. return null;
  28851. },
  28852. enumerable: true,
  28853. configurable: true
  28854. });
  28855. Mesh.prototype._resetPointsArrayCache = function () {
  28856. if (this._geometry) {
  28857. this._geometry._resetPointsArrayCache();
  28858. }
  28859. return this;
  28860. };
  28861. Mesh.prototype._generatePointsArray = function () {
  28862. if (this._geometry) {
  28863. return this._geometry._generatePointsArray();
  28864. }
  28865. return false;
  28866. };
  28867. /**
  28868. * Returns a new Mesh object generated from the current mesh properties.
  28869. * This method must not get confused with createInstance().
  28870. * The parameter `name` is a string, the name given to the new mesh.
  28871. * The optional parameter `newParent` can be any Node object (default `null`).
  28872. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28873. * 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.
  28874. */
  28875. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28876. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28877. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28878. };
  28879. /**
  28880. * Releases resources associated with this mesh.
  28881. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28882. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28883. */
  28884. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28885. var _this = this;
  28886. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28887. this.morphTargetManager = null;
  28888. if (this._geometry) {
  28889. this._geometry.releaseForMesh(this, true);
  28890. }
  28891. // Sources
  28892. var meshes = this.getScene().meshes;
  28893. meshes.forEach(function (abstractMesh) {
  28894. var mesh = abstractMesh;
  28895. if (mesh._source && mesh._source === _this) {
  28896. mesh._source = null;
  28897. }
  28898. });
  28899. this._source = null;
  28900. // Instances
  28901. if (this._instancesBuffer) {
  28902. this._instancesBuffer.dispose();
  28903. this._instancesBuffer = null;
  28904. }
  28905. while (this.instances.length) {
  28906. this.instances[0].dispose();
  28907. }
  28908. // Effect layers.
  28909. var effectLayers = this.getScene().effectLayers;
  28910. for (var i = 0; i < effectLayers.length; i++) {
  28911. var effectLayer = effectLayers[i];
  28912. if (effectLayer) {
  28913. effectLayer._disposeMesh(this);
  28914. }
  28915. }
  28916. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28917. };
  28918. /**
  28919. * Modifies the mesh geometry according to a displacement map.
  28920. * 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.
  28921. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28922. * This method returns nothing.
  28923. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28924. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28925. * 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.
  28926. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28927. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28928. *
  28929. * Returns the Mesh.
  28930. */
  28931. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28932. var _this = this;
  28933. var scene = this.getScene();
  28934. var onload = function (img) {
  28935. // Getting height map data
  28936. var canvas = document.createElement("canvas");
  28937. var context = canvas.getContext("2d");
  28938. var heightMapWidth = img.width;
  28939. var heightMapHeight = img.height;
  28940. canvas.width = heightMapWidth;
  28941. canvas.height = heightMapHeight;
  28942. context.drawImage(img, 0, 0);
  28943. // Create VertexData from map data
  28944. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28945. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28946. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28947. //execute success callback, if set
  28948. if (onSuccess) {
  28949. onSuccess(_this);
  28950. }
  28951. };
  28952. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28953. return this;
  28954. };
  28955. /**
  28956. * Modifies the mesh geometry according to a displacementMap buffer.
  28957. * 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.
  28958. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28959. * This method returns nothing.
  28960. * 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.
  28961. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28962. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28963. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28964. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28965. *
  28966. * Returns the Mesh.
  28967. */
  28968. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28969. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28970. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28971. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28972. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28973. return this;
  28974. }
  28975. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28976. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28977. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28978. var position = BABYLON.Vector3.Zero();
  28979. var normal = BABYLON.Vector3.Zero();
  28980. var uv = BABYLON.Vector2.Zero();
  28981. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28982. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28983. for (var index = 0; index < positions.length; index += 3) {
  28984. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28985. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28986. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28987. // Compute height
  28988. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28989. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28990. var pos = (u + v * heightMapWidth) * 4;
  28991. var r = buffer[pos] / 255.0;
  28992. var g = buffer[pos + 1] / 255.0;
  28993. var b = buffer[pos + 2] / 255.0;
  28994. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28995. normal.normalize();
  28996. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28997. position = position.add(normal);
  28998. position.toArray(positions, index);
  28999. }
  29000. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29001. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29002. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29003. return this;
  29004. };
  29005. /**
  29006. * Modify the mesh to get a flat shading rendering.
  29007. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29008. * This method returns the Mesh.
  29009. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29010. */
  29011. Mesh.prototype.convertToFlatShadedMesh = function () {
  29012. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29013. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29014. var kinds = this.getVerticesDataKinds();
  29015. var vbs = {};
  29016. var data = {};
  29017. var newdata = {};
  29018. var updatableNormals = false;
  29019. var kindIndex;
  29020. var kind;
  29021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29022. kind = kinds[kindIndex];
  29023. var vertexBuffer = this.getVertexBuffer(kind);
  29024. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29025. updatableNormals = vertexBuffer.isUpdatable();
  29026. kinds.splice(kindIndex, 1);
  29027. kindIndex--;
  29028. continue;
  29029. }
  29030. vbs[kind] = vertexBuffer;
  29031. data[kind] = vbs[kind].getData();
  29032. newdata[kind] = [];
  29033. }
  29034. // Save previous submeshes
  29035. var previousSubmeshes = this.subMeshes.slice(0);
  29036. var indices = this.getIndices();
  29037. var totalIndices = this.getTotalIndices();
  29038. // Generating unique vertices per face
  29039. var index;
  29040. for (index = 0; index < totalIndices; index++) {
  29041. var vertexIndex = indices[index];
  29042. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29043. kind = kinds[kindIndex];
  29044. var stride = vbs[kind].getStrideSize();
  29045. for (var offset = 0; offset < stride; offset++) {
  29046. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29047. }
  29048. }
  29049. }
  29050. // Updating faces & normal
  29051. var normals = [];
  29052. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29053. for (index = 0; index < totalIndices; index += 3) {
  29054. indices[index] = index;
  29055. indices[index + 1] = index + 1;
  29056. indices[index + 2] = index + 2;
  29057. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29058. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29059. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29060. var p1p2 = p1.subtract(p2);
  29061. var p3p2 = p3.subtract(p2);
  29062. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29063. // Store same normals for every vertex
  29064. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29065. normals.push(normal.x);
  29066. normals.push(normal.y);
  29067. normals.push(normal.z);
  29068. }
  29069. }
  29070. this.setIndices(indices);
  29071. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29072. // Updating vertex buffers
  29073. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29074. kind = kinds[kindIndex];
  29075. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29076. }
  29077. // Updating submeshes
  29078. this.releaseSubMeshes();
  29079. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29080. var previousOne = previousSubmeshes[submeshIndex];
  29081. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29082. }
  29083. this.synchronizeInstances();
  29084. return this;
  29085. };
  29086. /**
  29087. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29088. * In other words, more vertices, no more indices and a single bigger VBO.
  29089. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29090. * Returns the Mesh.
  29091. */
  29092. Mesh.prototype.convertToUnIndexedMesh = function () {
  29093. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29094. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29095. var kinds = this.getVerticesDataKinds();
  29096. var vbs = {};
  29097. var data = {};
  29098. var newdata = {};
  29099. var kindIndex;
  29100. var kind;
  29101. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29102. kind = kinds[kindIndex];
  29103. var vertexBuffer = this.getVertexBuffer(kind);
  29104. vbs[kind] = vertexBuffer;
  29105. data[kind] = vbs[kind].getData();
  29106. newdata[kind] = [];
  29107. }
  29108. // Save previous submeshes
  29109. var previousSubmeshes = this.subMeshes.slice(0);
  29110. var indices = this.getIndices();
  29111. var totalIndices = this.getTotalIndices();
  29112. // Generating unique vertices per face
  29113. var index;
  29114. for (index = 0; index < totalIndices; index++) {
  29115. var vertexIndex = indices[index];
  29116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29117. kind = kinds[kindIndex];
  29118. var stride = vbs[kind].getStrideSize();
  29119. for (var offset = 0; offset < stride; offset++) {
  29120. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29121. }
  29122. }
  29123. }
  29124. // Updating indices
  29125. for (index = 0; index < totalIndices; index += 3) {
  29126. indices[index] = index;
  29127. indices[index + 1] = index + 1;
  29128. indices[index + 2] = index + 2;
  29129. }
  29130. this.setIndices(indices);
  29131. // Updating vertex buffers
  29132. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29133. kind = kinds[kindIndex];
  29134. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29135. }
  29136. // Updating submeshes
  29137. this.releaseSubMeshes();
  29138. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29139. var previousOne = previousSubmeshes[submeshIndex];
  29140. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29141. }
  29142. this._unIndexed = true;
  29143. this.synchronizeInstances();
  29144. return this;
  29145. };
  29146. /**
  29147. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29148. * This method returns the Mesh.
  29149. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29150. */
  29151. Mesh.prototype.flipFaces = function (flipNormals) {
  29152. if (flipNormals === void 0) { flipNormals = false; }
  29153. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29154. var i;
  29155. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29156. for (i = 0; i < vertex_data.normals.length; i++) {
  29157. vertex_data.normals[i] *= -1;
  29158. }
  29159. }
  29160. if (vertex_data.indices) {
  29161. var temp;
  29162. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29163. // reassign indices
  29164. temp = vertex_data.indices[i + 1];
  29165. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29166. vertex_data.indices[i + 2] = temp;
  29167. }
  29168. }
  29169. vertex_data.applyToMesh(this);
  29170. return this;
  29171. };
  29172. // Instances
  29173. /**
  29174. * Creates a new InstancedMesh object from the mesh model.
  29175. * An instance shares the same properties and the same material than its model.
  29176. * Only these properties of each instance can then be set individually :
  29177. * - position
  29178. * - rotation
  29179. * - rotationQuaternion
  29180. * - setPivotMatrix
  29181. * - scaling
  29182. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29183. * Warning : this method is not supported for Line mesh and LineSystem
  29184. */
  29185. Mesh.prototype.createInstance = function (name) {
  29186. return new BABYLON.InstancedMesh(name, this);
  29187. };
  29188. /**
  29189. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29190. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29191. * This method returns the Mesh.
  29192. */
  29193. Mesh.prototype.synchronizeInstances = function () {
  29194. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29195. var instance = this.instances[instanceIndex];
  29196. instance._syncSubMeshes();
  29197. }
  29198. return this;
  29199. };
  29200. /**
  29201. * Simplify the mesh according to the given array of settings.
  29202. * Function will return immediately and will simplify async. It returns the Mesh.
  29203. * @param settings a collection of simplification settings.
  29204. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29205. * @param type the type of simplification to run.
  29206. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29207. */
  29208. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29209. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29210. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29211. this.getScene().simplificationQueue.addTask({
  29212. settings: settings,
  29213. parallelProcessing: parallelProcessing,
  29214. mesh: this,
  29215. simplificationType: simplificationType,
  29216. successCallback: successCallback
  29217. });
  29218. return this;
  29219. };
  29220. /**
  29221. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29222. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29223. * This should be used together with the simplification to avoid disappearing triangles.
  29224. * Returns the Mesh.
  29225. * @param successCallback an optional success callback to be called after the optimization finished.
  29226. */
  29227. Mesh.prototype.optimizeIndices = function (successCallback) {
  29228. var _this = this;
  29229. var indices = this.getIndices();
  29230. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29231. if (!positions || !indices) {
  29232. return this;
  29233. }
  29234. var vectorPositions = new Array();
  29235. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29236. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29237. }
  29238. var dupes = new Array();
  29239. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29240. var realPos = vectorPositions.length - 1 - iteration;
  29241. var testedPosition = vectorPositions[realPos];
  29242. for (var j = 0; j < realPos; ++j) {
  29243. var againstPosition = vectorPositions[j];
  29244. if (testedPosition.equals(againstPosition)) {
  29245. dupes[realPos] = j;
  29246. break;
  29247. }
  29248. }
  29249. }, function () {
  29250. for (var i = 0; i < indices.length; ++i) {
  29251. indices[i] = dupes[indices[i]] || indices[i];
  29252. }
  29253. //indices are now reordered
  29254. var originalSubMeshes = _this.subMeshes.slice(0);
  29255. _this.setIndices(indices);
  29256. _this.subMeshes = originalSubMeshes;
  29257. if (successCallback) {
  29258. successCallback(_this);
  29259. }
  29260. });
  29261. return this;
  29262. };
  29263. Mesh.prototype.serialize = function (serializationObject) {
  29264. serializationObject.name = this.name;
  29265. serializationObject.id = this.id;
  29266. serializationObject.type = this.getClassName();
  29267. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29268. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29269. }
  29270. serializationObject.position = this.position.asArray();
  29271. if (this.rotationQuaternion) {
  29272. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29273. }
  29274. else if (this.rotation) {
  29275. serializationObject.rotation = this.rotation.asArray();
  29276. }
  29277. serializationObject.scaling = this.scaling.asArray();
  29278. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29279. serializationObject.isEnabled = this.isEnabled(false);
  29280. serializationObject.isVisible = this.isVisible;
  29281. serializationObject.infiniteDistance = this.infiniteDistance;
  29282. serializationObject.pickable = this.isPickable;
  29283. serializationObject.receiveShadows = this.receiveShadows;
  29284. serializationObject.billboardMode = this.billboardMode;
  29285. serializationObject.visibility = this.visibility;
  29286. serializationObject.checkCollisions = this.checkCollisions;
  29287. serializationObject.isBlocker = this.isBlocker;
  29288. // Parent
  29289. if (this.parent) {
  29290. serializationObject.parentId = this.parent.id;
  29291. }
  29292. // Geometry
  29293. serializationObject.isUnIndexed = this.isUnIndexed;
  29294. var geometry = this._geometry;
  29295. if (geometry) {
  29296. var geometryId = geometry.id;
  29297. serializationObject.geometryId = geometryId;
  29298. // SubMeshes
  29299. serializationObject.subMeshes = [];
  29300. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29301. var subMesh = this.subMeshes[subIndex];
  29302. serializationObject.subMeshes.push({
  29303. materialIndex: subMesh.materialIndex,
  29304. verticesStart: subMesh.verticesStart,
  29305. verticesCount: subMesh.verticesCount,
  29306. indexStart: subMesh.indexStart,
  29307. indexCount: subMesh.indexCount
  29308. });
  29309. }
  29310. }
  29311. // Material
  29312. if (this.material) {
  29313. serializationObject.materialId = this.material.id;
  29314. }
  29315. else {
  29316. this.material = null;
  29317. }
  29318. // Morph targets
  29319. if (this.morphTargetManager) {
  29320. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29321. }
  29322. // Skeleton
  29323. if (this.skeleton) {
  29324. serializationObject.skeletonId = this.skeleton.id;
  29325. }
  29326. // Physics
  29327. //TODO implement correct serialization for physics impostors.
  29328. var impostor = this.getPhysicsImpostor();
  29329. if (impostor) {
  29330. serializationObject.physicsMass = impostor.getParam("mass");
  29331. serializationObject.physicsFriction = impostor.getParam("friction");
  29332. serializationObject.physicsRestitution = impostor.getParam("mass");
  29333. serializationObject.physicsImpostor = impostor.type;
  29334. }
  29335. // Metadata
  29336. if (this.metadata) {
  29337. serializationObject.metadata = this.metadata;
  29338. }
  29339. // Instances
  29340. serializationObject.instances = [];
  29341. for (var index = 0; index < this.instances.length; index++) {
  29342. var instance = this.instances[index];
  29343. var serializationInstance = {
  29344. name: instance.name,
  29345. id: instance.id,
  29346. position: instance.position.asArray(),
  29347. scaling: instance.scaling.asArray()
  29348. };
  29349. if (instance.rotationQuaternion) {
  29350. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29351. }
  29352. else if (instance.rotation) {
  29353. serializationInstance.rotation = instance.rotation.asArray();
  29354. }
  29355. serializationObject.instances.push(serializationInstance);
  29356. // Animations
  29357. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29358. serializationInstance.ranges = instance.serializeAnimationRanges();
  29359. }
  29360. //
  29361. // Animations
  29362. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29363. serializationObject.ranges = this.serializeAnimationRanges();
  29364. // Layer mask
  29365. serializationObject.layerMask = this.layerMask;
  29366. // Alpha
  29367. serializationObject.alphaIndex = this.alphaIndex;
  29368. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29369. // Overlay
  29370. serializationObject.overlayAlpha = this.overlayAlpha;
  29371. serializationObject.overlayColor = this.overlayColor.asArray();
  29372. serializationObject.renderOverlay = this.renderOverlay;
  29373. // Fog
  29374. serializationObject.applyFog = this.applyFog;
  29375. // Action Manager
  29376. if (this.actionManager) {
  29377. serializationObject.actions = this.actionManager.serialize(this.name);
  29378. }
  29379. };
  29380. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29381. if (!this.geometry) {
  29382. return;
  29383. }
  29384. this._markSubMeshesAsAttributesDirty();
  29385. var morphTargetManager = this._morphTargetManager;
  29386. if (morphTargetManager && morphTargetManager.vertexCount) {
  29387. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29388. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29389. this.morphTargetManager = null;
  29390. return;
  29391. }
  29392. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29393. var morphTarget = morphTargetManager.getActiveTarget(index);
  29394. var positions = morphTarget.getPositions();
  29395. if (!positions) {
  29396. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29397. return;
  29398. }
  29399. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29400. var normals = morphTarget.getNormals();
  29401. if (normals) {
  29402. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29403. }
  29404. var tangents = morphTarget.getTangents();
  29405. if (tangents) {
  29406. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29407. }
  29408. }
  29409. }
  29410. else {
  29411. var index = 0;
  29412. // Positions
  29413. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29414. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29415. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29416. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29417. }
  29418. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29419. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29420. }
  29421. index++;
  29422. }
  29423. }
  29424. };
  29425. // Statics
  29426. /**
  29427. * Returns a new Mesh object parsed from the source provided.
  29428. * The parameter `parsedMesh` is the source.
  29429. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29430. */
  29431. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29432. var mesh;
  29433. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29434. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29435. }
  29436. else {
  29437. mesh = new Mesh(parsedMesh.name, scene);
  29438. }
  29439. mesh.id = parsedMesh.id;
  29440. if (BABYLON.Tags) {
  29441. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29442. }
  29443. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29444. if (parsedMesh.metadata !== undefined) {
  29445. mesh.metadata = parsedMesh.metadata;
  29446. }
  29447. if (parsedMesh.rotationQuaternion) {
  29448. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29449. }
  29450. else if (parsedMesh.rotation) {
  29451. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29452. }
  29453. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29454. if (parsedMesh.localMatrix) {
  29455. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29456. }
  29457. else if (parsedMesh.pivotMatrix) {
  29458. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29459. }
  29460. mesh.setEnabled(parsedMesh.isEnabled);
  29461. mesh.isVisible = parsedMesh.isVisible;
  29462. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29463. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29464. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29465. if (parsedMesh.applyFog !== undefined) {
  29466. mesh.applyFog = parsedMesh.applyFog;
  29467. }
  29468. if (parsedMesh.pickable !== undefined) {
  29469. mesh.isPickable = parsedMesh.pickable;
  29470. }
  29471. if (parsedMesh.alphaIndex !== undefined) {
  29472. mesh.alphaIndex = parsedMesh.alphaIndex;
  29473. }
  29474. mesh.receiveShadows = parsedMesh.receiveShadows;
  29475. mesh.billboardMode = parsedMesh.billboardMode;
  29476. if (parsedMesh.visibility !== undefined) {
  29477. mesh.visibility = parsedMesh.visibility;
  29478. }
  29479. mesh.checkCollisions = parsedMesh.checkCollisions;
  29480. if (parsedMesh.isBlocker !== undefined) {
  29481. mesh.isBlocker = parsedMesh.isBlocker;
  29482. }
  29483. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29484. // freezeWorldMatrix
  29485. if (parsedMesh.freezeWorldMatrix) {
  29486. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29487. }
  29488. // Parent
  29489. if (parsedMesh.parentId) {
  29490. mesh._waitingParentId = parsedMesh.parentId;
  29491. }
  29492. // Actions
  29493. if (parsedMesh.actions !== undefined) {
  29494. mesh._waitingActions = parsedMesh.actions;
  29495. }
  29496. // Overlay
  29497. if (parsedMesh.overlayAlpha !== undefined) {
  29498. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29499. }
  29500. if (parsedMesh.overlayColor !== undefined) {
  29501. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29502. }
  29503. if (parsedMesh.renderOverlay !== undefined) {
  29504. mesh.renderOverlay = parsedMesh.renderOverlay;
  29505. }
  29506. // Geometry
  29507. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29508. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29509. if (parsedMesh.delayLoadingFile) {
  29510. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29511. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29512. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29513. if (parsedMesh._binaryInfo) {
  29514. mesh._binaryInfo = parsedMesh._binaryInfo;
  29515. }
  29516. mesh._delayInfo = [];
  29517. if (parsedMesh.hasUVs) {
  29518. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29519. }
  29520. if (parsedMesh.hasUVs2) {
  29521. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29522. }
  29523. if (parsedMesh.hasUVs3) {
  29524. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29525. }
  29526. if (parsedMesh.hasUVs4) {
  29527. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29528. }
  29529. if (parsedMesh.hasUVs5) {
  29530. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29531. }
  29532. if (parsedMesh.hasUVs6) {
  29533. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29534. }
  29535. if (parsedMesh.hasColors) {
  29536. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29537. }
  29538. if (parsedMesh.hasMatricesIndices) {
  29539. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29540. }
  29541. if (parsedMesh.hasMatricesWeights) {
  29542. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29543. }
  29544. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29545. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29546. mesh._checkDelayState();
  29547. }
  29548. }
  29549. else {
  29550. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29551. }
  29552. // Material
  29553. if (parsedMesh.materialId) {
  29554. mesh.setMaterialByID(parsedMesh.materialId);
  29555. }
  29556. else {
  29557. mesh.material = null;
  29558. }
  29559. // Morph targets
  29560. if (parsedMesh.morphTargetManagerId > -1) {
  29561. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29562. }
  29563. // Skeleton
  29564. if (parsedMesh.skeletonId > -1) {
  29565. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29566. if (parsedMesh.numBoneInfluencers) {
  29567. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29568. }
  29569. }
  29570. // Animations
  29571. if (parsedMesh.animations) {
  29572. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29573. var parsedAnimation = parsedMesh.animations[animationIndex];
  29574. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29575. }
  29576. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29577. }
  29578. if (parsedMesh.autoAnimate) {
  29579. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29580. }
  29581. // Layer Mask
  29582. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29583. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29584. }
  29585. else {
  29586. mesh.layerMask = 0x0FFFFFFF;
  29587. }
  29588. // Physics
  29589. if (parsedMesh.physicsImpostor) {
  29590. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29591. mass: parsedMesh.physicsMass,
  29592. friction: parsedMesh.physicsFriction,
  29593. restitution: parsedMesh.physicsRestitution
  29594. }, scene);
  29595. }
  29596. // Instances
  29597. if (parsedMesh.instances) {
  29598. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29599. var parsedInstance = parsedMesh.instances[index];
  29600. var instance = mesh.createInstance(parsedInstance.name);
  29601. if (parsedInstance.id) {
  29602. instance.id = parsedInstance.id;
  29603. }
  29604. if (BABYLON.Tags) {
  29605. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29606. }
  29607. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29608. if (parsedInstance.parentId) {
  29609. instance._waitingParentId = parsedInstance.parentId;
  29610. }
  29611. if (parsedInstance.rotationQuaternion) {
  29612. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29613. }
  29614. else if (parsedInstance.rotation) {
  29615. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29616. }
  29617. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29618. instance.checkCollisions = mesh.checkCollisions;
  29619. if (parsedMesh.animations) {
  29620. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29621. parsedAnimation = parsedMesh.animations[animationIndex];
  29622. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29623. }
  29624. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29625. }
  29626. }
  29627. }
  29628. return mesh;
  29629. };
  29630. /**
  29631. * Creates a ribbon mesh.
  29632. * Please consider using the same method from the MeshBuilder class instead.
  29633. * 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.
  29634. *
  29635. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29636. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29637. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29638. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29639. * 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.
  29640. * 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.
  29641. * 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
  29642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29645. */
  29646. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29647. if (closeArray === void 0) { closeArray = false; }
  29648. if (updatable === void 0) { updatable = false; }
  29649. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29650. pathArray: pathArray,
  29651. closeArray: closeArray,
  29652. closePath: closePath,
  29653. offset: offset,
  29654. updatable: updatable,
  29655. sideOrientation: sideOrientation,
  29656. instance: instance
  29657. }, scene);
  29658. };
  29659. /**
  29660. * Creates a plane polygonal mesh. By default, this is a disc.
  29661. * Please consider using the same method from the MeshBuilder class instead.
  29662. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29663. * 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.
  29664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29667. */
  29668. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29669. if (scene === void 0) { scene = null; }
  29670. var options = {
  29671. radius: radius,
  29672. tessellation: tessellation,
  29673. sideOrientation: sideOrientation,
  29674. updatable: updatable
  29675. };
  29676. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29677. };
  29678. /**
  29679. * Creates a box mesh.
  29680. * Please consider using the same method from the MeshBuilder class instead.
  29681. * The parameter `size` sets the size (float) of each box side (default 1).
  29682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29683. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29685. */
  29686. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29687. if (scene === void 0) { scene = null; }
  29688. var options = {
  29689. size: size,
  29690. sideOrientation: sideOrientation,
  29691. updatable: updatable
  29692. };
  29693. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29694. };
  29695. /**
  29696. * Creates a sphere mesh.
  29697. * Please consider using the same method from the MeshBuilder class instead.
  29698. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29699. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29700. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29701. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29703. */
  29704. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29705. var options = {
  29706. segments: segments,
  29707. diameterX: diameter,
  29708. diameterY: diameter,
  29709. diameterZ: diameter,
  29710. sideOrientation: sideOrientation,
  29711. updatable: updatable
  29712. };
  29713. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29714. };
  29715. /**
  29716. * Creates a cylinder or a cone mesh.
  29717. * Please consider using the same method from the MeshBuilder class instead.
  29718. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29719. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29720. * 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.
  29721. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29722. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29726. */
  29727. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29728. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29729. if (scene !== undefined) {
  29730. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29731. updatable = scene;
  29732. }
  29733. scene = subdivisions;
  29734. subdivisions = 1;
  29735. }
  29736. var options = {
  29737. height: height,
  29738. diameterTop: diameterTop,
  29739. diameterBottom: diameterBottom,
  29740. tessellation: tessellation,
  29741. subdivisions: subdivisions,
  29742. sideOrientation: sideOrientation,
  29743. updatable: updatable
  29744. };
  29745. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29746. };
  29747. // Torus (Code from SharpDX.org)
  29748. /**
  29749. * Creates a torus mesh.
  29750. * Please consider using the same method from the MeshBuilder class instead.
  29751. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29752. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29753. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29757. */
  29758. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29759. var options = {
  29760. diameter: diameter,
  29761. thickness: thickness,
  29762. tessellation: tessellation,
  29763. sideOrientation: sideOrientation,
  29764. updatable: updatable
  29765. };
  29766. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29767. };
  29768. /**
  29769. * Creates a torus knot mesh.
  29770. * Please consider using the same method from the MeshBuilder class instead.
  29771. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29772. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29773. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29774. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29778. */
  29779. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29780. var options = {
  29781. radius: radius,
  29782. tube: tube,
  29783. radialSegments: radialSegments,
  29784. tubularSegments: tubularSegments,
  29785. p: p,
  29786. q: q,
  29787. sideOrientation: sideOrientation,
  29788. updatable: updatable
  29789. };
  29790. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29791. };
  29792. /**
  29793. * Creates a line mesh.
  29794. * Please consider using the same method from the MeshBuilder class instead.
  29795. * 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.
  29796. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29797. * The parameter `points` is an array successive Vector3.
  29798. * 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
  29799. * When updating an instance, remember that only point positions can change, not the number of points.
  29800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29801. */
  29802. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29803. if (scene === void 0) { scene = null; }
  29804. if (updatable === void 0) { updatable = false; }
  29805. if (instance === void 0) { instance = null; }
  29806. var options = {
  29807. points: points,
  29808. updatable: updatable,
  29809. instance: instance
  29810. };
  29811. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29812. };
  29813. /**
  29814. * Creates a dashed line mesh.
  29815. * Please consider using the same method from the MeshBuilder class instead.
  29816. * 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.
  29817. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29818. * The parameter `points` is an array successive Vector3.
  29819. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29820. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29821. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29822. * 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
  29823. * When updating an instance, remember that only point positions can change, not the number of points.
  29824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29825. */
  29826. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29827. if (scene === void 0) { scene = null; }
  29828. var options = {
  29829. points: points,
  29830. dashSize: dashSize,
  29831. gapSize: gapSize,
  29832. dashNb: dashNb,
  29833. updatable: updatable,
  29834. instance: instance
  29835. };
  29836. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29837. };
  29838. /**
  29839. * Creates a polygon mesh.
  29840. * Please consider using the same method from the MeshBuilder class instead.
  29841. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29842. * 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.
  29843. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29845. * Remember you can only change the shape positions, not their number when updating a polygon.
  29846. */
  29847. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29848. var options = {
  29849. shape: shape,
  29850. holes: holes,
  29851. updatable: updatable,
  29852. sideOrientation: sideOrientation
  29853. };
  29854. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29855. };
  29856. /**
  29857. * Creates an extruded polygon mesh, with depth in the Y direction.
  29858. * Please consider using the same method from the MeshBuilder class instead.
  29859. */
  29860. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29861. var options = {
  29862. shape: shape,
  29863. holes: holes,
  29864. depth: depth,
  29865. updatable: updatable,
  29866. sideOrientation: sideOrientation
  29867. };
  29868. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29869. };
  29870. /**
  29871. * Creates an extruded shape mesh.
  29872. * 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.
  29873. * Please consider using the same method from the MeshBuilder class instead.
  29874. *
  29875. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29876. * 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
  29877. * extruded along the Z axis.
  29878. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29879. * 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.
  29880. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29881. * 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
  29882. * 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
  29883. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29887. */
  29888. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29889. if (scene === void 0) { scene = null; }
  29890. var options = {
  29891. shape: shape,
  29892. path: path,
  29893. scale: scale,
  29894. rotation: rotation,
  29895. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29896. sideOrientation: sideOrientation,
  29897. instance: instance,
  29898. updatable: updatable
  29899. };
  29900. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29901. };
  29902. /**
  29903. * Creates an custom extruded shape mesh.
  29904. * 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.
  29905. * Please consider using the same method from the MeshBuilder class instead.
  29906. *
  29907. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29908. * 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
  29909. * extruded along the Z axis.
  29910. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29911. * 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
  29912. * and the distance of this point from the begining of the path :
  29913. * ```javascript
  29914. * var rotationFunction = function(i, distance) {
  29915. * // do things
  29916. * return rotationValue; }
  29917. * ```
  29918. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29919. * 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
  29920. * and the distance of this point from the begining of the path :
  29921. * ```javascript
  29922. * var scaleFunction = function(i, distance) {
  29923. * // do things
  29924. * return scaleValue;}
  29925. * ```
  29926. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29927. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29928. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29929. * 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
  29930. * 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
  29931. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29935. */
  29936. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29937. var options = {
  29938. shape: shape,
  29939. path: path,
  29940. scaleFunction: scaleFunction,
  29941. rotationFunction: rotationFunction,
  29942. ribbonCloseArray: ribbonCloseArray,
  29943. ribbonClosePath: ribbonClosePath,
  29944. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29945. sideOrientation: sideOrientation,
  29946. instance: instance,
  29947. updatable: updatable
  29948. };
  29949. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29950. };
  29951. /**
  29952. * Creates lathe mesh.
  29953. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29954. * Please consider using the same method from the MeshBuilder class instead.
  29955. * 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
  29956. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29957. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29958. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29962. */
  29963. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29964. var options = {
  29965. shape: shape,
  29966. radius: radius,
  29967. tessellation: tessellation,
  29968. sideOrientation: sideOrientation,
  29969. updatable: updatable
  29970. };
  29971. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29972. };
  29973. /**
  29974. * Creates a plane mesh.
  29975. * Please consider using the same method from the MeshBuilder class instead.
  29976. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29980. */
  29981. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29982. var options = {
  29983. size: size,
  29984. width: size,
  29985. height: size,
  29986. sideOrientation: sideOrientation,
  29987. updatable: updatable
  29988. };
  29989. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29990. };
  29991. /**
  29992. * Creates a ground mesh.
  29993. * Please consider using the same method from the MeshBuilder class instead.
  29994. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29995. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29997. */
  29998. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29999. var options = {
  30000. width: width,
  30001. height: height,
  30002. subdivisions: subdivisions,
  30003. updatable: updatable
  30004. };
  30005. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30006. };
  30007. /**
  30008. * Creates a tiled ground mesh.
  30009. * Please consider using the same method from the MeshBuilder class instead.
  30010. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30011. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30012. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30013. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30014. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30015. * numbers of subdivisions on the ground width and height of each tile.
  30016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30017. */
  30018. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30019. var options = {
  30020. xmin: xmin,
  30021. zmin: zmin,
  30022. xmax: xmax,
  30023. zmax: zmax,
  30024. subdivisions: subdivisions,
  30025. precision: precision,
  30026. updatable: updatable
  30027. };
  30028. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30029. };
  30030. /**
  30031. * Creates a ground mesh from a height map.
  30032. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30033. * Please consider using the same method from the MeshBuilder class instead.
  30034. * The parameter `url` sets the URL of the height map image resource.
  30035. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30036. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30037. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30038. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30039. * 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).
  30040. * This function is passed the newly built mesh :
  30041. * ```javascript
  30042. * function(mesh) { // do things
  30043. * return; }
  30044. * ```
  30045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30046. */
  30047. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30048. var options = {
  30049. width: width,
  30050. height: height,
  30051. subdivisions: subdivisions,
  30052. minHeight: minHeight,
  30053. maxHeight: maxHeight,
  30054. updatable: updatable,
  30055. onReady: onReady
  30056. };
  30057. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30058. };
  30059. /**
  30060. * Creates a tube mesh.
  30061. * 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.
  30062. * Please consider using the same method from the MeshBuilder class instead.
  30063. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30064. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30065. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30066. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30067. * 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.
  30068. * It must return a radius value (positive float) :
  30069. * ```javascript
  30070. * var radiusFunction = function(i, distance) {
  30071. * // do things
  30072. * return radius; }
  30073. * ```
  30074. * 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
  30075. * 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
  30076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30077. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30078. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30079. */
  30080. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30081. var options = {
  30082. path: path,
  30083. radius: radius,
  30084. tessellation: tessellation,
  30085. radiusFunction: radiusFunction,
  30086. arc: 1,
  30087. cap: cap,
  30088. updatable: updatable,
  30089. sideOrientation: sideOrientation,
  30090. instance: instance
  30091. };
  30092. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30093. };
  30094. /**
  30095. * Creates a polyhedron mesh.
  30096. * Please consider using the same method from the MeshBuilder class instead.
  30097. * 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
  30098. * to choose the wanted type.
  30099. * The parameter `size` (positive float, default 1) sets the polygon size.
  30100. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30101. * 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`.
  30102. * 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
  30103. * 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)`).
  30104. * 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
  30105. * 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.
  30106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30109. */
  30110. Mesh.CreatePolyhedron = function (name, options, scene) {
  30111. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30112. };
  30113. /**
  30114. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30115. * Please consider using the same method from the MeshBuilder class instead.
  30116. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30117. * 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`).
  30118. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30119. * 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.
  30120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30123. */
  30124. Mesh.CreateIcoSphere = function (name, options, scene) {
  30125. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30126. };
  30127. /**
  30128. * Creates a decal mesh.
  30129. * Please consider using the same method from the MeshBuilder class instead.
  30130. * 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.
  30131. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30132. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30133. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30134. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30135. */
  30136. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30137. var options = {
  30138. position: position,
  30139. normal: normal,
  30140. size: size,
  30141. angle: angle
  30142. };
  30143. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30144. };
  30145. // Skeletons
  30146. /**
  30147. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30148. */
  30149. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30150. if (!this._sourcePositions) {
  30151. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30152. if (!source) {
  30153. return this._sourcePositions;
  30154. }
  30155. this._sourcePositions = new Float32Array(source);
  30156. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30157. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30158. }
  30159. }
  30160. return this._sourcePositions;
  30161. };
  30162. /**
  30163. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30164. */
  30165. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30166. if (!this._sourceNormals) {
  30167. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30168. if (!source) {
  30169. return this._sourceNormals;
  30170. }
  30171. this._sourceNormals = new Float32Array(source);
  30172. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30173. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30174. }
  30175. }
  30176. return this._sourceNormals;
  30177. };
  30178. /**
  30179. * Updates the vertex buffer by applying transformation from the bones.
  30180. * Returns the Mesh.
  30181. *
  30182. * @param {skeleton} skeleton to apply
  30183. */
  30184. Mesh.prototype.applySkeleton = function (skeleton) {
  30185. if (!this.geometry) {
  30186. return this;
  30187. }
  30188. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30189. return this;
  30190. }
  30191. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30193. return this;
  30194. }
  30195. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30196. return this;
  30197. }
  30198. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30199. return this;
  30200. }
  30201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30202. return this;
  30203. }
  30204. if (!this._sourcePositions) {
  30205. var submeshes = this.subMeshes.slice();
  30206. this.setPositionsForCPUSkinning();
  30207. this.subMeshes = submeshes;
  30208. }
  30209. if (!this._sourceNormals) {
  30210. this.setNormalsForCPUSkinning();
  30211. }
  30212. // positionsData checks for not being Float32Array will only pass at most once
  30213. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30214. if (!positionsData) {
  30215. return this;
  30216. }
  30217. if (!(positionsData instanceof Float32Array)) {
  30218. positionsData = new Float32Array(positionsData);
  30219. }
  30220. // normalsData checks for not being Float32Array will only pass at most once
  30221. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30222. if (!normalsData) {
  30223. return this;
  30224. }
  30225. if (!(normalsData instanceof Float32Array)) {
  30226. normalsData = new Float32Array(normalsData);
  30227. }
  30228. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30229. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30230. if (!matricesWeightsData || !matricesIndicesData) {
  30231. return this;
  30232. }
  30233. var needExtras = this.numBoneInfluencers > 4;
  30234. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30235. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30236. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30237. var tempVector3 = BABYLON.Vector3.Zero();
  30238. var finalMatrix = new BABYLON.Matrix();
  30239. var tempMatrix = new BABYLON.Matrix();
  30240. var matWeightIdx = 0;
  30241. var inf;
  30242. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30243. var weight;
  30244. for (inf = 0; inf < 4; inf++) {
  30245. weight = matricesWeightsData[matWeightIdx + inf];
  30246. if (weight > 0) {
  30247. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30248. finalMatrix.addToSelf(tempMatrix);
  30249. }
  30250. else
  30251. break;
  30252. }
  30253. if (needExtras) {
  30254. for (inf = 0; inf < 4; inf++) {
  30255. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30256. if (weight > 0) {
  30257. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30258. finalMatrix.addToSelf(tempMatrix);
  30259. }
  30260. else
  30261. break;
  30262. }
  30263. }
  30264. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30265. tempVector3.toArray(positionsData, index);
  30266. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30267. tempVector3.toArray(normalsData, index);
  30268. finalMatrix.reset();
  30269. }
  30270. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30271. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30272. return this;
  30273. };
  30274. // Tools
  30275. /**
  30276. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30277. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30278. */
  30279. Mesh.MinMax = function (meshes) {
  30280. var minVector = null;
  30281. var maxVector = null;
  30282. meshes.forEach(function (mesh, index, array) {
  30283. var boundingInfo = mesh.getBoundingInfo();
  30284. var boundingBox = boundingInfo.boundingBox;
  30285. if (!minVector || !maxVector) {
  30286. minVector = boundingBox.minimumWorld;
  30287. maxVector = boundingBox.maximumWorld;
  30288. }
  30289. else {
  30290. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30291. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30292. }
  30293. });
  30294. if (!minVector || !maxVector) {
  30295. return {
  30296. min: BABYLON.Vector3.Zero(),
  30297. max: BABYLON.Vector3.Zero()
  30298. };
  30299. }
  30300. return {
  30301. min: minVector,
  30302. max: maxVector
  30303. };
  30304. };
  30305. /**
  30306. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30307. */
  30308. Mesh.Center = function (meshesOrMinMaxVector) {
  30309. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30310. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30311. };
  30312. /**
  30313. * Merge the array of meshes into a single mesh for performance reasons.
  30314. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30315. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30316. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30317. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30318. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30319. */
  30320. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30321. if (disposeSource === void 0) { disposeSource = true; }
  30322. var index;
  30323. if (!allow32BitsIndices) {
  30324. var totalVertices = 0;
  30325. // Counting vertices
  30326. for (index = 0; index < meshes.length; index++) {
  30327. if (meshes[index]) {
  30328. totalVertices += meshes[index].getTotalVertices();
  30329. if (totalVertices > 65536) {
  30330. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30331. return null;
  30332. }
  30333. }
  30334. }
  30335. }
  30336. // Merge
  30337. var vertexData = null;
  30338. var otherVertexData;
  30339. var indiceArray = new Array();
  30340. var source = null;
  30341. for (index = 0; index < meshes.length; index++) {
  30342. if (meshes[index]) {
  30343. meshes[index].computeWorldMatrix(true);
  30344. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30345. otherVertexData.transform(meshes[index].getWorldMatrix());
  30346. if (vertexData) {
  30347. vertexData.merge(otherVertexData);
  30348. }
  30349. else {
  30350. vertexData = otherVertexData;
  30351. source = meshes[index];
  30352. }
  30353. if (subdivideWithSubMeshes) {
  30354. indiceArray.push(meshes[index].getTotalIndices());
  30355. }
  30356. }
  30357. }
  30358. source = source;
  30359. if (!meshSubclass) {
  30360. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30361. }
  30362. vertexData.applyToMesh(meshSubclass);
  30363. // Setting properties
  30364. meshSubclass.material = source.material;
  30365. meshSubclass.checkCollisions = source.checkCollisions;
  30366. // Cleaning
  30367. if (disposeSource) {
  30368. for (index = 0; index < meshes.length; index++) {
  30369. if (meshes[index]) {
  30370. meshes[index].dispose();
  30371. }
  30372. }
  30373. }
  30374. // Subdivide
  30375. if (subdivideWithSubMeshes) {
  30376. //-- Suppresions du submesh global
  30377. meshSubclass.releaseSubMeshes();
  30378. index = 0;
  30379. var offset = 0;
  30380. //-- aplique la subdivision en fonction du tableau d'indices
  30381. while (index < indiceArray.length) {
  30382. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30383. offset += indiceArray[index];
  30384. index++;
  30385. }
  30386. }
  30387. return meshSubclass;
  30388. };
  30389. // Consts
  30390. Mesh._FRONTSIDE = 0;
  30391. Mesh._BACKSIDE = 1;
  30392. Mesh._DOUBLESIDE = 2;
  30393. Mesh._DEFAULTSIDE = 0;
  30394. Mesh._NO_CAP = 0;
  30395. Mesh._CAP_START = 1;
  30396. Mesh._CAP_END = 2;
  30397. Mesh._CAP_ALL = 3;
  30398. return Mesh;
  30399. }(BABYLON.AbstractMesh));
  30400. BABYLON.Mesh = Mesh;
  30401. })(BABYLON || (BABYLON = {}));
  30402. //# sourceMappingURL=babylon.mesh.js.map
  30403. var BABYLON;
  30404. (function (BABYLON) {
  30405. var BaseSubMesh = /** @class */ (function () {
  30406. function BaseSubMesh() {
  30407. }
  30408. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30409. get: function () {
  30410. return this._materialEffect;
  30411. },
  30412. enumerable: true,
  30413. configurable: true
  30414. });
  30415. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30416. if (defines === void 0) { defines = null; }
  30417. if (this._materialEffect === effect) {
  30418. if (!effect) {
  30419. this._materialDefines = null;
  30420. }
  30421. return;
  30422. }
  30423. this._materialDefines = defines;
  30424. this._materialEffect = effect;
  30425. };
  30426. return BaseSubMesh;
  30427. }());
  30428. BABYLON.BaseSubMesh = BaseSubMesh;
  30429. var SubMesh = /** @class */ (function (_super) {
  30430. __extends(SubMesh, _super);
  30431. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30432. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30433. var _this = _super.call(this) || this;
  30434. _this.materialIndex = materialIndex;
  30435. _this.verticesStart = verticesStart;
  30436. _this.verticesCount = verticesCount;
  30437. _this.indexStart = indexStart;
  30438. _this.indexCount = indexCount;
  30439. _this._renderId = 0;
  30440. _this._mesh = mesh;
  30441. _this._renderingMesh = renderingMesh || mesh;
  30442. mesh.subMeshes.push(_this);
  30443. _this._trianglePlanes = [];
  30444. _this._id = mesh.subMeshes.length - 1;
  30445. if (createBoundingBox) {
  30446. _this.refreshBoundingInfo();
  30447. mesh.computeWorldMatrix(true);
  30448. }
  30449. return _this;
  30450. }
  30451. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30452. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30453. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30454. };
  30455. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30456. get: function () {
  30457. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30458. },
  30459. enumerable: true,
  30460. configurable: true
  30461. });
  30462. /**
  30463. * Returns the submesh BoudingInfo object.
  30464. */
  30465. SubMesh.prototype.getBoundingInfo = function () {
  30466. if (this.IsGlobal) {
  30467. return this._mesh.getBoundingInfo();
  30468. }
  30469. return this._boundingInfo;
  30470. };
  30471. /**
  30472. * Sets the submesh BoundingInfo.
  30473. * Return the SubMesh.
  30474. */
  30475. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30476. this._boundingInfo = boundingInfo;
  30477. return this;
  30478. };
  30479. /**
  30480. * Returns the mesh of the current submesh.
  30481. */
  30482. SubMesh.prototype.getMesh = function () {
  30483. return this._mesh;
  30484. };
  30485. /**
  30486. * Returns the rendering mesh of the submesh.
  30487. */
  30488. SubMesh.prototype.getRenderingMesh = function () {
  30489. return this._renderingMesh;
  30490. };
  30491. /**
  30492. * Returns the submesh material.
  30493. */
  30494. SubMesh.prototype.getMaterial = function () {
  30495. var rootMaterial = this._renderingMesh.material;
  30496. if (rootMaterial === null || rootMaterial === undefined) {
  30497. return this._mesh.getScene().defaultMaterial;
  30498. }
  30499. else if (rootMaterial.getSubMaterial) {
  30500. var multiMaterial = rootMaterial;
  30501. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30502. if (this._currentMaterial !== effectiveMaterial) {
  30503. this._currentMaterial = effectiveMaterial;
  30504. this._materialDefines = null;
  30505. }
  30506. return effectiveMaterial;
  30507. }
  30508. return rootMaterial;
  30509. };
  30510. // Methods
  30511. /**
  30512. * Sets a new updated BoundingInfo object to the submesh.
  30513. * Returns the SubMesh.
  30514. */
  30515. SubMesh.prototype.refreshBoundingInfo = function () {
  30516. this._lastColliderWorldVertices = null;
  30517. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30518. return this;
  30519. }
  30520. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30521. if (!data) {
  30522. this._boundingInfo = this._mesh.getBoundingInfo();
  30523. return this;
  30524. }
  30525. var indices = this._renderingMesh.getIndices();
  30526. var extend;
  30527. //is this the only submesh?
  30528. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30529. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30530. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30531. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30532. }
  30533. else {
  30534. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30535. }
  30536. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30537. return this;
  30538. };
  30539. SubMesh.prototype._checkCollision = function (collider) {
  30540. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30541. return boundingInfo._checkCollision(collider);
  30542. };
  30543. /**
  30544. * Updates the submesh BoundingInfo.
  30545. * Returns the Submesh.
  30546. */
  30547. SubMesh.prototype.updateBoundingInfo = function (world) {
  30548. var boundingInfo = this.getBoundingInfo();
  30549. if (!boundingInfo) {
  30550. this.refreshBoundingInfo();
  30551. boundingInfo = this.getBoundingInfo();
  30552. }
  30553. boundingInfo.update(world);
  30554. return this;
  30555. };
  30556. /**
  30557. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30558. * Boolean returned.
  30559. */
  30560. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30561. var boundingInfo = this.getBoundingInfo();
  30562. if (!boundingInfo) {
  30563. return false;
  30564. }
  30565. return boundingInfo.isInFrustum(frustumPlanes);
  30566. };
  30567. /**
  30568. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30569. * Boolean returned.
  30570. */
  30571. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30572. var boundingInfo = this.getBoundingInfo();
  30573. if (!boundingInfo) {
  30574. return false;
  30575. }
  30576. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30577. };
  30578. /**
  30579. * Renders the submesh.
  30580. * Returns it.
  30581. */
  30582. SubMesh.prototype.render = function (enableAlphaMode) {
  30583. this._renderingMesh.render(this, enableAlphaMode);
  30584. return this;
  30585. };
  30586. /**
  30587. * Returns a new Index Buffer.
  30588. * Type returned : WebGLBuffer.
  30589. */
  30590. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30591. if (!this._linesIndexBuffer) {
  30592. var linesIndices = [];
  30593. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30594. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30595. }
  30596. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30597. this.linesIndexCount = linesIndices.length;
  30598. }
  30599. return this._linesIndexBuffer;
  30600. };
  30601. /**
  30602. * True is the passed Ray intersects the submesh bounding box.
  30603. * Boolean returned.
  30604. */
  30605. SubMesh.prototype.canIntersects = function (ray) {
  30606. var boundingInfo = this.getBoundingInfo();
  30607. if (!boundingInfo) {
  30608. return false;
  30609. }
  30610. return ray.intersectsBox(boundingInfo.boundingBox);
  30611. };
  30612. /**
  30613. * Returns an object IntersectionInfo.
  30614. */
  30615. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30616. var intersectInfo = null;
  30617. // LineMesh first as it's also a Mesh...
  30618. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30619. var lineMesh = this._mesh;
  30620. // Line test
  30621. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30622. var p0 = positions[indices[index]];
  30623. var p1 = positions[indices[index + 1]];
  30624. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30625. if (length < 0) {
  30626. continue;
  30627. }
  30628. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30629. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30630. if (fastCheck) {
  30631. break;
  30632. }
  30633. }
  30634. }
  30635. }
  30636. else {
  30637. // Triangles test
  30638. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30639. var p0 = positions[indices[index]];
  30640. var p1 = positions[indices[index + 1]];
  30641. var p2 = positions[indices[index + 2]];
  30642. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30643. if (currentIntersectInfo) {
  30644. if (currentIntersectInfo.distance < 0) {
  30645. continue;
  30646. }
  30647. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30648. intersectInfo = currentIntersectInfo;
  30649. intersectInfo.faceId = index / 3;
  30650. if (fastCheck) {
  30651. break;
  30652. }
  30653. }
  30654. }
  30655. }
  30656. }
  30657. return intersectInfo;
  30658. };
  30659. SubMesh.prototype._rebuild = function () {
  30660. if (this._linesIndexBuffer) {
  30661. this._linesIndexBuffer = null;
  30662. }
  30663. };
  30664. // Clone
  30665. /**
  30666. * Creates a new Submesh from the passed Mesh.
  30667. */
  30668. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30669. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30670. if (!this.IsGlobal) {
  30671. var boundingInfo = this.getBoundingInfo();
  30672. if (!boundingInfo) {
  30673. return result;
  30674. }
  30675. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30676. }
  30677. return result;
  30678. };
  30679. // Dispose
  30680. /**
  30681. * Disposes the Submesh.
  30682. * Returns nothing.
  30683. */
  30684. SubMesh.prototype.dispose = function () {
  30685. if (this._linesIndexBuffer) {
  30686. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30687. this._linesIndexBuffer = null;
  30688. }
  30689. // Remove from mesh
  30690. var index = this._mesh.subMeshes.indexOf(this);
  30691. this._mesh.subMeshes.splice(index, 1);
  30692. };
  30693. // Statics
  30694. /**
  30695. * Creates a new Submesh from the passed parameters :
  30696. * - materialIndex (integer) : the index of the main mesh material.
  30697. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30698. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30699. * - mesh (Mesh) : the main mesh to create the submesh from.
  30700. * - renderingMesh (optional Mesh) : rendering mesh.
  30701. */
  30702. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30703. var minVertexIndex = Number.MAX_VALUE;
  30704. var maxVertexIndex = -Number.MAX_VALUE;
  30705. renderingMesh = (renderingMesh || mesh);
  30706. var indices = renderingMesh.getIndices();
  30707. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30708. var vertexIndex = indices[index];
  30709. if (vertexIndex < minVertexIndex)
  30710. minVertexIndex = vertexIndex;
  30711. if (vertexIndex > maxVertexIndex)
  30712. maxVertexIndex = vertexIndex;
  30713. }
  30714. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30715. };
  30716. return SubMesh;
  30717. }(BaseSubMesh));
  30718. BABYLON.SubMesh = SubMesh;
  30719. })(BABYLON || (BABYLON = {}));
  30720. //# sourceMappingURL=babylon.subMesh.js.map
  30721. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30722. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30723. s = arguments[i];
  30724. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30725. t[p] = s[p];
  30726. }
  30727. return t;
  30728. };
  30729. var BABYLON;
  30730. (function (BABYLON) {
  30731. /**
  30732. * Manages the defines for the Material.
  30733. */
  30734. var MaterialDefines = /** @class */ (function () {
  30735. function MaterialDefines() {
  30736. this._isDirty = true;
  30737. this._areLightsDirty = true;
  30738. this._areAttributesDirty = true;
  30739. this._areTexturesDirty = true;
  30740. this._areFresnelDirty = true;
  30741. this._areMiscDirty = true;
  30742. this._areImageProcessingDirty = true;
  30743. this._normals = false;
  30744. this._uvs = false;
  30745. this._needNormals = false;
  30746. this._needUVs = false;
  30747. }
  30748. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30749. /**
  30750. * Specifies if the material needs to be re-calculated.
  30751. */
  30752. get: function () {
  30753. return this._isDirty;
  30754. },
  30755. enumerable: true,
  30756. configurable: true
  30757. });
  30758. /**
  30759. * Marks the material to indicate that it has been re-calculated.
  30760. */
  30761. MaterialDefines.prototype.markAsProcessed = function () {
  30762. this._isDirty = false;
  30763. this._areAttributesDirty = false;
  30764. this._areTexturesDirty = false;
  30765. this._areFresnelDirty = false;
  30766. this._areLightsDirty = false;
  30767. this._areMiscDirty = false;
  30768. this._areImageProcessingDirty = false;
  30769. };
  30770. /**
  30771. * Marks the material to indicate that it needs to be re-calculated.
  30772. */
  30773. MaterialDefines.prototype.markAsUnprocessed = function () {
  30774. this._isDirty = true;
  30775. };
  30776. /**
  30777. * Marks the material to indicate all of its defines need to be re-calculated.
  30778. */
  30779. MaterialDefines.prototype.markAllAsDirty = function () {
  30780. this._areTexturesDirty = true;
  30781. this._areAttributesDirty = true;
  30782. this._areLightsDirty = true;
  30783. this._areFresnelDirty = true;
  30784. this._areMiscDirty = true;
  30785. this._areImageProcessingDirty = true;
  30786. this._isDirty = true;
  30787. };
  30788. /**
  30789. * Marks the material to indicate that image processing needs to be re-calculated.
  30790. */
  30791. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30792. this._areImageProcessingDirty = true;
  30793. this._isDirty = true;
  30794. };
  30795. /**
  30796. * Marks the material to indicate the lights need to be re-calculated.
  30797. */
  30798. MaterialDefines.prototype.markAsLightDirty = function () {
  30799. this._areLightsDirty = true;
  30800. this._isDirty = true;
  30801. };
  30802. /**
  30803. * Marks the attribute state as changed.
  30804. */
  30805. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30806. this._areAttributesDirty = true;
  30807. this._isDirty = true;
  30808. };
  30809. /**
  30810. * Marks the texture state as changed.
  30811. */
  30812. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30813. this._areTexturesDirty = true;
  30814. this._isDirty = true;
  30815. };
  30816. /**
  30817. * Marks the fresnel state as changed.
  30818. */
  30819. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30820. this._areFresnelDirty = true;
  30821. this._isDirty = true;
  30822. };
  30823. /**
  30824. * Marks the misc state as changed.
  30825. */
  30826. MaterialDefines.prototype.markAsMiscDirty = function () {
  30827. this._areMiscDirty = true;
  30828. this._isDirty = true;
  30829. };
  30830. /**
  30831. * Rebuilds the material defines.
  30832. */
  30833. MaterialDefines.prototype.rebuild = function () {
  30834. if (this._keys) {
  30835. delete this._keys;
  30836. }
  30837. this._keys = [];
  30838. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30839. var key = _a[_i];
  30840. if (key[0] === "_") {
  30841. continue;
  30842. }
  30843. this._keys.push(key);
  30844. }
  30845. };
  30846. /**
  30847. * Specifies if two material defines are equal.
  30848. * @param other - A material define instance to compare to.
  30849. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30850. */
  30851. MaterialDefines.prototype.isEqual = function (other) {
  30852. if (this._keys.length !== other._keys.length) {
  30853. return false;
  30854. }
  30855. for (var index = 0; index < this._keys.length; index++) {
  30856. var prop = this._keys[index];
  30857. if (this[prop] !== other[prop]) {
  30858. return false;
  30859. }
  30860. }
  30861. return true;
  30862. };
  30863. /**
  30864. * Clones this instance's defines to another instance.
  30865. * @param other - material defines to clone values to.
  30866. */
  30867. MaterialDefines.prototype.cloneTo = function (other) {
  30868. if (this._keys.length !== other._keys.length) {
  30869. other._keys = this._keys.slice(0);
  30870. }
  30871. for (var index = 0; index < this._keys.length; index++) {
  30872. var prop = this._keys[index];
  30873. other[prop] = this[prop];
  30874. }
  30875. };
  30876. /**
  30877. * Resets the material define values.
  30878. */
  30879. MaterialDefines.prototype.reset = function () {
  30880. for (var index = 0; index < this._keys.length; index++) {
  30881. var prop = this._keys[index];
  30882. if (typeof (this[prop]) === "number") {
  30883. this[prop] = 0;
  30884. }
  30885. else {
  30886. this[prop] = false;
  30887. }
  30888. }
  30889. };
  30890. /**
  30891. * Converts the material define values to a string.
  30892. * @returns - String of material define information.
  30893. */
  30894. MaterialDefines.prototype.toString = function () {
  30895. var result = "";
  30896. for (var index = 0; index < this._keys.length; index++) {
  30897. var prop = this._keys[index];
  30898. var value = this[prop];
  30899. if (typeof (value) === "number") {
  30900. result += "#define " + prop + " " + this[prop] + "\n";
  30901. }
  30902. else if (value) {
  30903. result += "#define " + prop + "\n";
  30904. }
  30905. }
  30906. return result;
  30907. };
  30908. return MaterialDefines;
  30909. }());
  30910. BABYLON.MaterialDefines = MaterialDefines;
  30911. /**
  30912. * This offers the main features of a material in BJS.
  30913. */
  30914. var Material = /** @class */ (function () {
  30915. /**
  30916. * Creates a material instance.
  30917. * @param name - The name of the material.
  30918. * @param scene - The BJS scene to reference.
  30919. * @param doNotAdd - Specifies if the material should be added to the scene.
  30920. */
  30921. function Material(name, scene, doNotAdd) {
  30922. /**
  30923. * Specifies if the ready state should be checked on each call.
  30924. */
  30925. this.checkReadyOnEveryCall = false;
  30926. /**
  30927. * Specifies if the ready state should be checked once.
  30928. */
  30929. this.checkReadyOnlyOnce = false;
  30930. /**
  30931. * The state of the material.
  30932. */
  30933. this.state = "";
  30934. /**
  30935. * The alpha value of the material.
  30936. */
  30937. this._alpha = 1.0;
  30938. /**
  30939. * Specifies if back face culling is enabled.
  30940. */
  30941. this._backFaceCulling = true;
  30942. /**
  30943. * Specifies if the material should be serialized.
  30944. */
  30945. this.doNotSerialize = false;
  30946. /**
  30947. * Specifies if the effect should be stored on sub meshes.
  30948. */
  30949. this.storeEffectOnSubMeshes = false;
  30950. /**
  30951. * An event triggered when the material is disposed.
  30952. * @type {BABYLON.Observable}
  30953. */
  30954. this.onDisposeObservable = new BABYLON.Observable();
  30955. /**
  30956. * An event triggered when the material is bound.
  30957. * @type {BABYLON.Observable}
  30958. */
  30959. this.onBindObservable = new BABYLON.Observable();
  30960. /**
  30961. * An event triggered when the material is unbound.
  30962. * @type {BABYLON.Observable}
  30963. */
  30964. this.onUnBindObservable = new BABYLON.Observable();
  30965. /**
  30966. * Stores the value of the alpha mode.
  30967. */
  30968. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30969. /**
  30970. * Stores the state of the need depth pre-pass value.
  30971. */
  30972. this._needDepthPrePass = false;
  30973. /**
  30974. * Specifies if depth writing should be disabled.
  30975. */
  30976. this.disableDepthWrite = false;
  30977. /**
  30978. * Specifies if depth writing should be forced.
  30979. */
  30980. this.forceDepthWrite = false;
  30981. /**
  30982. * Specifies if there should be a separate pass for culling.
  30983. */
  30984. this.separateCullingPass = false;
  30985. /**
  30986. * Stores the state specifing if fog should be enabled.
  30987. */
  30988. this._fogEnabled = true;
  30989. /**
  30990. * Stores the size of points.
  30991. */
  30992. this.pointSize = 1.0;
  30993. /**
  30994. * Stores the z offset value.
  30995. */
  30996. this.zOffset = 0;
  30997. /**
  30998. * Specifies if the material was previously ready.
  30999. */
  31000. this._wasPreviouslyReady = false;
  31001. /**
  31002. * Stores the fill mode state.
  31003. */
  31004. this._fillMode = Material.TriangleFillMode;
  31005. this.name = name;
  31006. this.id = name || BABYLON.Tools.RandomId();
  31007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31008. if (this._scene.useRightHandedSystem) {
  31009. this.sideOrientation = Material.ClockWiseSideOrientation;
  31010. }
  31011. else {
  31012. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31013. }
  31014. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31015. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31016. if (!doNotAdd) {
  31017. this._scene.materials.push(this);
  31018. }
  31019. }
  31020. Object.defineProperty(Material, "TriangleFillMode", {
  31021. /**
  31022. * Returns the triangle fill mode.
  31023. */
  31024. get: function () {
  31025. return Material._TriangleFillMode;
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Material, "WireFrameFillMode", {
  31031. /**
  31032. * Returns the wireframe mode.
  31033. */
  31034. get: function () {
  31035. return Material._WireFrameFillMode;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Material, "PointFillMode", {
  31041. /**
  31042. * Returns the point fill mode.
  31043. */
  31044. get: function () {
  31045. return Material._PointFillMode;
  31046. },
  31047. enumerable: true,
  31048. configurable: true
  31049. });
  31050. Object.defineProperty(Material, "PointListDrawMode", {
  31051. /**
  31052. * Returns the point list draw mode.
  31053. */
  31054. get: function () {
  31055. return Material._PointListDrawMode;
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(Material, "LineListDrawMode", {
  31061. /**
  31062. * Returns the line list draw mode.
  31063. */
  31064. get: function () {
  31065. return Material._LineListDrawMode;
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(Material, "LineLoopDrawMode", {
  31071. /**
  31072. * Returns the line loop draw mode.
  31073. */
  31074. get: function () {
  31075. return Material._LineLoopDrawMode;
  31076. },
  31077. enumerable: true,
  31078. configurable: true
  31079. });
  31080. Object.defineProperty(Material, "LineStripDrawMode", {
  31081. /**
  31082. * Returns the line strip draw mode.
  31083. */
  31084. get: function () {
  31085. return Material._LineStripDrawMode;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31091. /**
  31092. * Returns the triangle strip draw mode.
  31093. */
  31094. get: function () {
  31095. return Material._TriangleStripDrawMode;
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31101. /**
  31102. * Returns the triangle fan draw mode.
  31103. */
  31104. get: function () {
  31105. return Material._TriangleFanDrawMode;
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31111. /**
  31112. * Returns the clock-wise side orientation.
  31113. */
  31114. get: function () {
  31115. return Material._ClockWiseSideOrientation;
  31116. },
  31117. enumerable: true,
  31118. configurable: true
  31119. });
  31120. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31121. /**
  31122. * Returns the counter clock-wise side orientation.
  31123. */
  31124. get: function () {
  31125. return Material._CounterClockWiseSideOrientation;
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(Material, "TextureDirtyFlag", {
  31131. /**
  31132. * Returns the dirty texture flag value.
  31133. */
  31134. get: function () {
  31135. return Material._TextureDirtyFlag;
  31136. },
  31137. enumerable: true,
  31138. configurable: true
  31139. });
  31140. Object.defineProperty(Material, "LightDirtyFlag", {
  31141. /**
  31142. * Returns the dirty light flag value.
  31143. */
  31144. get: function () {
  31145. return Material._LightDirtyFlag;
  31146. },
  31147. enumerable: true,
  31148. configurable: true
  31149. });
  31150. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31151. /**
  31152. * Returns the dirty fresnel flag value.
  31153. */
  31154. get: function () {
  31155. return Material._FresnelDirtyFlag;
  31156. },
  31157. enumerable: true,
  31158. configurable: true
  31159. });
  31160. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31161. /**
  31162. * Returns the dirty attributes flag value.
  31163. */
  31164. get: function () {
  31165. return Material._AttributesDirtyFlag;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Object.defineProperty(Material, "MiscDirtyFlag", {
  31171. /**
  31172. * Returns the dirty misc flag value.
  31173. */
  31174. get: function () {
  31175. return Material._MiscDirtyFlag;
  31176. },
  31177. enumerable: true,
  31178. configurable: true
  31179. });
  31180. Object.defineProperty(Material.prototype, "alpha", {
  31181. /**
  31182. * Gets the alpha value of the material.
  31183. */
  31184. get: function () {
  31185. return this._alpha;
  31186. },
  31187. /**
  31188. * Sets the alpha value of the material.
  31189. */
  31190. set: function (value) {
  31191. if (this._alpha === value) {
  31192. return;
  31193. }
  31194. this._alpha = value;
  31195. this.markAsDirty(Material.MiscDirtyFlag);
  31196. },
  31197. enumerable: true,
  31198. configurable: true
  31199. });
  31200. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31201. /**
  31202. * Gets the back-face culling state.
  31203. */
  31204. get: function () {
  31205. return this._backFaceCulling;
  31206. },
  31207. /**
  31208. * Sets the back-face culling state.
  31209. */
  31210. set: function (value) {
  31211. if (this._backFaceCulling === value) {
  31212. return;
  31213. }
  31214. this._backFaceCulling = value;
  31215. this.markAsDirty(Material.TextureDirtyFlag);
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. Object.defineProperty(Material.prototype, "onDispose", {
  31221. /**
  31222. * Called during a dispose event.
  31223. */
  31224. set: function (callback) {
  31225. if (this._onDisposeObserver) {
  31226. this.onDisposeObservable.remove(this._onDisposeObserver);
  31227. }
  31228. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31229. },
  31230. enumerable: true,
  31231. configurable: true
  31232. });
  31233. Object.defineProperty(Material.prototype, "onBind", {
  31234. /**
  31235. * Called during a bind event.
  31236. */
  31237. set: function (callback) {
  31238. if (this._onBindObserver) {
  31239. this.onBindObservable.remove(this._onBindObserver);
  31240. }
  31241. this._onBindObserver = this.onBindObservable.add(callback);
  31242. },
  31243. enumerable: true,
  31244. configurable: true
  31245. });
  31246. Object.defineProperty(Material.prototype, "alphaMode", {
  31247. /**
  31248. * Gets the value of the alpha mode.
  31249. */
  31250. get: function () {
  31251. return this._alphaMode;
  31252. },
  31253. /**
  31254. * Sets the value of the alpha mode.
  31255. */
  31256. set: function (value) {
  31257. if (this._alphaMode === value) {
  31258. return;
  31259. }
  31260. this._alphaMode = value;
  31261. this.markAsDirty(Material.TextureDirtyFlag);
  31262. },
  31263. enumerable: true,
  31264. configurable: true
  31265. });
  31266. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31267. /**
  31268. * Gets the depth pre-pass value.
  31269. */
  31270. get: function () {
  31271. return this._needDepthPrePass;
  31272. },
  31273. /**
  31274. * Sets the need depth pre-pass value.
  31275. */
  31276. set: function (value) {
  31277. if (this._needDepthPrePass === value) {
  31278. return;
  31279. }
  31280. this._needDepthPrePass = value;
  31281. if (this._needDepthPrePass) {
  31282. this.checkReadyOnEveryCall = true;
  31283. }
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(Material.prototype, "fogEnabled", {
  31289. /**
  31290. * Gets the value of the fog enabled state.
  31291. */
  31292. get: function () {
  31293. return this._fogEnabled;
  31294. },
  31295. /**
  31296. * Sets the state for enabling fog.
  31297. */
  31298. set: function (value) {
  31299. if (this._fogEnabled === value) {
  31300. return;
  31301. }
  31302. this._fogEnabled = value;
  31303. this.markAsDirty(Material.MiscDirtyFlag);
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. Object.defineProperty(Material.prototype, "wireframe", {
  31309. /**
  31310. * Gets a value specifying if wireframe mode is enabled.
  31311. */
  31312. get: function () {
  31313. return this._fillMode === Material.WireFrameFillMode;
  31314. },
  31315. /**
  31316. * Sets the state of wireframe mode.
  31317. */
  31318. set: function (value) {
  31319. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. Object.defineProperty(Material.prototype, "pointsCloud", {
  31325. /**
  31326. * Gets the value specifying if point clouds are enabled.
  31327. */
  31328. get: function () {
  31329. return this._fillMode === Material.PointFillMode;
  31330. },
  31331. /**
  31332. * Sets the state of point cloud mode.
  31333. */
  31334. set: function (value) {
  31335. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31336. },
  31337. enumerable: true,
  31338. configurable: true
  31339. });
  31340. Object.defineProperty(Material.prototype, "fillMode", {
  31341. /**
  31342. * Gets the material fill mode.
  31343. */
  31344. get: function () {
  31345. return this._fillMode;
  31346. },
  31347. /**
  31348. * Sets the material fill mode.
  31349. */
  31350. set: function (value) {
  31351. if (this._fillMode === value) {
  31352. return;
  31353. }
  31354. this._fillMode = value;
  31355. this.markAsDirty(Material.MiscDirtyFlag);
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. /**
  31361. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31362. * subclasses should override adding information pertainent to themselves.
  31363. * @returns - String with material information.
  31364. */
  31365. Material.prototype.toString = function (fullDetails) {
  31366. var ret = "Name: " + this.name;
  31367. if (fullDetails) {
  31368. }
  31369. return ret;
  31370. };
  31371. /**
  31372. * Gets the class name of the material.
  31373. * @returns - String with the class name of the material.
  31374. */
  31375. Material.prototype.getClassName = function () {
  31376. return "Material";
  31377. };
  31378. Object.defineProperty(Material.prototype, "isFrozen", {
  31379. /**
  31380. * Specifies if updates for the material been locked.
  31381. */
  31382. get: function () {
  31383. return this.checkReadyOnlyOnce;
  31384. },
  31385. enumerable: true,
  31386. configurable: true
  31387. });
  31388. /**
  31389. * Locks updates for the material.
  31390. */
  31391. Material.prototype.freeze = function () {
  31392. this.checkReadyOnlyOnce = true;
  31393. };
  31394. /**
  31395. * Unlocks updates for the material.
  31396. */
  31397. Material.prototype.unfreeze = function () {
  31398. this.checkReadyOnlyOnce = false;
  31399. };
  31400. /**
  31401. * Specifies if the material is ready to be used.
  31402. * @param mesh - BJS mesh.
  31403. * @param useInstances - Specifies if instances should be used.
  31404. * @returns - Boolean indicating if the material is ready to be used.
  31405. */
  31406. Material.prototype.isReady = function (mesh, useInstances) {
  31407. return true;
  31408. };
  31409. /**
  31410. * Specifies that the submesh is ready to be used.
  31411. * @param mesh - BJS mesh.
  31412. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31413. * @param useInstances - Specifies that instances should be used.
  31414. * @returns - boolean indicating that the submesh is ready or not.
  31415. */
  31416. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31417. return false;
  31418. };
  31419. /**
  31420. * Returns the material effect.
  31421. * @returns - Nullable material effect.
  31422. */
  31423. Material.prototype.getEffect = function () {
  31424. return this._effect;
  31425. };
  31426. /**
  31427. * Returns the BJS scene.
  31428. * @returns - BJS Scene.
  31429. */
  31430. Material.prototype.getScene = function () {
  31431. return this._scene;
  31432. };
  31433. /**
  31434. * Specifies if the material will require alpha blending
  31435. * @returns - Boolean specifying if alpha blending is needed.
  31436. */
  31437. Material.prototype.needAlphaBlending = function () {
  31438. return (this.alpha < 1.0);
  31439. };
  31440. /**
  31441. * Specifies if the mesh will require alpha blending.
  31442. * @param mesh - BJS mesh.
  31443. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31444. */
  31445. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31446. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31447. };
  31448. /**
  31449. * Specifies if this material should be rendered in alpha test mode.
  31450. * @returns - Boolean specifying if an alpha test is needed.
  31451. */
  31452. Material.prototype.needAlphaTesting = function () {
  31453. return false;
  31454. };
  31455. /**
  31456. * Gets the texture used for the alpha test.
  31457. * @returns - Nullable alpha test texture.
  31458. */
  31459. Material.prototype.getAlphaTestTexture = function () {
  31460. return null;
  31461. };
  31462. /**
  31463. * Marks the material to indicate that it needs to be re-calculated.
  31464. */
  31465. Material.prototype.markDirty = function () {
  31466. this._wasPreviouslyReady = false;
  31467. };
  31468. Material.prototype._preBind = function (effect, overrideOrientation) {
  31469. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31470. var engine = this._scene.getEngine();
  31471. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31472. var reverse = orientation === Material.ClockWiseSideOrientation;
  31473. engine.enableEffect(effect ? effect : this._effect);
  31474. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31475. return reverse;
  31476. };
  31477. /**
  31478. * Binds the material to the mesh.
  31479. * @param world - World transformation matrix.
  31480. * @param mesh - Mesh to bind the material to.
  31481. */
  31482. Material.prototype.bind = function (world, mesh) {
  31483. };
  31484. /**
  31485. * Binds the submesh to the material.
  31486. * @param world - World transformation matrix.
  31487. * @param mesh - Mesh containing the submesh.
  31488. * @param subMesh - Submesh to bind the material to.
  31489. */
  31490. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31491. };
  31492. /**
  31493. * Binds the world matrix to the material.
  31494. * @param world - World transformation matrix.
  31495. */
  31496. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31497. };
  31498. /**
  31499. * Binds the scene's uniform buffer to the effect.
  31500. * @param effect - Effect to bind to the scene uniform buffer.
  31501. * @param sceneUbo - Scene uniform buffer.
  31502. */
  31503. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31504. sceneUbo.bindToEffect(effect, "Scene");
  31505. };
  31506. /**
  31507. * Binds the view matrix to the effect.
  31508. * @param effect - Effect to bind the view matrix to.
  31509. */
  31510. Material.prototype.bindView = function (effect) {
  31511. if (!this._useUBO) {
  31512. effect.setMatrix("view", this.getScene().getViewMatrix());
  31513. }
  31514. else {
  31515. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31516. }
  31517. };
  31518. /**
  31519. * Binds the view projection matrix to the effect.
  31520. * @param effect - Effect to bind the view projection matrix to.
  31521. */
  31522. Material.prototype.bindViewProjection = function (effect) {
  31523. if (!this._useUBO) {
  31524. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31525. }
  31526. else {
  31527. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31528. }
  31529. };
  31530. /**
  31531. * Specifies if material alpha testing should be turned on for the mesh.
  31532. * @param mesh - BJS mesh.
  31533. */
  31534. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31535. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31536. };
  31537. /**
  31538. * Processes to execute after binding the material to a mesh.
  31539. * @param mesh - BJS mesh.
  31540. */
  31541. Material.prototype._afterBind = function (mesh) {
  31542. this._scene._cachedMaterial = this;
  31543. if (mesh) {
  31544. this._scene._cachedVisibility = mesh.visibility;
  31545. }
  31546. else {
  31547. this._scene._cachedVisibility = 1;
  31548. }
  31549. if (mesh) {
  31550. this.onBindObservable.notifyObservers(mesh);
  31551. }
  31552. if (this.disableDepthWrite) {
  31553. var engine = this._scene.getEngine();
  31554. this._cachedDepthWriteState = engine.getDepthWrite();
  31555. engine.setDepthWrite(false);
  31556. }
  31557. };
  31558. /**
  31559. * Unbinds the material from the mesh.
  31560. */
  31561. Material.prototype.unbind = function () {
  31562. this.onUnBindObservable.notifyObservers(this);
  31563. if (this.disableDepthWrite) {
  31564. var engine = this._scene.getEngine();
  31565. engine.setDepthWrite(this._cachedDepthWriteState);
  31566. }
  31567. };
  31568. /**
  31569. * Gets the active textures from the material.
  31570. * @returns - Array of textures.
  31571. */
  31572. Material.prototype.getActiveTextures = function () {
  31573. return [];
  31574. };
  31575. /**
  31576. * Specifies if the material uses a texture.
  31577. * @param texture - Texture to check against the material.
  31578. * @returns - Boolean specifying if the material uses the texture.
  31579. */
  31580. Material.prototype.hasTexture = function (texture) {
  31581. return false;
  31582. };
  31583. /**
  31584. * Makes a duplicate of the material, and gives it a new name.
  31585. * @param name - Name to call the duplicated material.
  31586. * @returns - Nullable cloned material
  31587. */
  31588. Material.prototype.clone = function (name) {
  31589. return null;
  31590. };
  31591. /**
  31592. * Gets the meshes bound to the material.
  31593. * @returns - Array of meshes bound to the material.
  31594. */
  31595. Material.prototype.getBindedMeshes = function () {
  31596. var result = new Array();
  31597. for (var index = 0; index < this._scene.meshes.length; index++) {
  31598. var mesh = this._scene.meshes[index];
  31599. if (mesh.material === this) {
  31600. result.push(mesh);
  31601. }
  31602. }
  31603. return result;
  31604. };
  31605. /**
  31606. * Force shader compilation
  31607. * @param mesh - BJS mesh.
  31608. * @param onCompiled - function to execute once the material is compiled.
  31609. * @param options - options to pass to this function.
  31610. */
  31611. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31612. var _this = this;
  31613. var localOptions = __assign({ clipPlane: false }, options);
  31614. var subMesh = new BABYLON.BaseSubMesh();
  31615. var scene = this.getScene();
  31616. var checkReady = function () {
  31617. if (!_this._scene || !_this._scene.getEngine()) {
  31618. return;
  31619. }
  31620. if (subMesh._materialDefines) {
  31621. subMesh._materialDefines._renderId = -1;
  31622. }
  31623. var clipPlaneState = scene.clipPlane;
  31624. if (localOptions.clipPlane) {
  31625. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31626. }
  31627. if (_this.storeEffectOnSubMeshes) {
  31628. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31629. if (onCompiled) {
  31630. onCompiled(_this);
  31631. }
  31632. }
  31633. else {
  31634. setTimeout(checkReady, 16);
  31635. }
  31636. }
  31637. else {
  31638. if (_this.isReady(mesh)) {
  31639. if (onCompiled) {
  31640. onCompiled(_this);
  31641. }
  31642. }
  31643. else {
  31644. setTimeout(checkReady, 16);
  31645. }
  31646. }
  31647. if (localOptions.clipPlane) {
  31648. scene.clipPlane = clipPlaneState;
  31649. }
  31650. };
  31651. checkReady();
  31652. };
  31653. /**
  31654. * Force shader compilation.
  31655. * @param mesh The mesh that will use this material
  31656. * @param options Additional options for compiling the shaders
  31657. * @returns A promise that resolves when the compilation completes
  31658. */
  31659. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31660. var _this = this;
  31661. return new Promise(function (resolve) {
  31662. _this.forceCompilation(mesh, function () {
  31663. resolve();
  31664. }, options);
  31665. });
  31666. };
  31667. /**
  31668. * Marks a define in the material to indicate that it needs to be re-computed.
  31669. * @param flag - Material define flag.
  31670. */
  31671. Material.prototype.markAsDirty = function (flag) {
  31672. if (flag & Material.TextureDirtyFlag) {
  31673. this._markAllSubMeshesAsTexturesDirty();
  31674. }
  31675. if (flag & Material.LightDirtyFlag) {
  31676. this._markAllSubMeshesAsLightsDirty();
  31677. }
  31678. if (flag & Material.FresnelDirtyFlag) {
  31679. this._markAllSubMeshesAsFresnelDirty();
  31680. }
  31681. if (flag & Material.AttributesDirtyFlag) {
  31682. this._markAllSubMeshesAsAttributesDirty();
  31683. }
  31684. if (flag & Material.MiscDirtyFlag) {
  31685. this._markAllSubMeshesAsMiscDirty();
  31686. }
  31687. this.getScene().resetCachedMaterial();
  31688. };
  31689. /**
  31690. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31691. * @param func - function which checks material defines against the submeshes.
  31692. */
  31693. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31694. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31695. var mesh = _a[_i];
  31696. if (!mesh.subMeshes) {
  31697. continue;
  31698. }
  31699. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31700. var subMesh = _c[_b];
  31701. if (subMesh.getMaterial() !== this) {
  31702. continue;
  31703. }
  31704. if (!subMesh._materialDefines) {
  31705. continue;
  31706. }
  31707. func(subMesh._materialDefines);
  31708. }
  31709. }
  31710. };
  31711. /**
  31712. * Indicates that image processing needs to be re-calculated for all submeshes.
  31713. */
  31714. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31715. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31716. };
  31717. /**
  31718. * Indicates that textures need to be re-calculated for all submeshes.
  31719. */
  31720. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31721. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31722. };
  31723. /**
  31724. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31725. */
  31726. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31727. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31728. };
  31729. /**
  31730. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31731. */
  31732. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31733. this._markAllSubMeshesAsDirty(function (defines) {
  31734. defines.markAsFresnelDirty();
  31735. defines.markAsMiscDirty();
  31736. });
  31737. };
  31738. /**
  31739. * Indicates that lights need to be re-calculated for all submeshes.
  31740. */
  31741. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31742. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31743. };
  31744. /**
  31745. * Indicates that attributes need to be re-calculated for all submeshes.
  31746. */
  31747. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31748. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31749. };
  31750. /**
  31751. * Indicates that misc needs to be re-calculated for all submeshes.
  31752. */
  31753. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31754. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31755. };
  31756. /**
  31757. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31758. */
  31759. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31760. this._markAllSubMeshesAsDirty(function (defines) {
  31761. defines.markAsTexturesDirty();
  31762. defines.markAsMiscDirty();
  31763. });
  31764. };
  31765. /**
  31766. * Disposes the material.
  31767. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31768. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31769. */
  31770. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31771. // Animations
  31772. this.getScene().stopAnimation(this);
  31773. // Remove from scene
  31774. var index = this._scene.materials.indexOf(this);
  31775. if (index >= 0) {
  31776. this._scene.materials.splice(index, 1);
  31777. }
  31778. // Remove from meshes
  31779. for (index = 0; index < this._scene.meshes.length; index++) {
  31780. var mesh = this._scene.meshes[index];
  31781. if (mesh.material === this) {
  31782. mesh.material = null;
  31783. if (mesh.geometry) {
  31784. var geometry = (mesh.geometry);
  31785. if (this.storeEffectOnSubMeshes) {
  31786. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31787. var subMesh = _a[_i];
  31788. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31789. if (forceDisposeEffect && subMesh._materialEffect) {
  31790. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31791. }
  31792. }
  31793. }
  31794. else {
  31795. geometry._releaseVertexArrayObject(this._effect);
  31796. }
  31797. }
  31798. }
  31799. }
  31800. this._uniformBuffer.dispose();
  31801. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31802. if (forceDisposeEffect && this._effect) {
  31803. if (!this.storeEffectOnSubMeshes) {
  31804. this._scene.getEngine()._releaseEffect(this._effect);
  31805. }
  31806. this._effect = null;
  31807. }
  31808. // Callback
  31809. this.onDisposeObservable.notifyObservers(this);
  31810. this.onDisposeObservable.clear();
  31811. this.onBindObservable.clear();
  31812. this.onUnBindObservable.clear();
  31813. };
  31814. /**
  31815. * Serializes this material.
  31816. * @returns - serialized material object.
  31817. */
  31818. Material.prototype.serialize = function () {
  31819. return BABYLON.SerializationHelper.Serialize(this);
  31820. };
  31821. /**
  31822. * Creates a MultiMaterial from parse MultiMaterial data.
  31823. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31824. * @param scene - BJS scene.
  31825. * @returns - MultiMaterial.
  31826. */
  31827. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31828. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31829. multiMaterial.id = parsedMultiMaterial.id;
  31830. if (BABYLON.Tags) {
  31831. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31832. }
  31833. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31834. var subMatId = parsedMultiMaterial.materials[matIndex];
  31835. if (subMatId) {
  31836. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31837. }
  31838. else {
  31839. multiMaterial.subMaterials.push(null);
  31840. }
  31841. }
  31842. return multiMaterial;
  31843. };
  31844. /**
  31845. * Creates a material from parsed material data.
  31846. * @param parsedMaterial - Parsed material data.
  31847. * @param scene - BJS scene.
  31848. * @param rootUrl - Root URL containing the material information.
  31849. * @returns - Parsed material.
  31850. */
  31851. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31852. if (!parsedMaterial.customType) {
  31853. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31854. }
  31855. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31856. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31857. if (!BABYLON.LegacyPBRMaterial) {
  31858. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31859. return;
  31860. }
  31861. }
  31862. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31863. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31864. ;
  31865. };
  31866. // Triangle views
  31867. Material._TriangleFillMode = 0;
  31868. Material._WireFrameFillMode = 1;
  31869. Material._PointFillMode = 2;
  31870. // Draw modes
  31871. Material._PointListDrawMode = 3;
  31872. Material._LineListDrawMode = 4;
  31873. Material._LineLoopDrawMode = 5;
  31874. Material._LineStripDrawMode = 6;
  31875. Material._TriangleStripDrawMode = 7;
  31876. Material._TriangleFanDrawMode = 8;
  31877. /**
  31878. * Stores the clock-wise side orientation.
  31879. */
  31880. Material._ClockWiseSideOrientation = 0;
  31881. /**
  31882. * Stores the counter clock-wise side orientation.
  31883. */
  31884. Material._CounterClockWiseSideOrientation = 1;
  31885. /**
  31886. * The dirty texture flag value.
  31887. */
  31888. Material._TextureDirtyFlag = 1;
  31889. /**
  31890. * The dirty light flag value.
  31891. */
  31892. Material._LightDirtyFlag = 2;
  31893. /**
  31894. * The dirty fresnel flag value.
  31895. */
  31896. Material._FresnelDirtyFlag = 4;
  31897. /**
  31898. * The dirty attribute flag value.
  31899. */
  31900. Material._AttributesDirtyFlag = 8;
  31901. /**
  31902. * The dirty misc flag value.
  31903. */
  31904. Material._MiscDirtyFlag = 16;
  31905. __decorate([
  31906. BABYLON.serialize()
  31907. ], Material.prototype, "id", void 0);
  31908. __decorate([
  31909. BABYLON.serialize()
  31910. ], Material.prototype, "name", void 0);
  31911. __decorate([
  31912. BABYLON.serialize()
  31913. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31914. __decorate([
  31915. BABYLON.serialize()
  31916. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31917. __decorate([
  31918. BABYLON.serialize()
  31919. ], Material.prototype, "state", void 0);
  31920. __decorate([
  31921. BABYLON.serialize("alpha")
  31922. ], Material.prototype, "_alpha", void 0);
  31923. __decorate([
  31924. BABYLON.serialize("backFaceCulling")
  31925. ], Material.prototype, "_backFaceCulling", void 0);
  31926. __decorate([
  31927. BABYLON.serialize()
  31928. ], Material.prototype, "sideOrientation", void 0);
  31929. __decorate([
  31930. BABYLON.serialize("alphaMode")
  31931. ], Material.prototype, "_alphaMode", void 0);
  31932. __decorate([
  31933. BABYLON.serialize()
  31934. ], Material.prototype, "_needDepthPrePass", void 0);
  31935. __decorate([
  31936. BABYLON.serialize()
  31937. ], Material.prototype, "disableDepthWrite", void 0);
  31938. __decorate([
  31939. BABYLON.serialize()
  31940. ], Material.prototype, "forceDepthWrite", void 0);
  31941. __decorate([
  31942. BABYLON.serialize()
  31943. ], Material.prototype, "separateCullingPass", void 0);
  31944. __decorate([
  31945. BABYLON.serialize("fogEnabled")
  31946. ], Material.prototype, "_fogEnabled", void 0);
  31947. __decorate([
  31948. BABYLON.serialize()
  31949. ], Material.prototype, "pointSize", void 0);
  31950. __decorate([
  31951. BABYLON.serialize()
  31952. ], Material.prototype, "zOffset", void 0);
  31953. __decorate([
  31954. BABYLON.serialize()
  31955. ], Material.prototype, "wireframe", null);
  31956. __decorate([
  31957. BABYLON.serialize()
  31958. ], Material.prototype, "pointsCloud", null);
  31959. __decorate([
  31960. BABYLON.serialize()
  31961. ], Material.prototype, "fillMode", null);
  31962. return Material;
  31963. }());
  31964. BABYLON.Material = Material;
  31965. })(BABYLON || (BABYLON = {}));
  31966. //# sourceMappingURL=babylon.material.js.map
  31967. var BABYLON;
  31968. (function (BABYLON) {
  31969. var UniformBuffer = /** @class */ (function () {
  31970. /**
  31971. * Uniform buffer objects.
  31972. *
  31973. * Handles blocks of uniform on the GPU.
  31974. *
  31975. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31976. *
  31977. * For more information, please refer to :
  31978. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31979. */
  31980. function UniformBuffer(engine, data, dynamic) {
  31981. this._engine = engine;
  31982. this._noUBO = !engine.supportsUniformBuffers;
  31983. this._dynamic = dynamic;
  31984. this._data = data || [];
  31985. this._uniformLocations = {};
  31986. this._uniformSizes = {};
  31987. this._uniformLocationPointer = 0;
  31988. this._needSync = false;
  31989. if (this._noUBO) {
  31990. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31991. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31992. this.updateFloat = this._updateFloatForEffect;
  31993. this.updateFloat2 = this._updateFloat2ForEffect;
  31994. this.updateFloat3 = this._updateFloat3ForEffect;
  31995. this.updateFloat4 = this._updateFloat4ForEffect;
  31996. this.updateMatrix = this._updateMatrixForEffect;
  31997. this.updateVector3 = this._updateVector3ForEffect;
  31998. this.updateVector4 = this._updateVector4ForEffect;
  31999. this.updateColor3 = this._updateColor3ForEffect;
  32000. this.updateColor4 = this._updateColor4ForEffect;
  32001. }
  32002. else {
  32003. this._engine._uniformBuffers.push(this);
  32004. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32005. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32006. this.updateFloat = this._updateFloatForUniform;
  32007. this.updateFloat2 = this._updateFloat2ForUniform;
  32008. this.updateFloat3 = this._updateFloat3ForUniform;
  32009. this.updateFloat4 = this._updateFloat4ForUniform;
  32010. this.updateMatrix = this._updateMatrixForUniform;
  32011. this.updateVector3 = this._updateVector3ForUniform;
  32012. this.updateVector4 = this._updateVector4ForUniform;
  32013. this.updateColor3 = this._updateColor3ForUniform;
  32014. this.updateColor4 = this._updateColor4ForUniform;
  32015. }
  32016. }
  32017. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32018. // Properties
  32019. /**
  32020. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32021. * or just falling back on setUniformXXX calls.
  32022. */
  32023. get: function () {
  32024. return !this._noUBO;
  32025. },
  32026. enumerable: true,
  32027. configurable: true
  32028. });
  32029. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32030. /**
  32031. * Indicates if the WebGL underlying uniform buffer is in sync
  32032. * with the javascript cache data.
  32033. */
  32034. get: function () {
  32035. return !this._needSync;
  32036. },
  32037. enumerable: true,
  32038. configurable: true
  32039. });
  32040. /**
  32041. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32042. * Also, a dynamic UniformBuffer will disable cache verification and always
  32043. * update the underlying WebGL uniform buffer to the GPU.
  32044. */
  32045. UniformBuffer.prototype.isDynamic = function () {
  32046. return this._dynamic !== undefined;
  32047. };
  32048. /**
  32049. * The data cache on JS side.
  32050. */
  32051. UniformBuffer.prototype.getData = function () {
  32052. return this._bufferData;
  32053. };
  32054. /**
  32055. * The underlying WebGL Uniform buffer.
  32056. */
  32057. UniformBuffer.prototype.getBuffer = function () {
  32058. return this._buffer;
  32059. };
  32060. /**
  32061. * std140 layout specifies how to align data within an UBO structure.
  32062. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32063. * for specs.
  32064. */
  32065. UniformBuffer.prototype._fillAlignment = function (size) {
  32066. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32067. // and 4x4 matrices
  32068. // TODO : change if other types are used
  32069. var alignment;
  32070. if (size <= 2) {
  32071. alignment = size;
  32072. }
  32073. else {
  32074. alignment = 4;
  32075. }
  32076. if ((this._uniformLocationPointer % alignment) !== 0) {
  32077. var oldPointer = this._uniformLocationPointer;
  32078. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32079. var diff = this._uniformLocationPointer - oldPointer;
  32080. for (var i = 0; i < diff; i++) {
  32081. this._data.push(0);
  32082. }
  32083. }
  32084. };
  32085. /**
  32086. * Adds an uniform in the buffer.
  32087. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32088. * for the layout to be correct !
  32089. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32090. * @param {number|number[]} size Data size, or data directly.
  32091. */
  32092. UniformBuffer.prototype.addUniform = function (name, size) {
  32093. if (this._noUBO) {
  32094. return;
  32095. }
  32096. if (this._uniformLocations[name] !== undefined) {
  32097. // Already existing uniform
  32098. return;
  32099. }
  32100. // This function must be called in the order of the shader layout !
  32101. // size can be the size of the uniform, or data directly
  32102. var data;
  32103. if (size instanceof Array) {
  32104. data = size;
  32105. size = data.length;
  32106. }
  32107. else {
  32108. size = size;
  32109. data = [];
  32110. // Fill with zeros
  32111. for (var i = 0; i < size; i++) {
  32112. data.push(0);
  32113. }
  32114. }
  32115. this._fillAlignment(size);
  32116. this._uniformSizes[name] = size;
  32117. this._uniformLocations[name] = this._uniformLocationPointer;
  32118. this._uniformLocationPointer += size;
  32119. for (var i = 0; i < size; i++) {
  32120. this._data.push(data[i]);
  32121. }
  32122. this._needSync = true;
  32123. };
  32124. /**
  32125. * Wrapper for addUniform.
  32126. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32127. * @param {Matrix} mat A 4x4 matrix.
  32128. */
  32129. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32130. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32131. };
  32132. /**
  32133. * Wrapper for addUniform.
  32134. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32135. * @param {number} x
  32136. * @param {number} y
  32137. */
  32138. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32139. var temp = [x, y];
  32140. this.addUniform(name, temp);
  32141. };
  32142. /**
  32143. * Wrapper for addUniform.
  32144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32145. * @param {number} x
  32146. * @param {number} y
  32147. * @param {number} z
  32148. */
  32149. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32150. var temp = [x, y, z];
  32151. this.addUniform(name, temp);
  32152. };
  32153. /**
  32154. * Wrapper for addUniform.
  32155. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32156. * @param {Color3} color
  32157. */
  32158. UniformBuffer.prototype.addColor3 = function (name, color) {
  32159. var temp = new Array();
  32160. color.toArray(temp);
  32161. this.addUniform(name, temp);
  32162. };
  32163. /**
  32164. * Wrapper for addUniform.
  32165. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32166. * @param {Color3} color
  32167. * @param {number} alpha
  32168. */
  32169. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32170. var temp = new Array();
  32171. color.toArray(temp);
  32172. temp.push(alpha);
  32173. this.addUniform(name, temp);
  32174. };
  32175. /**
  32176. * Wrapper for addUniform.
  32177. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32178. * @param {Vector3} vector
  32179. */
  32180. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32181. var temp = new Array();
  32182. vector.toArray(temp);
  32183. this.addUniform(name, temp);
  32184. };
  32185. /**
  32186. * Wrapper for addUniform.
  32187. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32188. */
  32189. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32190. this.addUniform(name, 12);
  32191. };
  32192. /**
  32193. * Wrapper for addUniform.
  32194. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32195. */
  32196. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32197. this.addUniform(name, 8);
  32198. };
  32199. /**
  32200. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32201. */
  32202. UniformBuffer.prototype.create = function () {
  32203. if (this._noUBO) {
  32204. return;
  32205. }
  32206. if (this._buffer) {
  32207. return; // nothing to do
  32208. }
  32209. // See spec, alignment must be filled as a vec4
  32210. this._fillAlignment(4);
  32211. this._bufferData = new Float32Array(this._data);
  32212. this._rebuild();
  32213. this._needSync = true;
  32214. };
  32215. UniformBuffer.prototype._rebuild = function () {
  32216. if (this._noUBO) {
  32217. return;
  32218. }
  32219. if (this._dynamic) {
  32220. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32221. }
  32222. else {
  32223. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32224. }
  32225. };
  32226. /**
  32227. * Updates the WebGL Uniform Buffer on the GPU.
  32228. * If the `dynamic` flag is set to true, no cache comparison is done.
  32229. * Otherwise, the buffer will be updated only if the cache differs.
  32230. */
  32231. UniformBuffer.prototype.update = function () {
  32232. if (!this._buffer) {
  32233. this.create();
  32234. return;
  32235. }
  32236. if (!this._dynamic && !this._needSync) {
  32237. return;
  32238. }
  32239. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32240. this._needSync = false;
  32241. };
  32242. /**
  32243. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32244. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32245. * @param {number[]|Float32Array} data Flattened data
  32246. * @param {number} size Size of the data.
  32247. */
  32248. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32249. var location = this._uniformLocations[uniformName];
  32250. if (location === undefined) {
  32251. if (this._buffer) {
  32252. // Cannot add an uniform if the buffer is already created
  32253. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32254. return;
  32255. }
  32256. this.addUniform(uniformName, size);
  32257. location = this._uniformLocations[uniformName];
  32258. }
  32259. if (!this._buffer) {
  32260. this.create();
  32261. }
  32262. if (!this._dynamic) {
  32263. // Cache for static uniform buffers
  32264. var changed = false;
  32265. for (var i = 0; i < size; i++) {
  32266. if (this._bufferData[location + i] !== data[i]) {
  32267. changed = true;
  32268. this._bufferData[location + i] = data[i];
  32269. }
  32270. }
  32271. this._needSync = this._needSync || changed;
  32272. }
  32273. else {
  32274. // No cache for dynamic
  32275. for (var i = 0; i < size; i++) {
  32276. this._bufferData[location + i] = data[i];
  32277. }
  32278. }
  32279. };
  32280. // Update methods
  32281. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32282. // To match std140, matrix must be realigned
  32283. for (var i = 0; i < 3; i++) {
  32284. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32285. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32286. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32287. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32288. }
  32289. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32290. };
  32291. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32292. this._currentEffect.setMatrix3x3(name, matrix);
  32293. };
  32294. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32295. this._currentEffect.setMatrix2x2(name, matrix);
  32296. };
  32297. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32298. // To match std140, matrix must be realigned
  32299. for (var i = 0; i < 2; i++) {
  32300. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32301. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32302. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32303. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32304. }
  32305. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32306. };
  32307. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32308. this._currentEffect.setFloat(name, x);
  32309. };
  32310. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32311. UniformBuffer._tempBuffer[0] = x;
  32312. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32313. };
  32314. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32315. if (suffix === void 0) { suffix = ""; }
  32316. this._currentEffect.setFloat2(name + suffix, x, y);
  32317. };
  32318. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32319. if (suffix === void 0) { suffix = ""; }
  32320. UniformBuffer._tempBuffer[0] = x;
  32321. UniformBuffer._tempBuffer[1] = y;
  32322. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32323. };
  32324. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32325. if (suffix === void 0) { suffix = ""; }
  32326. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32327. };
  32328. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32329. if (suffix === void 0) { suffix = ""; }
  32330. UniformBuffer._tempBuffer[0] = x;
  32331. UniformBuffer._tempBuffer[1] = y;
  32332. UniformBuffer._tempBuffer[2] = z;
  32333. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32334. };
  32335. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32336. if (suffix === void 0) { suffix = ""; }
  32337. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32338. };
  32339. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32340. if (suffix === void 0) { suffix = ""; }
  32341. UniformBuffer._tempBuffer[0] = x;
  32342. UniformBuffer._tempBuffer[1] = y;
  32343. UniformBuffer._tempBuffer[2] = z;
  32344. UniformBuffer._tempBuffer[3] = w;
  32345. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32346. };
  32347. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32348. this._currentEffect.setMatrix(name, mat);
  32349. };
  32350. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32351. this.updateUniform(name, mat.toArray(), 16);
  32352. };
  32353. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32354. this._currentEffect.setVector3(name, vector);
  32355. };
  32356. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32357. vector.toArray(UniformBuffer._tempBuffer);
  32358. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32359. };
  32360. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32361. this._currentEffect.setVector4(name, vector);
  32362. };
  32363. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32364. vector.toArray(UniformBuffer._tempBuffer);
  32365. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32366. };
  32367. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32368. if (suffix === void 0) { suffix = ""; }
  32369. this._currentEffect.setColor3(name + suffix, color);
  32370. };
  32371. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32372. if (suffix === void 0) { suffix = ""; }
  32373. color.toArray(UniformBuffer._tempBuffer);
  32374. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32375. };
  32376. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32377. if (suffix === void 0) { suffix = ""; }
  32378. this._currentEffect.setColor4(name + suffix, color, alpha);
  32379. };
  32380. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32381. if (suffix === void 0) { suffix = ""; }
  32382. color.toArray(UniformBuffer._tempBuffer);
  32383. UniformBuffer._tempBuffer[3] = alpha;
  32384. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32385. };
  32386. /**
  32387. * Sets a sampler uniform on the effect.
  32388. * @param {string} name Name of the sampler.
  32389. * @param {Texture} texture
  32390. */
  32391. UniformBuffer.prototype.setTexture = function (name, texture) {
  32392. this._currentEffect.setTexture(name, texture);
  32393. };
  32394. /**
  32395. * Directly updates the value of the uniform in the cache AND on the GPU.
  32396. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32397. * @param {number[]|Float32Array} data Flattened data
  32398. */
  32399. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32400. this.updateUniform(uniformName, data, data.length);
  32401. this.update();
  32402. };
  32403. /**
  32404. * Binds this uniform buffer to an effect.
  32405. * @param {Effect} effect
  32406. * @param {string} name Name of the uniform block in the shader.
  32407. */
  32408. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32409. this._currentEffect = effect;
  32410. if (this._noUBO || !this._buffer) {
  32411. return;
  32412. }
  32413. effect.bindUniformBuffer(this._buffer, name);
  32414. };
  32415. /**
  32416. * Disposes the uniform buffer.
  32417. */
  32418. UniformBuffer.prototype.dispose = function () {
  32419. if (this._noUBO) {
  32420. return;
  32421. }
  32422. var index = this._engine._uniformBuffers.indexOf(this);
  32423. if (index !== -1) {
  32424. this._engine._uniformBuffers.splice(index, 1);
  32425. }
  32426. if (!this._buffer) {
  32427. return;
  32428. }
  32429. if (this._engine._releaseBuffer(this._buffer)) {
  32430. this._buffer = null;
  32431. }
  32432. };
  32433. // Pool for avoiding memory leaks
  32434. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32435. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32436. return UniformBuffer;
  32437. }());
  32438. BABYLON.UniformBuffer = UniformBuffer;
  32439. })(BABYLON || (BABYLON = {}));
  32440. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32441. var BABYLON;
  32442. (function (BABYLON) {
  32443. var VertexData = /** @class */ (function () {
  32444. function VertexData() {
  32445. }
  32446. VertexData.prototype.set = function (data, kind) {
  32447. switch (kind) {
  32448. case BABYLON.VertexBuffer.PositionKind:
  32449. this.positions = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.NormalKind:
  32452. this.normals = data;
  32453. break;
  32454. case BABYLON.VertexBuffer.TangentKind:
  32455. this.tangents = data;
  32456. break;
  32457. case BABYLON.VertexBuffer.UVKind:
  32458. this.uvs = data;
  32459. break;
  32460. case BABYLON.VertexBuffer.UV2Kind:
  32461. this.uvs2 = data;
  32462. break;
  32463. case BABYLON.VertexBuffer.UV3Kind:
  32464. this.uvs3 = data;
  32465. break;
  32466. case BABYLON.VertexBuffer.UV4Kind:
  32467. this.uvs4 = data;
  32468. break;
  32469. case BABYLON.VertexBuffer.UV5Kind:
  32470. this.uvs5 = data;
  32471. break;
  32472. case BABYLON.VertexBuffer.UV6Kind:
  32473. this.uvs6 = data;
  32474. break;
  32475. case BABYLON.VertexBuffer.ColorKind:
  32476. this.colors = data;
  32477. break;
  32478. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32479. this.matricesIndices = data;
  32480. break;
  32481. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32482. this.matricesWeights = data;
  32483. break;
  32484. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32485. this.matricesIndicesExtra = data;
  32486. break;
  32487. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32488. this.matricesWeightsExtra = data;
  32489. break;
  32490. }
  32491. };
  32492. /**
  32493. * Associates the vertexData to the passed Mesh.
  32494. * Sets it as updatable or not (default `false`).
  32495. * Returns the VertexData.
  32496. */
  32497. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32498. this._applyTo(mesh, updatable);
  32499. return this;
  32500. };
  32501. /**
  32502. * Associates the vertexData to the passed Geometry.
  32503. * Sets it as updatable or not (default `false`).
  32504. * Returns the VertexData.
  32505. */
  32506. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32507. this._applyTo(geometry, updatable);
  32508. return this;
  32509. };
  32510. /**
  32511. * Updates the associated mesh.
  32512. * Returns the VertexData.
  32513. */
  32514. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32515. this._update(mesh);
  32516. return this;
  32517. };
  32518. /**
  32519. * Updates the associated geometry.
  32520. * Returns the VertexData.
  32521. */
  32522. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32523. this._update(geometry);
  32524. return this;
  32525. };
  32526. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32527. if (updatable === void 0) { updatable = false; }
  32528. if (this.positions) {
  32529. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32530. }
  32531. if (this.normals) {
  32532. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32533. }
  32534. if (this.tangents) {
  32535. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32536. }
  32537. if (this.uvs) {
  32538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32539. }
  32540. if (this.uvs2) {
  32541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32542. }
  32543. if (this.uvs3) {
  32544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32545. }
  32546. if (this.uvs4) {
  32547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32548. }
  32549. if (this.uvs5) {
  32550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32551. }
  32552. if (this.uvs6) {
  32553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32554. }
  32555. if (this.colors) {
  32556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32557. }
  32558. if (this.matricesIndices) {
  32559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32560. }
  32561. if (this.matricesWeights) {
  32562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32563. }
  32564. if (this.matricesIndicesExtra) {
  32565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32566. }
  32567. if (this.matricesWeightsExtra) {
  32568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32569. }
  32570. if (this.indices) {
  32571. meshOrGeometry.setIndices(this.indices, null, updatable);
  32572. }
  32573. return this;
  32574. };
  32575. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32576. if (this.positions) {
  32577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32578. }
  32579. if (this.normals) {
  32580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32581. }
  32582. if (this.tangents) {
  32583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32584. }
  32585. if (this.uvs) {
  32586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32587. }
  32588. if (this.uvs2) {
  32589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32590. }
  32591. if (this.uvs3) {
  32592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32593. }
  32594. if (this.uvs4) {
  32595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32596. }
  32597. if (this.uvs5) {
  32598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32599. }
  32600. if (this.uvs6) {
  32601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32602. }
  32603. if (this.colors) {
  32604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32605. }
  32606. if (this.matricesIndices) {
  32607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32608. }
  32609. if (this.matricesWeights) {
  32610. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32611. }
  32612. if (this.matricesIndicesExtra) {
  32613. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32614. }
  32615. if (this.matricesWeightsExtra) {
  32616. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32617. }
  32618. if (this.indices) {
  32619. meshOrGeometry.setIndices(this.indices, null);
  32620. }
  32621. return this;
  32622. };
  32623. /**
  32624. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32625. * Returns the VertexData.
  32626. */
  32627. VertexData.prototype.transform = function (matrix) {
  32628. var transformed = BABYLON.Vector3.Zero();
  32629. var index;
  32630. if (this.positions) {
  32631. var position = BABYLON.Vector3.Zero();
  32632. for (index = 0; index < this.positions.length; index += 3) {
  32633. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32634. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32635. this.positions[index] = transformed.x;
  32636. this.positions[index + 1] = transformed.y;
  32637. this.positions[index + 2] = transformed.z;
  32638. }
  32639. }
  32640. if (this.normals) {
  32641. var normal = BABYLON.Vector3.Zero();
  32642. for (index = 0; index < this.normals.length; index += 3) {
  32643. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32644. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32645. this.normals[index] = transformed.x;
  32646. this.normals[index + 1] = transformed.y;
  32647. this.normals[index + 2] = transformed.z;
  32648. }
  32649. }
  32650. if (this.tangents) {
  32651. var tangent = BABYLON.Vector4.Zero();
  32652. var tangentTransformed = BABYLON.Vector4.Zero();
  32653. for (index = 0; index < this.tangents.length; index += 4) {
  32654. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32655. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32656. this.tangents[index] = tangentTransformed.x;
  32657. this.tangents[index + 1] = tangentTransformed.y;
  32658. this.tangents[index + 2] = tangentTransformed.z;
  32659. this.tangents[index + 3] = tangentTransformed.w;
  32660. }
  32661. }
  32662. return this;
  32663. };
  32664. /**
  32665. * Merges the passed VertexData into the current one.
  32666. * Returns the modified VertexData.
  32667. */
  32668. VertexData.prototype.merge = function (other) {
  32669. this._validate();
  32670. other._validate();
  32671. if (!this.normals !== !other.normals ||
  32672. !this.tangents !== !other.tangents ||
  32673. !this.uvs !== !other.uvs ||
  32674. !this.uvs2 !== !other.uvs2 ||
  32675. !this.uvs3 !== !other.uvs3 ||
  32676. !this.uvs4 !== !other.uvs4 ||
  32677. !this.uvs5 !== !other.uvs5 ||
  32678. !this.uvs6 !== !other.uvs6 ||
  32679. !this.colors !== !other.colors ||
  32680. !this.matricesIndices !== !other.matricesIndices ||
  32681. !this.matricesWeights !== !other.matricesWeights ||
  32682. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32683. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32684. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32685. }
  32686. if (other.indices) {
  32687. if (!this.indices) {
  32688. this.indices = [];
  32689. }
  32690. var offset = this.positions ? this.positions.length / 3 : 0;
  32691. for (var index = 0; index < other.indices.length; index++) {
  32692. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32693. this.indices.push(other.indices[index] + offset);
  32694. }
  32695. }
  32696. this.positions = this._mergeElement(this.positions, other.positions);
  32697. this.normals = this._mergeElement(this.normals, other.normals);
  32698. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32699. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32700. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32701. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32702. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32703. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32704. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32705. this.colors = this._mergeElement(this.colors, other.colors);
  32706. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32707. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32708. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32709. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32710. return this;
  32711. };
  32712. VertexData.prototype._mergeElement = function (source, other) {
  32713. if (!source) {
  32714. return other;
  32715. }
  32716. if (!other) {
  32717. return source;
  32718. }
  32719. var len = other.length + source.length;
  32720. var isSrcTypedArray = source instanceof Float32Array;
  32721. var isOthTypedArray = other instanceof Float32Array;
  32722. // use non-loop method when the source is Float32Array
  32723. if (isSrcTypedArray) {
  32724. var ret32 = new Float32Array(len);
  32725. ret32.set(source);
  32726. ret32.set(other, source.length);
  32727. return ret32;
  32728. // source is number[], when other is also use concat
  32729. }
  32730. else if (!isOthTypedArray) {
  32731. return source.concat(other);
  32732. // source is a number[], but other is a Float32Array, loop required
  32733. }
  32734. else {
  32735. var ret = source.slice(0); // copy source to a separate array
  32736. for (var i = 0, len = other.length; i < len; i++) {
  32737. ret.push(other[i]);
  32738. }
  32739. return ret;
  32740. }
  32741. };
  32742. VertexData.prototype._validate = function () {
  32743. if (!this.positions) {
  32744. throw new Error("Positions are required");
  32745. }
  32746. var getElementCount = function (kind, values) {
  32747. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32748. if ((values.length % stride) !== 0) {
  32749. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32750. }
  32751. return values.length / stride;
  32752. };
  32753. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32754. var validateElementCount = function (kind, values) {
  32755. var elementCount = getElementCount(kind, values);
  32756. if (elementCount !== positionsElementCount) {
  32757. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32758. }
  32759. };
  32760. if (this.normals)
  32761. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32762. if (this.tangents)
  32763. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32764. if (this.uvs)
  32765. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32766. if (this.uvs2)
  32767. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32768. if (this.uvs3)
  32769. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32770. if (this.uvs4)
  32771. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32772. if (this.uvs5)
  32773. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32774. if (this.uvs6)
  32775. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32776. if (this.colors)
  32777. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32778. if (this.matricesIndices)
  32779. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32780. if (this.matricesWeights)
  32781. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32782. if (this.matricesIndicesExtra)
  32783. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32784. if (this.matricesWeightsExtra)
  32785. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32786. };
  32787. /**
  32788. * Serializes the VertexData.
  32789. * Returns a serialized object.
  32790. */
  32791. VertexData.prototype.serialize = function () {
  32792. var serializationObject = this.serialize();
  32793. if (this.positions) {
  32794. serializationObject.positions = this.positions;
  32795. }
  32796. if (this.normals) {
  32797. serializationObject.normals = this.normals;
  32798. }
  32799. if (this.tangents) {
  32800. serializationObject.tangents = this.tangents;
  32801. }
  32802. if (this.uvs) {
  32803. serializationObject.uvs = this.uvs;
  32804. }
  32805. if (this.uvs2) {
  32806. serializationObject.uvs2 = this.uvs2;
  32807. }
  32808. if (this.uvs3) {
  32809. serializationObject.uvs3 = this.uvs3;
  32810. }
  32811. if (this.uvs4) {
  32812. serializationObject.uvs4 = this.uvs4;
  32813. }
  32814. if (this.uvs5) {
  32815. serializationObject.uvs5 = this.uvs5;
  32816. }
  32817. if (this.uvs6) {
  32818. serializationObject.uvs6 = this.uvs6;
  32819. }
  32820. if (this.colors) {
  32821. serializationObject.colors = this.colors;
  32822. }
  32823. if (this.matricesIndices) {
  32824. serializationObject.matricesIndices = this.matricesIndices;
  32825. serializationObject.matricesIndices._isExpanded = true;
  32826. }
  32827. if (this.matricesWeights) {
  32828. serializationObject.matricesWeights = this.matricesWeights;
  32829. }
  32830. if (this.matricesIndicesExtra) {
  32831. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32832. serializationObject.matricesIndicesExtra._isExpanded = true;
  32833. }
  32834. if (this.matricesWeightsExtra) {
  32835. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32836. }
  32837. serializationObject.indices = this.indices;
  32838. return serializationObject;
  32839. };
  32840. // Statics
  32841. /**
  32842. * Returns the object VertexData associated to the passed mesh.
  32843. */
  32844. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32845. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32846. };
  32847. /**
  32848. * Returns the object VertexData associated to the passed geometry.
  32849. */
  32850. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32851. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32852. };
  32853. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32854. var result = new VertexData();
  32855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32856. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32857. }
  32858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32859. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32860. }
  32861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32862. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32863. }
  32864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32865. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32866. }
  32867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32868. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32869. }
  32870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32871. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32872. }
  32873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32874. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32875. }
  32876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32877. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32878. }
  32879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32880. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32881. }
  32882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32883. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32884. }
  32885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32886. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32887. }
  32888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32889. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32890. }
  32891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32892. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32893. }
  32894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32895. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32896. }
  32897. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32898. return result;
  32899. };
  32900. /**
  32901. * Creates the vertexData of the Ribbon.
  32902. */
  32903. VertexData.CreateRibbon = function (options) {
  32904. var pathArray = options.pathArray;
  32905. var closeArray = options.closeArray || false;
  32906. var closePath = options.closePath || false;
  32907. var invertUV = options.invertUV || false;
  32908. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32909. var offset = options.offset || defaultOffset;
  32910. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32911. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32912. var customUV = options.uvs;
  32913. var customColors = options.colors;
  32914. var positions = [];
  32915. var indices = [];
  32916. var normals = [];
  32917. var uvs = [];
  32918. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32919. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32920. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32921. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32922. var minlg; // minimal length among all paths from pathArray
  32923. var lg = []; // array of path lengths : nb of vertex per path
  32924. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32925. var p; // path iterator
  32926. var i; // point iterator
  32927. var j; // point iterator
  32928. // if single path in pathArray
  32929. if (pathArray.length < 2) {
  32930. var ar1 = [];
  32931. var ar2 = [];
  32932. for (i = 0; i < pathArray[0].length - offset; i++) {
  32933. ar1.push(pathArray[0][i]);
  32934. ar2.push(pathArray[0][i + offset]);
  32935. }
  32936. pathArray = [ar1, ar2];
  32937. }
  32938. // positions and horizontal distances (u)
  32939. var idc = 0;
  32940. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32941. var path;
  32942. var l;
  32943. minlg = pathArray[0].length;
  32944. var vectlg;
  32945. var dist;
  32946. for (p = 0; p < pathArray.length; p++) {
  32947. uTotalDistance[p] = 0;
  32948. us[p] = [0];
  32949. path = pathArray[p];
  32950. l = path.length;
  32951. minlg = (minlg < l) ? minlg : l;
  32952. j = 0;
  32953. while (j < l) {
  32954. positions.push(path[j].x, path[j].y, path[j].z);
  32955. if (j > 0) {
  32956. vectlg = path[j].subtract(path[j - 1]).length();
  32957. dist = vectlg + uTotalDistance[p];
  32958. us[p].push(dist);
  32959. uTotalDistance[p] = dist;
  32960. }
  32961. j++;
  32962. }
  32963. if (closePath) {
  32964. j--;
  32965. positions.push(path[0].x, path[0].y, path[0].z);
  32966. vectlg = path[j].subtract(path[0]).length();
  32967. dist = vectlg + uTotalDistance[p];
  32968. us[p].push(dist);
  32969. uTotalDistance[p] = dist;
  32970. }
  32971. lg[p] = l + closePathCorr;
  32972. idx[p] = idc;
  32973. idc += (l + closePathCorr);
  32974. }
  32975. // vertical distances (v)
  32976. var path1;
  32977. var path2;
  32978. var vertex1 = null;
  32979. var vertex2 = null;
  32980. for (i = 0; i < minlg + closePathCorr; i++) {
  32981. vTotalDistance[i] = 0;
  32982. vs[i] = [0];
  32983. for (p = 0; p < pathArray.length - 1; p++) {
  32984. path1 = pathArray[p];
  32985. path2 = pathArray[p + 1];
  32986. if (i === minlg) {
  32987. vertex1 = path1[0];
  32988. vertex2 = path2[0];
  32989. }
  32990. else {
  32991. vertex1 = path1[i];
  32992. vertex2 = path2[i];
  32993. }
  32994. vectlg = vertex2.subtract(vertex1).length();
  32995. dist = vectlg + vTotalDistance[i];
  32996. vs[i].push(dist);
  32997. vTotalDistance[i] = dist;
  32998. }
  32999. if (closeArray && vertex2 && vertex1) {
  33000. path1 = pathArray[p];
  33001. path2 = pathArray[0];
  33002. if (i === minlg) {
  33003. vertex2 = path2[0];
  33004. }
  33005. vectlg = vertex2.subtract(vertex1).length();
  33006. dist = vectlg + vTotalDistance[i];
  33007. vTotalDistance[i] = dist;
  33008. }
  33009. }
  33010. // uvs
  33011. var u;
  33012. var v;
  33013. if (customUV) {
  33014. for (p = 0; p < customUV.length; p++) {
  33015. uvs.push(customUV[p].x, customUV[p].y);
  33016. }
  33017. }
  33018. else {
  33019. for (p = 0; p < pathArray.length; p++) {
  33020. for (i = 0; i < minlg + closePathCorr; i++) {
  33021. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33022. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33023. if (invertUV) {
  33024. uvs.push(v, u);
  33025. }
  33026. else {
  33027. uvs.push(u, v);
  33028. }
  33029. }
  33030. }
  33031. }
  33032. // indices
  33033. p = 0; // path index
  33034. var pi = 0; // positions array index
  33035. var l1 = lg[p] - 1; // path1 length
  33036. var l2 = lg[p + 1] - 1; // path2 length
  33037. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33038. var shft = idx[1] - idx[0]; // shift
  33039. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33040. while (pi <= min && p < path1nb) {
  33041. // 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
  33042. indices.push(pi, pi + shft, pi + 1);
  33043. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33044. pi += 1;
  33045. if (pi === min) {
  33046. p++;
  33047. if (p === lg.length - 1) {
  33048. shft = idx[0] - idx[p];
  33049. l1 = lg[p] - 1;
  33050. l2 = lg[0] - 1;
  33051. }
  33052. else {
  33053. shft = idx[p + 1] - idx[p];
  33054. l1 = lg[p] - 1;
  33055. l2 = lg[p + 1] - 1;
  33056. }
  33057. pi = idx[p];
  33058. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33059. }
  33060. }
  33061. // normals
  33062. VertexData.ComputeNormals(positions, indices, normals);
  33063. if (closePath) {
  33064. var indexFirst = 0;
  33065. var indexLast = 0;
  33066. for (p = 0; p < pathArray.length; p++) {
  33067. indexFirst = idx[p] * 3;
  33068. if (p + 1 < pathArray.length) {
  33069. indexLast = (idx[p + 1] - 1) * 3;
  33070. }
  33071. else {
  33072. indexLast = normals.length - 3;
  33073. }
  33074. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33075. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33076. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33077. normals[indexLast] = normals[indexFirst];
  33078. normals[indexLast + 1] = normals[indexFirst + 1];
  33079. normals[indexLast + 2] = normals[indexFirst + 2];
  33080. }
  33081. }
  33082. // sides
  33083. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33084. // Colors
  33085. var colors = null;
  33086. if (customColors) {
  33087. colors = new Float32Array(customColors.length * 4);
  33088. for (var c = 0; c < customColors.length; c++) {
  33089. colors[c * 4] = customColors[c].r;
  33090. colors[c * 4 + 1] = customColors[c].g;
  33091. colors[c * 4 + 2] = customColors[c].b;
  33092. colors[c * 4 + 3] = customColors[c].a;
  33093. }
  33094. }
  33095. // Result
  33096. var vertexData = new VertexData();
  33097. var positions32 = new Float32Array(positions);
  33098. var normals32 = new Float32Array(normals);
  33099. var uvs32 = new Float32Array(uvs);
  33100. vertexData.indices = indices;
  33101. vertexData.positions = positions32;
  33102. vertexData.normals = normals32;
  33103. vertexData.uvs = uvs32;
  33104. if (colors) {
  33105. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33106. }
  33107. if (closePath) {
  33108. vertexData._idx = idx;
  33109. }
  33110. return vertexData;
  33111. };
  33112. /**
  33113. * Creates the VertexData of the Box.
  33114. */
  33115. VertexData.CreateBox = function (options) {
  33116. var normalsSource = [
  33117. new BABYLON.Vector3(0, 0, 1),
  33118. new BABYLON.Vector3(0, 0, -1),
  33119. new BABYLON.Vector3(1, 0, 0),
  33120. new BABYLON.Vector3(-1, 0, 0),
  33121. new BABYLON.Vector3(0, 1, 0),
  33122. new BABYLON.Vector3(0, -1, 0)
  33123. ];
  33124. var indices = [];
  33125. var positions = [];
  33126. var normals = [];
  33127. var uvs = [];
  33128. var width = options.width || options.size || 1;
  33129. var height = options.height || options.size || 1;
  33130. var depth = options.depth || options.size || 1;
  33131. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33132. var faceUV = options.faceUV || new Array(6);
  33133. var faceColors = options.faceColors;
  33134. var colors = [];
  33135. // default face colors and UV if undefined
  33136. for (var f = 0; f < 6; f++) {
  33137. if (faceUV[f] === undefined) {
  33138. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33139. }
  33140. if (faceColors && faceColors[f] === undefined) {
  33141. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33142. }
  33143. }
  33144. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33145. // Create each face in turn.
  33146. for (var index = 0; index < normalsSource.length; index++) {
  33147. var normal = normalsSource[index];
  33148. // Get two vectors perpendicular to the face normal and to each other.
  33149. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33150. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33151. // Six indices (two triangles) per face.
  33152. var verticesLength = positions.length / 3;
  33153. indices.push(verticesLength);
  33154. indices.push(verticesLength + 1);
  33155. indices.push(verticesLength + 2);
  33156. indices.push(verticesLength);
  33157. indices.push(verticesLength + 2);
  33158. indices.push(verticesLength + 3);
  33159. // Four vertices per face.
  33160. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33161. positions.push(vertex.x, vertex.y, vertex.z);
  33162. normals.push(normal.x, normal.y, normal.z);
  33163. uvs.push(faceUV[index].z, faceUV[index].w);
  33164. if (faceColors) {
  33165. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33166. }
  33167. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33168. positions.push(vertex.x, vertex.y, vertex.z);
  33169. normals.push(normal.x, normal.y, normal.z);
  33170. uvs.push(faceUV[index].x, faceUV[index].w);
  33171. if (faceColors) {
  33172. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33173. }
  33174. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33175. positions.push(vertex.x, vertex.y, vertex.z);
  33176. normals.push(normal.x, normal.y, normal.z);
  33177. uvs.push(faceUV[index].x, faceUV[index].y);
  33178. if (faceColors) {
  33179. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33180. }
  33181. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33182. positions.push(vertex.x, vertex.y, vertex.z);
  33183. normals.push(normal.x, normal.y, normal.z);
  33184. uvs.push(faceUV[index].z, faceUV[index].y);
  33185. if (faceColors) {
  33186. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33187. }
  33188. }
  33189. // sides
  33190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33191. // Result
  33192. var vertexData = new VertexData();
  33193. vertexData.indices = indices;
  33194. vertexData.positions = positions;
  33195. vertexData.normals = normals;
  33196. vertexData.uvs = uvs;
  33197. if (faceColors) {
  33198. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33199. vertexData.colors = totalColors;
  33200. }
  33201. return vertexData;
  33202. };
  33203. /**
  33204. * Creates the VertexData of the Sphere.
  33205. */
  33206. VertexData.CreateSphere = function (options) {
  33207. var segments = options.segments || 32;
  33208. var diameterX = options.diameterX || options.diameter || 1;
  33209. var diameterY = options.diameterY || options.diameter || 1;
  33210. var diameterZ = options.diameterZ || options.diameter || 1;
  33211. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33212. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33214. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33215. var totalZRotationSteps = 2 + segments;
  33216. var totalYRotationSteps = 2 * totalZRotationSteps;
  33217. var indices = [];
  33218. var positions = [];
  33219. var normals = [];
  33220. var uvs = [];
  33221. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33222. var normalizedZ = zRotationStep / totalZRotationSteps;
  33223. var angleZ = normalizedZ * Math.PI * slice;
  33224. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33225. var normalizedY = yRotationStep / totalYRotationSteps;
  33226. var angleY = normalizedY * Math.PI * 2 * arc;
  33227. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33228. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33229. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33230. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33231. var vertex = complete.multiply(radius);
  33232. var normal = complete.divide(radius).normalize();
  33233. positions.push(vertex.x, vertex.y, vertex.z);
  33234. normals.push(normal.x, normal.y, normal.z);
  33235. uvs.push(normalizedY, normalizedZ);
  33236. }
  33237. if (zRotationStep > 0) {
  33238. var verticesCount = positions.length / 3;
  33239. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33240. indices.push((firstIndex));
  33241. indices.push((firstIndex + 1));
  33242. indices.push(firstIndex + totalYRotationSteps + 1);
  33243. indices.push((firstIndex + totalYRotationSteps + 1));
  33244. indices.push((firstIndex + 1));
  33245. indices.push((firstIndex + totalYRotationSteps + 2));
  33246. }
  33247. }
  33248. }
  33249. // Sides
  33250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33251. // Result
  33252. var vertexData = new VertexData();
  33253. vertexData.indices = indices;
  33254. vertexData.positions = positions;
  33255. vertexData.normals = normals;
  33256. vertexData.uvs = uvs;
  33257. return vertexData;
  33258. };
  33259. /**
  33260. * Creates the VertexData of the Cylinder or Cone.
  33261. */
  33262. VertexData.CreateCylinder = function (options) {
  33263. var height = options.height || 2;
  33264. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33265. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33266. var tessellation = options.tessellation || 24;
  33267. var subdivisions = options.subdivisions || 1;
  33268. var hasRings = options.hasRings ? true : false;
  33269. var enclose = options.enclose ? true : false;
  33270. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33271. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33272. var faceUV = options.faceUV || new Array(3);
  33273. var faceColors = options.faceColors;
  33274. // default face colors and UV if undefined
  33275. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33276. var ringNb = (hasRings) ? subdivisions : 1;
  33277. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33278. var f;
  33279. for (f = 0; f < surfaceNb; f++) {
  33280. if (faceColors && faceColors[f] === undefined) {
  33281. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33282. }
  33283. }
  33284. for (f = 0; f < surfaceNb; f++) {
  33285. if (faceUV && faceUV[f] === undefined) {
  33286. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33287. }
  33288. }
  33289. var indices = new Array();
  33290. var positions = new Array();
  33291. var normals = new Array();
  33292. var uvs = new Array();
  33293. var colors = new Array();
  33294. var angle_step = Math.PI * 2 * arc / tessellation;
  33295. var angle;
  33296. var h;
  33297. var radius;
  33298. var tan = (diameterBottom - diameterTop) / 2 / height;
  33299. var ringVertex = BABYLON.Vector3.Zero();
  33300. var ringNormal = BABYLON.Vector3.Zero();
  33301. var ringFirstVertex = BABYLON.Vector3.Zero();
  33302. var ringFirstNormal = BABYLON.Vector3.Zero();
  33303. var quadNormal = BABYLON.Vector3.Zero();
  33304. var Y = BABYLON.Axis.Y;
  33305. // positions, normals, uvs
  33306. var i;
  33307. var j;
  33308. var r;
  33309. var ringIdx = 1;
  33310. var s = 1; // surface index
  33311. var cs = 0;
  33312. var v = 0;
  33313. for (i = 0; i <= subdivisions; i++) {
  33314. h = i / subdivisions;
  33315. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33316. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33317. for (r = 0; r < ringIdx; r++) {
  33318. if (hasRings) {
  33319. s += r;
  33320. }
  33321. if (enclose) {
  33322. s += 2 * r;
  33323. }
  33324. for (j = 0; j <= tessellation; j++) {
  33325. angle = j * angle_step;
  33326. // position
  33327. ringVertex.x = Math.cos(-angle) * radius;
  33328. ringVertex.y = -height / 2 + h * height;
  33329. ringVertex.z = Math.sin(-angle) * radius;
  33330. // normal
  33331. if (diameterTop === 0 && i === subdivisions) {
  33332. // if no top cap, reuse former normals
  33333. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33334. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33335. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33336. }
  33337. else {
  33338. ringNormal.x = ringVertex.x;
  33339. ringNormal.z = ringVertex.z;
  33340. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33341. ringNormal.normalize();
  33342. }
  33343. // keep first ring vertex values for enclose
  33344. if (j === 0) {
  33345. ringFirstVertex.copyFrom(ringVertex);
  33346. ringFirstNormal.copyFrom(ringNormal);
  33347. }
  33348. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33349. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33350. if (hasRings) {
  33351. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33352. }
  33353. else {
  33354. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33355. }
  33356. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33357. if (faceColors) {
  33358. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33359. }
  33360. }
  33361. // if enclose, add four vertices and their dedicated normals
  33362. if (arc !== 1 && enclose) {
  33363. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33364. positions.push(0, ringVertex.y, 0);
  33365. positions.push(0, ringVertex.y, 0);
  33366. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33367. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33368. quadNormal.normalize();
  33369. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33370. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33371. quadNormal.normalize();
  33372. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33373. if (hasRings) {
  33374. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33375. }
  33376. else {
  33377. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33378. }
  33379. uvs.push(faceUV[s + 1].x, v);
  33380. uvs.push(faceUV[s + 1].z, v);
  33381. if (hasRings) {
  33382. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33383. }
  33384. else {
  33385. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33386. }
  33387. uvs.push(faceUV[s + 2].x, v);
  33388. uvs.push(faceUV[s + 2].z, v);
  33389. if (faceColors) {
  33390. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33391. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33392. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33393. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33394. }
  33395. }
  33396. if (cs !== s) {
  33397. cs = s;
  33398. }
  33399. }
  33400. }
  33401. // indices
  33402. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33403. var s;
  33404. i = 0;
  33405. for (s = 0; s < subdivisions; s++) {
  33406. var i0 = 0;
  33407. var i1 = 0;
  33408. var i2 = 0;
  33409. var i3 = 0;
  33410. for (j = 0; j < tessellation; j++) {
  33411. i0 = i * (e + 1) + j;
  33412. i1 = (i + 1) * (e + 1) + j;
  33413. i2 = i * (e + 1) + (j + 1);
  33414. i3 = (i + 1) * (e + 1) + (j + 1);
  33415. indices.push(i0, i1, i2);
  33416. indices.push(i3, i2, i1);
  33417. }
  33418. if (arc !== 1 && enclose) {
  33419. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33420. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33421. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33422. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33423. }
  33424. i = (hasRings) ? (i + 2) : (i + 1);
  33425. }
  33426. // Caps
  33427. var createCylinderCap = function (isTop) {
  33428. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33429. if (radius === 0) {
  33430. return;
  33431. }
  33432. // Cap positions, normals & uvs
  33433. var angle;
  33434. var circleVector;
  33435. var i;
  33436. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33437. var c = null;
  33438. if (faceColors) {
  33439. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33440. }
  33441. // cap center
  33442. var vbase = positions.length / 3;
  33443. var offset = isTop ? height / 2 : -height / 2;
  33444. var center = new BABYLON.Vector3(0, offset, 0);
  33445. positions.push(center.x, center.y, center.z);
  33446. normals.push(0, isTop ? 1 : -1, 0);
  33447. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33448. if (c) {
  33449. colors.push(c.r, c.g, c.b, c.a);
  33450. }
  33451. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33452. for (i = 0; i <= tessellation; i++) {
  33453. angle = Math.PI * 2 * i * arc / tessellation;
  33454. var cos = Math.cos(-angle);
  33455. var sin = Math.sin(-angle);
  33456. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33457. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33458. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33459. normals.push(0, isTop ? 1 : -1, 0);
  33460. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33461. if (c) {
  33462. colors.push(c.r, c.g, c.b, c.a);
  33463. }
  33464. }
  33465. // Cap indices
  33466. for (i = 0; i < tessellation; i++) {
  33467. if (!isTop) {
  33468. indices.push(vbase);
  33469. indices.push(vbase + (i + 1));
  33470. indices.push(vbase + (i + 2));
  33471. }
  33472. else {
  33473. indices.push(vbase);
  33474. indices.push(vbase + (i + 2));
  33475. indices.push(vbase + (i + 1));
  33476. }
  33477. }
  33478. };
  33479. // add caps to geometry
  33480. createCylinderCap(false);
  33481. createCylinderCap(true);
  33482. // Sides
  33483. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33484. var vertexData = new VertexData();
  33485. vertexData.indices = indices;
  33486. vertexData.positions = positions;
  33487. vertexData.normals = normals;
  33488. vertexData.uvs = uvs;
  33489. if (faceColors) {
  33490. vertexData.colors = colors;
  33491. }
  33492. return vertexData;
  33493. };
  33494. /**
  33495. * Creates the VertexData of the Torus.
  33496. */
  33497. VertexData.CreateTorus = function (options) {
  33498. var indices = [];
  33499. var positions = [];
  33500. var normals = [];
  33501. var uvs = [];
  33502. var diameter = options.diameter || 1;
  33503. var thickness = options.thickness || 0.5;
  33504. var tessellation = options.tessellation || 16;
  33505. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33506. var stride = tessellation + 1;
  33507. for (var i = 0; i <= tessellation; i++) {
  33508. var u = i / tessellation;
  33509. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33510. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33511. for (var j = 0; j <= tessellation; j++) {
  33512. var v = 1 - j / tessellation;
  33513. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33514. var dx = Math.cos(innerAngle);
  33515. var dy = Math.sin(innerAngle);
  33516. // Create a vertex.
  33517. var normal = new BABYLON.Vector3(dx, dy, 0);
  33518. var position = normal.scale(thickness / 2);
  33519. var textureCoordinate = new BABYLON.Vector2(u, v);
  33520. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33521. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33522. positions.push(position.x, position.y, position.z);
  33523. normals.push(normal.x, normal.y, normal.z);
  33524. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33525. // And create indices for two triangles.
  33526. var nextI = (i + 1) % stride;
  33527. var nextJ = (j + 1) % stride;
  33528. indices.push(i * stride + j);
  33529. indices.push(i * stride + nextJ);
  33530. indices.push(nextI * stride + j);
  33531. indices.push(i * stride + nextJ);
  33532. indices.push(nextI * stride + nextJ);
  33533. indices.push(nextI * stride + j);
  33534. }
  33535. }
  33536. // Sides
  33537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33538. // Result
  33539. var vertexData = new VertexData();
  33540. vertexData.indices = indices;
  33541. vertexData.positions = positions;
  33542. vertexData.normals = normals;
  33543. vertexData.uvs = uvs;
  33544. return vertexData;
  33545. };
  33546. /**
  33547. * Creates the VertexData of the LineSystem.
  33548. */
  33549. VertexData.CreateLineSystem = function (options) {
  33550. var indices = [];
  33551. var positions = [];
  33552. var lines = options.lines;
  33553. var colors = options.colors;
  33554. var vertexColors = [];
  33555. var idx = 0;
  33556. for (var l = 0; l < lines.length; l++) {
  33557. var points = lines[l];
  33558. for (var index = 0; index < points.length; index++) {
  33559. positions.push(points[index].x, points[index].y, points[index].z);
  33560. if (colors) {
  33561. var color = colors[l];
  33562. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33563. }
  33564. if (index > 0) {
  33565. indices.push(idx - 1);
  33566. indices.push(idx);
  33567. }
  33568. idx++;
  33569. }
  33570. }
  33571. var vertexData = new VertexData();
  33572. vertexData.indices = indices;
  33573. vertexData.positions = positions;
  33574. if (colors) {
  33575. vertexData.colors = vertexColors;
  33576. }
  33577. return vertexData;
  33578. };
  33579. /**
  33580. * Create the VertexData of the DashedLines.
  33581. */
  33582. VertexData.CreateDashedLines = function (options) {
  33583. var dashSize = options.dashSize || 3;
  33584. var gapSize = options.gapSize || 1;
  33585. var dashNb = options.dashNb || 200;
  33586. var points = options.points;
  33587. var positions = new Array();
  33588. var indices = new Array();
  33589. var curvect = BABYLON.Vector3.Zero();
  33590. var lg = 0;
  33591. var nb = 0;
  33592. var shft = 0;
  33593. var dashshft = 0;
  33594. var curshft = 0;
  33595. var idx = 0;
  33596. var i = 0;
  33597. for (i = 0; i < points.length - 1; i++) {
  33598. points[i + 1].subtractToRef(points[i], curvect);
  33599. lg += curvect.length();
  33600. }
  33601. shft = lg / dashNb;
  33602. dashshft = dashSize * shft / (dashSize + gapSize);
  33603. for (i = 0; i < points.length - 1; i++) {
  33604. points[i + 1].subtractToRef(points[i], curvect);
  33605. nb = Math.floor(curvect.length() / shft);
  33606. curvect.normalize();
  33607. for (var j = 0; j < nb; j++) {
  33608. curshft = shft * j;
  33609. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33610. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33611. indices.push(idx, idx + 1);
  33612. idx += 2;
  33613. }
  33614. }
  33615. // Result
  33616. var vertexData = new VertexData();
  33617. vertexData.positions = positions;
  33618. vertexData.indices = indices;
  33619. return vertexData;
  33620. };
  33621. /**
  33622. * Creates the VertexData of the Ground.
  33623. */
  33624. VertexData.CreateGround = function (options) {
  33625. var indices = [];
  33626. var positions = [];
  33627. var normals = [];
  33628. var uvs = [];
  33629. var row, col;
  33630. var width = options.width || 1;
  33631. var height = options.height || 1;
  33632. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33633. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33634. for (row = 0; row <= subdivisionsY; row++) {
  33635. for (col = 0; col <= subdivisionsX; col++) {
  33636. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33637. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33638. positions.push(position.x, position.y, position.z);
  33639. normals.push(normal.x, normal.y, normal.z);
  33640. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33641. }
  33642. }
  33643. for (row = 0; row < subdivisionsY; row++) {
  33644. for (col = 0; col < subdivisionsX; col++) {
  33645. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33646. indices.push(col + 1 + row * (subdivisionsX + 1));
  33647. indices.push(col + row * (subdivisionsX + 1));
  33648. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33649. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33650. indices.push(col + row * (subdivisionsX + 1));
  33651. }
  33652. }
  33653. // Result
  33654. var vertexData = new VertexData();
  33655. vertexData.indices = indices;
  33656. vertexData.positions = positions;
  33657. vertexData.normals = normals;
  33658. vertexData.uvs = uvs;
  33659. return vertexData;
  33660. };
  33661. /**
  33662. * Creates the VertexData of the TiledGround.
  33663. */
  33664. VertexData.CreateTiledGround = function (options) {
  33665. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33666. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33667. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33668. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33669. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33670. var precision = options.precision || { w: 1, h: 1 };
  33671. var indices = new Array();
  33672. var positions = new Array();
  33673. var normals = new Array();
  33674. var uvs = new Array();
  33675. var row, col, tileRow, tileCol;
  33676. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33677. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33678. precision.w = (precision.w < 1) ? 1 : precision.w;
  33679. precision.h = (precision.h < 1) ? 1 : precision.h;
  33680. var tileSize = {
  33681. 'w': (xmax - xmin) / subdivisions.w,
  33682. 'h': (zmax - zmin) / subdivisions.h
  33683. };
  33684. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33685. // Indices
  33686. var base = positions.length / 3;
  33687. var rowLength = precision.w + 1;
  33688. for (row = 0; row < precision.h; row++) {
  33689. for (col = 0; col < precision.w; col++) {
  33690. var square = [
  33691. base + col + row * rowLength,
  33692. base + (col + 1) + row * rowLength,
  33693. base + (col + 1) + (row + 1) * rowLength,
  33694. base + col + (row + 1) * rowLength
  33695. ];
  33696. indices.push(square[1]);
  33697. indices.push(square[2]);
  33698. indices.push(square[3]);
  33699. indices.push(square[0]);
  33700. indices.push(square[1]);
  33701. indices.push(square[3]);
  33702. }
  33703. }
  33704. // Position, normals and uvs
  33705. var position = BABYLON.Vector3.Zero();
  33706. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33707. for (row = 0; row <= precision.h; row++) {
  33708. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33709. for (col = 0; col <= precision.w; col++) {
  33710. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33711. position.y = 0;
  33712. positions.push(position.x, position.y, position.z);
  33713. normals.push(normal.x, normal.y, normal.z);
  33714. uvs.push(col / precision.w, row / precision.h);
  33715. }
  33716. }
  33717. }
  33718. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33719. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33720. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33721. }
  33722. }
  33723. // Result
  33724. var vertexData = new VertexData();
  33725. vertexData.indices = indices;
  33726. vertexData.positions = positions;
  33727. vertexData.normals = normals;
  33728. vertexData.uvs = uvs;
  33729. return vertexData;
  33730. };
  33731. /**
  33732. * Creates the VertexData of the Ground designed from a heightmap.
  33733. */
  33734. VertexData.CreateGroundFromHeightMap = function (options) {
  33735. var indices = [];
  33736. var positions = [];
  33737. var normals = [];
  33738. var uvs = [];
  33739. var row, col;
  33740. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33741. // Vertices
  33742. for (row = 0; row <= options.subdivisions; row++) {
  33743. for (col = 0; col <= options.subdivisions; col++) {
  33744. 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));
  33745. // Compute height
  33746. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33747. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33748. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33749. var r = options.buffer[pos] / 255.0;
  33750. var g = options.buffer[pos + 1] / 255.0;
  33751. var b = options.buffer[pos + 2] / 255.0;
  33752. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33753. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33754. // Add vertex
  33755. positions.push(position.x, position.y, position.z);
  33756. normals.push(0, 0, 0);
  33757. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33758. }
  33759. }
  33760. // Indices
  33761. for (row = 0; row < options.subdivisions; row++) {
  33762. for (col = 0; col < options.subdivisions; col++) {
  33763. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33764. indices.push(col + 1 + row * (options.subdivisions + 1));
  33765. indices.push(col + row * (options.subdivisions + 1));
  33766. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33767. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33768. indices.push(col + row * (options.subdivisions + 1));
  33769. }
  33770. }
  33771. // Normals
  33772. VertexData.ComputeNormals(positions, indices, normals);
  33773. // Result
  33774. var vertexData = new VertexData();
  33775. vertexData.indices = indices;
  33776. vertexData.positions = positions;
  33777. vertexData.normals = normals;
  33778. vertexData.uvs = uvs;
  33779. return vertexData;
  33780. };
  33781. /**
  33782. * Creates the VertexData of the Plane.
  33783. */
  33784. VertexData.CreatePlane = function (options) {
  33785. var indices = [];
  33786. var positions = [];
  33787. var normals = [];
  33788. var uvs = [];
  33789. var width = options.width || options.size || 1;
  33790. var height = options.height || options.size || 1;
  33791. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33792. // Vertices
  33793. var halfWidth = width / 2.0;
  33794. var halfHeight = height / 2.0;
  33795. positions.push(-halfWidth, -halfHeight, 0);
  33796. normals.push(0, 0, -1.0);
  33797. uvs.push(0.0, 0.0);
  33798. positions.push(halfWidth, -halfHeight, 0);
  33799. normals.push(0, 0, -1.0);
  33800. uvs.push(1.0, 0.0);
  33801. positions.push(halfWidth, halfHeight, 0);
  33802. normals.push(0, 0, -1.0);
  33803. uvs.push(1.0, 1.0);
  33804. positions.push(-halfWidth, halfHeight, 0);
  33805. normals.push(0, 0, -1.0);
  33806. uvs.push(0.0, 1.0);
  33807. // Indices
  33808. indices.push(0);
  33809. indices.push(1);
  33810. indices.push(2);
  33811. indices.push(0);
  33812. indices.push(2);
  33813. indices.push(3);
  33814. // Sides
  33815. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33816. // Result
  33817. var vertexData = new VertexData();
  33818. vertexData.indices = indices;
  33819. vertexData.positions = positions;
  33820. vertexData.normals = normals;
  33821. vertexData.uvs = uvs;
  33822. return vertexData;
  33823. };
  33824. /**
  33825. * Creates the VertexData of the Disc or regular Polygon.
  33826. */
  33827. VertexData.CreateDisc = function (options) {
  33828. var positions = new Array();
  33829. var indices = new Array();
  33830. var normals = new Array();
  33831. var uvs = new Array();
  33832. var radius = options.radius || 0.5;
  33833. var tessellation = options.tessellation || 64;
  33834. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33835. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33836. // positions and uvs
  33837. positions.push(0, 0, 0); // disc center first
  33838. uvs.push(0.5, 0.5);
  33839. var theta = Math.PI * 2 * arc;
  33840. var step = theta / tessellation;
  33841. for (var a = 0; a < theta; a += step) {
  33842. var x = Math.cos(a);
  33843. var y = Math.sin(a);
  33844. var u = (x + 1) / 2;
  33845. var v = (1 - y) / 2;
  33846. positions.push(radius * x, radius * y, 0);
  33847. uvs.push(u, v);
  33848. }
  33849. if (arc === 1) {
  33850. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33851. uvs.push(uvs[2], uvs[3]);
  33852. }
  33853. //indices
  33854. var vertexNb = positions.length / 3;
  33855. for (var i = 1; i < vertexNb - 1; i++) {
  33856. indices.push(i + 1, 0, i);
  33857. }
  33858. // result
  33859. VertexData.ComputeNormals(positions, indices, normals);
  33860. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33861. var vertexData = new VertexData();
  33862. vertexData.indices = indices;
  33863. vertexData.positions = positions;
  33864. vertexData.normals = normals;
  33865. vertexData.uvs = uvs;
  33866. return vertexData;
  33867. };
  33868. /**
  33869. * Re-creates the VertexData of the Polygon for sideOrientation.
  33870. */
  33871. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33872. var faceUV = fUV || new Array(3);
  33873. var faceColors = fColors;
  33874. var colors = [];
  33875. // default face colors and UV if undefined
  33876. for (var f = 0; f < 3; f++) {
  33877. if (faceUV[f] === undefined) {
  33878. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33879. }
  33880. if (faceColors && faceColors[f] === undefined) {
  33881. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33882. }
  33883. }
  33884. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33885. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33886. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33887. var indices = polygon.getIndices();
  33888. // set face colours and textures
  33889. var idx = 0;
  33890. var face = 0;
  33891. for (var index = 0; index < normals.length; index += 3) {
  33892. //Edge Face no. 1
  33893. if (Math.abs(normals[index + 1]) < 0.001) {
  33894. face = 1;
  33895. }
  33896. //Top Face no. 0
  33897. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33898. face = 0;
  33899. }
  33900. //Bottom Face no. 2
  33901. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33902. face = 2;
  33903. }
  33904. idx = index / 3;
  33905. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33906. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33907. if (faceColors) {
  33908. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33909. }
  33910. }
  33911. // sides
  33912. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33913. // Result
  33914. var vertexData = new VertexData();
  33915. vertexData.indices = indices;
  33916. vertexData.positions = positions;
  33917. vertexData.normals = normals;
  33918. vertexData.uvs = uvs;
  33919. if (faceColors) {
  33920. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33921. vertexData.colors = totalColors;
  33922. }
  33923. return vertexData;
  33924. };
  33925. /**
  33926. * Creates the VertexData of the IcoSphere.
  33927. */
  33928. VertexData.CreateIcoSphere = function (options) {
  33929. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33930. var radius = options.radius || 1;
  33931. var flat = (options.flat === undefined) ? true : options.flat;
  33932. var subdivisions = options.subdivisions || 4;
  33933. var radiusX = options.radiusX || radius;
  33934. var radiusY = options.radiusY || radius;
  33935. var radiusZ = options.radiusZ || radius;
  33936. var t = (1 + Math.sqrt(5)) / 2;
  33937. // 12 vertex x,y,z
  33938. var ico_vertices = [
  33939. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33940. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33941. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33942. ];
  33943. // index of 3 vertex makes a face of icopshere
  33944. var ico_indices = [
  33945. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33946. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33947. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33948. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33949. ];
  33950. // vertex for uv have aliased position, not for UV
  33951. var vertices_unalias_id = [
  33952. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33953. // vertex alias
  33954. 0,
  33955. 2,
  33956. 3,
  33957. 3,
  33958. 3,
  33959. 4,
  33960. 7,
  33961. 8,
  33962. 9,
  33963. 9,
  33964. 10,
  33965. 11 // 23: B + 12
  33966. ];
  33967. // uv as integer step (not pixels !)
  33968. var ico_vertexuv = [
  33969. 5, 1, 3, 1, 6, 4, 0, 0,
  33970. 5, 3, 4, 2, 2, 2, 4, 0,
  33971. 2, 0, 1, 1, 6, 0, 6, 2,
  33972. // vertex alias (for same vertex on different faces)
  33973. 0, 4,
  33974. 3, 3,
  33975. 4, 4,
  33976. 3, 1,
  33977. 4, 2,
  33978. 4, 4,
  33979. 0, 2,
  33980. 1, 1,
  33981. 2, 2,
  33982. 3, 3,
  33983. 1, 3,
  33984. 2, 4 // 23: B + 12
  33985. ];
  33986. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33987. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33988. // First island of uv mapping
  33989. // v = 4h 3+ 2
  33990. // v = 3h 9+ 4
  33991. // v = 2h 9+ 5 B
  33992. // v = 1h 9 1 0
  33993. // v = 0h 3 8 7 A
  33994. // u = 0 1 2 3 4 5 6 *a
  33995. // Second island of uv mapping
  33996. // v = 4h 0+ B+ 4+
  33997. // v = 3h A+ 2+
  33998. // v = 2h 7+ 6 3+
  33999. // v = 1h 8+ 3+
  34000. // v = 0h
  34001. // u = 0 1 2 3 4 5 6 *a
  34002. // Face layout on texture UV mapping
  34003. // ============
  34004. // \ 4 /\ 16 / ======
  34005. // \ / \ / /\ 11 /
  34006. // \/ 7 \/ / \ /
  34007. // ======= / 10 \/
  34008. // /\ 17 /\ =======
  34009. // / \ / \ \ 15 /\
  34010. // / 8 \/ 12 \ \ / \
  34011. // ============ \/ 6 \
  34012. // \ 18 /\ ============
  34013. // \ / \ \ 5 /\ 0 /
  34014. // \/ 13 \ \ / \ /
  34015. // ======= \/ 1 \/
  34016. // =============
  34017. // /\ 19 /\ 2 /\
  34018. // / \ / \ / \
  34019. // / 14 \/ 9 \/ 3 \
  34020. // ===================
  34021. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34022. var ustep = 138 / 1024;
  34023. var vstep = 239 / 1024;
  34024. var uoffset = 60 / 1024;
  34025. var voffset = 26 / 1024;
  34026. // Second island should have margin, not to touch the first island
  34027. // avoid any borderline artefact in pixel rounding
  34028. var island_u_offset = -40 / 1024;
  34029. var island_v_offset = +20 / 1024;
  34030. // face is either island 0 or 1 :
  34031. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34032. var island = [
  34033. 0, 0, 0, 0, 1,
  34034. 0, 0, 1, 1, 0,
  34035. 0, 0, 1, 1, 0,
  34036. 0, 1, 1, 1, 0 // 15 - 19
  34037. ];
  34038. var indices = new Array();
  34039. var positions = new Array();
  34040. var normals = new Array();
  34041. var uvs = new Array();
  34042. var current_indice = 0;
  34043. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34044. var face_vertex_pos = new Array(3);
  34045. var face_vertex_uv = new Array(3);
  34046. var v012;
  34047. for (v012 = 0; v012 < 3; v012++) {
  34048. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34049. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34050. }
  34051. // create all with normals
  34052. for (var face = 0; face < 20; face++) {
  34053. // 3 vertex per face
  34054. for (v012 = 0; v012 < 3; v012++) {
  34055. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34056. var v_id = ico_indices[3 * face + v012];
  34057. // vertex have 3D position (x,y,z)
  34058. 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]);
  34059. // Normalize to get normal, then scale to radius
  34060. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34061. // uv Coordinates from vertex ID
  34062. 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);
  34063. }
  34064. // Subdivide the face (interpolate pos, norm, uv)
  34065. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34066. // - norm is linear interpolation of vertex corner normal
  34067. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34068. // - uv is linear interpolation
  34069. //
  34070. // Topology is as below for sub-divide by 2
  34071. // vertex shown as v0,v1,v2
  34072. // interp index is i1 to progress in range [v0,v1[
  34073. // interp index is i2 to progress in range [v0,v2[
  34074. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34075. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34076. //
  34077. //
  34078. // i2 v2
  34079. // ^ ^
  34080. // / / \
  34081. // / / \
  34082. // / / \
  34083. // / / (0,1) \
  34084. // / #---------\
  34085. // / / \ (0,0)'/ \
  34086. // / / \ / \
  34087. // / / \ / \
  34088. // / / (0,0) \ / (1,0) \
  34089. // / #---------#---------\
  34090. // v0 v1
  34091. //
  34092. // --------------------> i1
  34093. //
  34094. // interp of (i1,i2):
  34095. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34096. // along i1 : lerp(x0,x1, i1/(S-i2))
  34097. //
  34098. // centroid of triangle is needed to get help normal computation
  34099. // (c1,c2) are used for centroid location
  34100. var interp_vertex = function (i1, i2, c1, c2) {
  34101. // vertex is interpolated from
  34102. // - face_vertex_pos[0..2]
  34103. // - face_vertex_uv[0..2]
  34104. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34105. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34106. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34107. pos_interp.normalize();
  34108. var vertex_normal;
  34109. if (flat) {
  34110. // in flat mode, recalculate normal as face centroid normal
  34111. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34112. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34113. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34114. }
  34115. else {
  34116. // in smooth mode, recalculate normal from each single vertex position
  34117. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34118. }
  34119. // Vertex normal need correction due to X,Y,Z radius scaling
  34120. vertex_normal.x /= radiusX;
  34121. vertex_normal.y /= radiusY;
  34122. vertex_normal.z /= radiusZ;
  34123. vertex_normal.normalize();
  34124. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34125. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34126. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34127. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34128. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34129. uvs.push(uv_interp.x, uv_interp.y);
  34130. // push each vertex has member of a face
  34131. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34132. indices.push(current_indice);
  34133. current_indice++;
  34134. };
  34135. for (var i2 = 0; i2 < subdivisions; i2++) {
  34136. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34137. // face : (i1,i2) for /\ :
  34138. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34139. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34140. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34141. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34142. if (i1 + i2 + 1 < subdivisions) {
  34143. // face : (i1,i2)' for \/ :
  34144. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34145. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34146. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34147. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34148. }
  34149. }
  34150. }
  34151. }
  34152. // Sides
  34153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34154. // Result
  34155. var vertexData = new VertexData();
  34156. vertexData.indices = indices;
  34157. vertexData.positions = positions;
  34158. vertexData.normals = normals;
  34159. vertexData.uvs = uvs;
  34160. return vertexData;
  34161. };
  34162. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34163. /**
  34164. * Creates the VertexData of the Polyhedron.
  34165. */
  34166. VertexData.CreatePolyhedron = function (options) {
  34167. // provided polyhedron types :
  34168. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34169. // 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)
  34170. var polyhedra = [];
  34171. 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]] };
  34172. 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]] };
  34173. polyhedra[2] = {
  34174. 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]],
  34175. 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]]
  34176. };
  34177. polyhedra[3] = {
  34178. 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]],
  34179. 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]]
  34180. };
  34181. polyhedra[4] = {
  34182. 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]],
  34183. 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]]
  34184. };
  34185. 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]] };
  34186. 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]] };
  34187. 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]] };
  34188. 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]] };
  34189. 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]] };
  34190. 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]] };
  34191. 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]] };
  34192. 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]] };
  34193. 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]] };
  34194. polyhedra[14] = {
  34195. 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]],
  34196. 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]]
  34197. };
  34198. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34199. var size = options.size;
  34200. var sizeX = options.sizeX || size || 1;
  34201. var sizeY = options.sizeY || size || 1;
  34202. var sizeZ = options.sizeZ || size || 1;
  34203. var data = options.custom || polyhedra[type];
  34204. var nbfaces = data.face.length;
  34205. var faceUV = options.faceUV || new Array(nbfaces);
  34206. var faceColors = options.faceColors;
  34207. var flat = (options.flat === undefined) ? true : options.flat;
  34208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34209. var positions = new Array();
  34210. var indices = new Array();
  34211. var normals = new Array();
  34212. var uvs = new Array();
  34213. var colors = new Array();
  34214. var index = 0;
  34215. var faceIdx = 0; // face cursor in the array "indexes"
  34216. var indexes = new Array();
  34217. var i = 0;
  34218. var f = 0;
  34219. var u, v, ang, x, y, tmp;
  34220. // default face colors and UV if undefined
  34221. if (flat) {
  34222. for (f = 0; f < nbfaces; f++) {
  34223. if (faceColors && faceColors[f] === undefined) {
  34224. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34225. }
  34226. if (faceUV && faceUV[f] === undefined) {
  34227. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34228. }
  34229. }
  34230. }
  34231. if (!flat) {
  34232. for (i = 0; i < data.vertex.length; i++) {
  34233. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34234. uvs.push(0, 0);
  34235. }
  34236. for (f = 0; f < nbfaces; f++) {
  34237. for (i = 0; i < data.face[f].length - 2; i++) {
  34238. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34239. }
  34240. }
  34241. }
  34242. else {
  34243. for (f = 0; f < nbfaces; f++) {
  34244. var fl = data.face[f].length; // number of vertices of the current face
  34245. ang = 2 * Math.PI / fl;
  34246. x = 0.5 * Math.tan(ang / 2);
  34247. y = 0.5;
  34248. // positions, uvs, colors
  34249. for (i = 0; i < fl; i++) {
  34250. // positions
  34251. 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);
  34252. indexes.push(index);
  34253. index++;
  34254. // uvs
  34255. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34256. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34257. uvs.push(u, v);
  34258. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34259. y = x * Math.sin(ang) + y * Math.cos(ang);
  34260. x = tmp;
  34261. // colors
  34262. if (faceColors) {
  34263. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34264. }
  34265. }
  34266. // indices from indexes
  34267. for (i = 0; i < fl - 2; i++) {
  34268. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34269. }
  34270. faceIdx += fl;
  34271. }
  34272. }
  34273. VertexData.ComputeNormals(positions, indices, normals);
  34274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34275. var vertexData = new VertexData();
  34276. vertexData.positions = positions;
  34277. vertexData.indices = indices;
  34278. vertexData.normals = normals;
  34279. vertexData.uvs = uvs;
  34280. if (faceColors && flat) {
  34281. vertexData.colors = colors;
  34282. }
  34283. return vertexData;
  34284. };
  34285. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34286. /**
  34287. * Creates the VertexData of the Torus Knot.
  34288. */
  34289. VertexData.CreateTorusKnot = function (options) {
  34290. var indices = new Array();
  34291. var positions = new Array();
  34292. var normals = new Array();
  34293. var uvs = new Array();
  34294. var radius = options.radius || 2;
  34295. var tube = options.tube || 0.5;
  34296. var radialSegments = options.radialSegments || 32;
  34297. var tubularSegments = options.tubularSegments || 32;
  34298. var p = options.p || 2;
  34299. var q = options.q || 3;
  34300. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34301. // Helper
  34302. var getPos = function (angle) {
  34303. var cu = Math.cos(angle);
  34304. var su = Math.sin(angle);
  34305. var quOverP = q / p * angle;
  34306. var cs = Math.cos(quOverP);
  34307. var tx = radius * (2 + cs) * 0.5 * cu;
  34308. var ty = radius * (2 + cs) * su * 0.5;
  34309. var tz = radius * Math.sin(quOverP) * 0.5;
  34310. return new BABYLON.Vector3(tx, ty, tz);
  34311. };
  34312. // Vertices
  34313. var i;
  34314. var j;
  34315. for (i = 0; i <= radialSegments; i++) {
  34316. var modI = i % radialSegments;
  34317. var u = modI / radialSegments * 2 * p * Math.PI;
  34318. var p1 = getPos(u);
  34319. var p2 = getPos(u + 0.01);
  34320. var tang = p2.subtract(p1);
  34321. var n = p2.add(p1);
  34322. var bitan = BABYLON.Vector3.Cross(tang, n);
  34323. n = BABYLON.Vector3.Cross(bitan, tang);
  34324. bitan.normalize();
  34325. n.normalize();
  34326. for (j = 0; j < tubularSegments; j++) {
  34327. var modJ = j % tubularSegments;
  34328. var v = modJ / tubularSegments * 2 * Math.PI;
  34329. var cx = -tube * Math.cos(v);
  34330. var cy = tube * Math.sin(v);
  34331. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34332. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34333. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34334. uvs.push(i / radialSegments);
  34335. uvs.push(j / tubularSegments);
  34336. }
  34337. }
  34338. for (i = 0; i < radialSegments; i++) {
  34339. for (j = 0; j < tubularSegments; j++) {
  34340. var jNext = (j + 1) % tubularSegments;
  34341. var a = i * tubularSegments + j;
  34342. var b = (i + 1) * tubularSegments + j;
  34343. var c = (i + 1) * tubularSegments + jNext;
  34344. var d = i * tubularSegments + jNext;
  34345. indices.push(d);
  34346. indices.push(b);
  34347. indices.push(a);
  34348. indices.push(d);
  34349. indices.push(c);
  34350. indices.push(b);
  34351. }
  34352. }
  34353. // Normals
  34354. VertexData.ComputeNormals(positions, indices, normals);
  34355. // Sides
  34356. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34357. // Result
  34358. var vertexData = new VertexData();
  34359. vertexData.indices = indices;
  34360. vertexData.positions = positions;
  34361. vertexData.normals = normals;
  34362. vertexData.uvs = uvs;
  34363. return vertexData;
  34364. };
  34365. // Tools
  34366. /**
  34367. * @param {any} - positions (number[] or Float32Array)
  34368. * @param {any} - indices (number[] or Uint16Array)
  34369. * @param {any} - normals (number[] or Float32Array)
  34370. * options (optional) :
  34371. * facetPositions : optional array of facet positions (vector3)
  34372. * facetNormals : optional array of facet normals (vector3)
  34373. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34374. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34375. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34376. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34377. * bInfo : optional bounding info, required for facetPartitioning computation
  34378. * useRightHandedSystem: optional boolean to for right handed system computation
  34379. * depthSort : optional boolean to enable the facet depth sort computation
  34380. * distanceTo : optional Vector3 to compute the facet depth from this location
  34381. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34382. */
  34383. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34384. // temporary scalar variables
  34385. var index = 0; // facet index
  34386. var p1p2x = 0.0; // p1p2 vector x coordinate
  34387. var p1p2y = 0.0; // p1p2 vector y coordinate
  34388. var p1p2z = 0.0; // p1p2 vector z coordinate
  34389. var p3p2x = 0.0; // p3p2 vector x coordinate
  34390. var p3p2y = 0.0; // p3p2 vector y coordinate
  34391. var p3p2z = 0.0; // p3p2 vector z coordinate
  34392. var faceNormalx = 0.0; // facet normal x coordinate
  34393. var faceNormaly = 0.0; // facet normal y coordinate
  34394. var faceNormalz = 0.0; // facet normal z coordinate
  34395. var length = 0.0; // facet normal length before normalization
  34396. var v1x = 0; // vector1 x index in the positions array
  34397. var v1y = 0; // vector1 y index in the positions array
  34398. var v1z = 0; // vector1 z index in the positions array
  34399. var v2x = 0; // vector2 x index in the positions array
  34400. var v2y = 0; // vector2 y index in the positions array
  34401. var v2z = 0; // vector2 z index in the positions array
  34402. var v3x = 0; // vector3 x index in the positions array
  34403. var v3y = 0; // vector3 y index in the positions array
  34404. var v3z = 0; // vector3 z index in the positions array
  34405. var computeFacetNormals = false;
  34406. var computeFacetPositions = false;
  34407. var computeFacetPartitioning = false;
  34408. var computeDepthSort = false;
  34409. var faceNormalSign = 1;
  34410. var ratio = 0;
  34411. var distanceTo = null;
  34412. if (options) {
  34413. computeFacetNormals = (options.facetNormals) ? true : false;
  34414. computeFacetPositions = (options.facetPositions) ? true : false;
  34415. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34416. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34417. ratio = options.ratio || 0;
  34418. computeDepthSort = (options.depthSort) ? true : false;
  34419. distanceTo = (options.distanceTo);
  34420. if (computeDepthSort) {
  34421. if (distanceTo === undefined) {
  34422. distanceTo = BABYLON.Vector3.Zero();
  34423. }
  34424. var depthSortedFacets = options.depthSortedFacets;
  34425. }
  34426. }
  34427. // facetPartitioning reinit if needed
  34428. var xSubRatio = 0;
  34429. var ySubRatio = 0;
  34430. var zSubRatio = 0;
  34431. var subSq = 0;
  34432. if (computeFacetPartitioning && options && options.bbSize) {
  34433. var ox = 0; // X partitioning index for facet position
  34434. var oy = 0; // Y partinioning index for facet position
  34435. var oz = 0; // Z partinioning index for facet position
  34436. var b1x = 0; // X partitioning index for facet v1 vertex
  34437. var b1y = 0; // Y partitioning index for facet v1 vertex
  34438. var b1z = 0; // z partitioning index for facet v1 vertex
  34439. var b2x = 0; // X partitioning index for facet v2 vertex
  34440. var b2y = 0; // Y partitioning index for facet v2 vertex
  34441. var b2z = 0; // Z partitioning index for facet v2 vertex
  34442. var b3x = 0; // X partitioning index for facet v3 vertex
  34443. var b3y = 0; // Y partitioning index for facet v3 vertex
  34444. var b3z = 0; // Z partitioning index for facet v3 vertex
  34445. var block_idx_o = 0; // facet barycenter block index
  34446. var block_idx_v1 = 0; // v1 vertex block index
  34447. var block_idx_v2 = 0; // v2 vertex block index
  34448. var block_idx_v3 = 0; // v3 vertex block index
  34449. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34450. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34451. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34452. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34453. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34454. subSq = options.subDiv.max * options.subDiv.max;
  34455. options.facetPartitioning.length = 0;
  34456. }
  34457. // reset the normals
  34458. for (index = 0; index < positions.length; index++) {
  34459. normals[index] = 0.0;
  34460. }
  34461. // Loop : 1 indice triplet = 1 facet
  34462. var nbFaces = (indices.length / 3) | 0;
  34463. for (index = 0; index < nbFaces; index++) {
  34464. // get the indexes of the coordinates of each vertex of the facet
  34465. v1x = indices[index * 3] * 3;
  34466. v1y = v1x + 1;
  34467. v1z = v1x + 2;
  34468. v2x = indices[index * 3 + 1] * 3;
  34469. v2y = v2x + 1;
  34470. v2z = v2x + 2;
  34471. v3x = indices[index * 3 + 2] * 3;
  34472. v3y = v3x + 1;
  34473. v3z = v3x + 2;
  34474. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34475. p1p2y = positions[v1y] - positions[v2y];
  34476. p1p2z = positions[v1z] - positions[v2z];
  34477. p3p2x = positions[v3x] - positions[v2x];
  34478. p3p2y = positions[v3y] - positions[v2y];
  34479. p3p2z = positions[v3z] - positions[v2z];
  34480. // compute the face normal with the cross product
  34481. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34482. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34483. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34484. // normalize this normal and store it in the array facetData
  34485. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34486. length = (length === 0) ? 1.0 : length;
  34487. faceNormalx /= length;
  34488. faceNormaly /= length;
  34489. faceNormalz /= length;
  34490. if (computeFacetNormals && options) {
  34491. options.facetNormals[index].x = faceNormalx;
  34492. options.facetNormals[index].y = faceNormaly;
  34493. options.facetNormals[index].z = faceNormalz;
  34494. }
  34495. if (computeFacetPositions && options) {
  34496. // compute and the facet barycenter coordinates in the array facetPositions
  34497. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34498. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34499. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34500. }
  34501. if (computeFacetPartitioning && options) {
  34502. // store the facet indexes in arrays in the main facetPartitioning array :
  34503. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34504. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34505. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34506. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34507. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34508. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34509. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34510. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34511. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34512. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34513. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34514. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34515. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34516. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34517. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34518. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34519. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34520. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34521. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34522. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34523. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34524. // push each facet index in each block containing the vertex
  34525. options.facetPartitioning[block_idx_v1].push(index);
  34526. if (block_idx_v2 != block_idx_v1) {
  34527. options.facetPartitioning[block_idx_v2].push(index);
  34528. }
  34529. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34530. options.facetPartitioning[block_idx_v3].push(index);
  34531. }
  34532. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34533. options.facetPartitioning[block_idx_o].push(index);
  34534. }
  34535. }
  34536. if (computeDepthSort && options && options.facetPositions) {
  34537. var dsf = depthSortedFacets[index];
  34538. dsf.ind = index * 3;
  34539. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34540. }
  34541. // compute the normals anyway
  34542. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34543. normals[v1y] += faceNormaly;
  34544. normals[v1z] += faceNormalz;
  34545. normals[v2x] += faceNormalx;
  34546. normals[v2y] += faceNormaly;
  34547. normals[v2z] += faceNormalz;
  34548. normals[v3x] += faceNormalx;
  34549. normals[v3y] += faceNormaly;
  34550. normals[v3z] += faceNormalz;
  34551. }
  34552. // last normalization of each normal
  34553. for (index = 0; index < normals.length / 3; index++) {
  34554. faceNormalx = normals[index * 3];
  34555. faceNormaly = normals[index * 3 + 1];
  34556. faceNormalz = normals[index * 3 + 2];
  34557. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34558. length = (length === 0) ? 1.0 : length;
  34559. faceNormalx /= length;
  34560. faceNormaly /= length;
  34561. faceNormalz /= length;
  34562. normals[index * 3] = faceNormalx;
  34563. normals[index * 3 + 1] = faceNormaly;
  34564. normals[index * 3 + 2] = faceNormalz;
  34565. }
  34566. };
  34567. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34568. var li = indices.length;
  34569. var ln = normals.length;
  34570. var i;
  34571. var n;
  34572. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34573. switch (sideOrientation) {
  34574. case BABYLON.Mesh.FRONTSIDE:
  34575. // nothing changed
  34576. break;
  34577. case BABYLON.Mesh.BACKSIDE:
  34578. var tmp;
  34579. // indices
  34580. for (i = 0; i < li; i += 3) {
  34581. tmp = indices[i];
  34582. indices[i] = indices[i + 2];
  34583. indices[i + 2] = tmp;
  34584. }
  34585. // normals
  34586. for (n = 0; n < ln; n++) {
  34587. normals[n] = -normals[n];
  34588. }
  34589. break;
  34590. case BABYLON.Mesh.DOUBLESIDE:
  34591. // positions
  34592. var lp = positions.length;
  34593. var l = lp / 3;
  34594. for (var p = 0; p < lp; p++) {
  34595. positions[lp + p] = positions[p];
  34596. }
  34597. // indices
  34598. for (i = 0; i < li; i += 3) {
  34599. indices[i + li] = indices[i + 2] + l;
  34600. indices[i + 1 + li] = indices[i + 1] + l;
  34601. indices[i + 2 + li] = indices[i] + l;
  34602. }
  34603. // normals
  34604. for (n = 0; n < ln; n++) {
  34605. normals[ln + n] = -normals[n];
  34606. }
  34607. // uvs
  34608. var lu = uvs.length;
  34609. var u = 0;
  34610. for (u = 0; u < lu; u++) {
  34611. uvs[u + lu] = uvs[u];
  34612. }
  34613. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34614. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34615. u = 0;
  34616. for (i = 0; i < lu / 2; i++) {
  34617. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34618. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34619. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34620. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34621. u += 2;
  34622. }
  34623. break;
  34624. }
  34625. };
  34626. /**
  34627. * Creates a new VertexData from the imported parameters.
  34628. */
  34629. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34630. var vertexData = new VertexData();
  34631. // positions
  34632. var positions = parsedVertexData.positions;
  34633. if (positions) {
  34634. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34635. }
  34636. // normals
  34637. var normals = parsedVertexData.normals;
  34638. if (normals) {
  34639. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34640. }
  34641. // tangents
  34642. var tangents = parsedVertexData.tangents;
  34643. if (tangents) {
  34644. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34645. }
  34646. // uvs
  34647. var uvs = parsedVertexData.uvs;
  34648. if (uvs) {
  34649. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34650. }
  34651. // uv2s
  34652. var uv2s = parsedVertexData.uv2s;
  34653. if (uv2s) {
  34654. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34655. }
  34656. // uv3s
  34657. var uv3s = parsedVertexData.uv3s;
  34658. if (uv3s) {
  34659. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34660. }
  34661. // uv4s
  34662. var uv4s = parsedVertexData.uv4s;
  34663. if (uv4s) {
  34664. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34665. }
  34666. // uv5s
  34667. var uv5s = parsedVertexData.uv5s;
  34668. if (uv5s) {
  34669. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34670. }
  34671. // uv6s
  34672. var uv6s = parsedVertexData.uv6s;
  34673. if (uv6s) {
  34674. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34675. }
  34676. // colors
  34677. var colors = parsedVertexData.colors;
  34678. if (colors) {
  34679. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34680. }
  34681. // matricesIndices
  34682. var matricesIndices = parsedVertexData.matricesIndices;
  34683. if (matricesIndices) {
  34684. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34685. }
  34686. // matricesWeights
  34687. var matricesWeights = parsedVertexData.matricesWeights;
  34688. if (matricesWeights) {
  34689. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34690. }
  34691. // indices
  34692. var indices = parsedVertexData.indices;
  34693. if (indices) {
  34694. vertexData.indices = indices;
  34695. }
  34696. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34697. };
  34698. return VertexData;
  34699. }());
  34700. BABYLON.VertexData = VertexData;
  34701. })(BABYLON || (BABYLON = {}));
  34702. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34703. var BABYLON;
  34704. (function (BABYLON) {
  34705. /**
  34706. * Class used to store geometry data (vertex buffers + index buffer)
  34707. */
  34708. var Geometry = /** @class */ (function () {
  34709. /**
  34710. * Creates a new geometry
  34711. * @param id defines the unique ID
  34712. * @param scene defines the hosting scene
  34713. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34714. * @param updatable defines if geometry must be updatable (false by default)
  34715. * @param mesh defines the mesh that will be associated with the geometry
  34716. */
  34717. function Geometry(id, scene, vertexData, updatable, mesh) {
  34718. if (updatable === void 0) { updatable = false; }
  34719. if (mesh === void 0) { mesh = null; }
  34720. /**
  34721. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34722. */
  34723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34724. this._totalVertices = 0;
  34725. this._isDisposed = false;
  34726. this._indexBufferIsUpdatable = false;
  34727. this.id = id;
  34728. this._engine = scene.getEngine();
  34729. this._meshes = [];
  34730. this._scene = scene;
  34731. //Init vertex buffer cache
  34732. this._vertexBuffers = {};
  34733. this._indices = [];
  34734. this._updatable = updatable;
  34735. // vertexData
  34736. if (vertexData) {
  34737. this.setAllVerticesData(vertexData, updatable);
  34738. }
  34739. else {
  34740. this._totalVertices = 0;
  34741. this._indices = [];
  34742. }
  34743. if (this._engine.getCaps().vertexArrayObject) {
  34744. this._vertexArrayObjects = {};
  34745. }
  34746. // applyToMesh
  34747. if (mesh) {
  34748. if (mesh.getClassName() === "LinesMesh") {
  34749. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34750. this.updateExtend();
  34751. }
  34752. this.applyToMesh(mesh);
  34753. mesh.computeWorldMatrix(true);
  34754. }
  34755. }
  34756. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34757. /**
  34758. * 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
  34759. */
  34760. get: function () {
  34761. return this._boundingBias;
  34762. },
  34763. /**
  34764. * 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
  34765. */
  34766. set: function (value) {
  34767. if (this._boundingBias && this._boundingBias.equals(value)) {
  34768. return;
  34769. }
  34770. this._boundingBias = value.clone();
  34771. this.updateBoundingInfo(true, null);
  34772. },
  34773. enumerable: true,
  34774. configurable: true
  34775. });
  34776. /**
  34777. * Static function used to attach a new empty geometry to a mesh
  34778. * @param mesh defines the mesh to attach the geometry to
  34779. * @returns the new {BABYLON.Geometry}
  34780. */
  34781. Geometry.CreateGeometryForMesh = function (mesh) {
  34782. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34783. geometry.applyToMesh(mesh);
  34784. return geometry;
  34785. };
  34786. Object.defineProperty(Geometry.prototype, "extend", {
  34787. /**
  34788. * Gets the current extend of the geometry
  34789. */
  34790. get: function () {
  34791. return this._extend;
  34792. },
  34793. enumerable: true,
  34794. configurable: true
  34795. });
  34796. /**
  34797. * Gets the hosting scene
  34798. * @returns the hosting {BABYLON.Scene}
  34799. */
  34800. Geometry.prototype.getScene = function () {
  34801. return this._scene;
  34802. };
  34803. /**
  34804. * Gets the hosting engine
  34805. * @returns the hosting {BABYLON.Engine}
  34806. */
  34807. Geometry.prototype.getEngine = function () {
  34808. return this._engine;
  34809. };
  34810. /**
  34811. * Defines if the geometry is ready to use
  34812. * @returns true if the geometry is ready to be used
  34813. */
  34814. Geometry.prototype.isReady = function () {
  34815. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34816. };
  34817. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34818. /**
  34819. * Gets a value indicating that the geometry should not be serialized
  34820. */
  34821. get: function () {
  34822. for (var index = 0; index < this._meshes.length; index++) {
  34823. if (!this._meshes[index].doNotSerialize) {
  34824. return false;
  34825. }
  34826. }
  34827. return true;
  34828. },
  34829. enumerable: true,
  34830. configurable: true
  34831. });
  34832. /** @ignore */
  34833. Geometry.prototype._rebuild = function () {
  34834. if (this._vertexArrayObjects) {
  34835. this._vertexArrayObjects = {};
  34836. }
  34837. // Index buffer
  34838. if (this._meshes.length !== 0 && this._indices) {
  34839. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34840. }
  34841. // Vertex buffers
  34842. for (var key in this._vertexBuffers) {
  34843. var vertexBuffer = this._vertexBuffers[key];
  34844. vertexBuffer._rebuild();
  34845. }
  34846. };
  34847. /**
  34848. * Affects all gemetry data in one call
  34849. * @param vertexData defines the geometry data
  34850. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34851. */
  34852. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34853. vertexData.applyToGeometry(this, updatable);
  34854. this.notifyUpdate();
  34855. };
  34856. /**
  34857. * Set specific vertex data
  34858. * @param kind defines the data kind (Position, normal, etc...)
  34859. * @param data defines the vertex data to use
  34860. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34861. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34862. */
  34863. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34864. if (updatable === void 0) { updatable = false; }
  34865. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34866. this.setVerticesBuffer(buffer);
  34867. };
  34868. /**
  34869. * Removes a specific vertex data
  34870. * @param kind defines the data kind (Position, normal, etc...)
  34871. */
  34872. Geometry.prototype.removeVerticesData = function (kind) {
  34873. if (this._vertexBuffers[kind]) {
  34874. this._vertexBuffers[kind].dispose();
  34875. delete this._vertexBuffers[kind];
  34876. }
  34877. };
  34878. /**
  34879. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34880. * @param buffer defines the vertex buffer to use
  34881. */
  34882. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34883. var kind = buffer.getKind();
  34884. if (this._vertexBuffers[kind]) {
  34885. this._vertexBuffers[kind].dispose();
  34886. }
  34887. this._vertexBuffers[kind] = buffer;
  34888. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34889. var data = buffer.getData();
  34890. var stride = buffer.getStrideSize();
  34891. this._totalVertices = data.length / stride;
  34892. this.updateExtend(data, stride);
  34893. this._resetPointsArrayCache();
  34894. var meshes = this._meshes;
  34895. var numOfMeshes = meshes.length;
  34896. for (var index = 0; index < numOfMeshes; index++) {
  34897. var mesh = meshes[index];
  34898. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34899. mesh._createGlobalSubMesh(false);
  34900. mesh.computeWorldMatrix(true);
  34901. }
  34902. }
  34903. this.notifyUpdate(kind);
  34904. if (this._vertexArrayObjects) {
  34905. this._disposeVertexArrayObjects();
  34906. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34907. }
  34908. };
  34909. /**
  34910. * Update a specific vertex buffer
  34911. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34912. * It will do nothing if the buffer is not updatable
  34913. * @param kind defines the data kind (Position, normal, etc...)
  34914. * @param data defines the data to use
  34915. * @param offset defines the offset in the target buffer where to store the data
  34916. */
  34917. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34918. var vertexBuffer = this.getVertexBuffer(kind);
  34919. if (!vertexBuffer) {
  34920. return;
  34921. }
  34922. vertexBuffer.updateDirectly(data, offset);
  34923. this.notifyUpdate(kind);
  34924. };
  34925. /**
  34926. * Update a specific vertex buffer
  34927. * This function will create a new buffer if the current one is not updatable
  34928. * @param kind defines the data kind (Position, normal, etc...)
  34929. * @param data defines the data to use
  34930. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34931. */
  34932. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34933. if (updateExtends === void 0) { updateExtends = false; }
  34934. var vertexBuffer = this.getVertexBuffer(kind);
  34935. if (!vertexBuffer) {
  34936. return;
  34937. }
  34938. vertexBuffer.update(data);
  34939. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34940. var stride = vertexBuffer.getStrideSize();
  34941. this._totalVertices = data.length / stride;
  34942. this.updateBoundingInfo(updateExtends, data);
  34943. }
  34944. this.notifyUpdate(kind);
  34945. };
  34946. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34947. if (updateExtends) {
  34948. this.updateExtend(data);
  34949. }
  34950. var meshes = this._meshes;
  34951. var numOfMeshes = meshes.length;
  34952. this._resetPointsArrayCache();
  34953. for (var index = 0; index < numOfMeshes; index++) {
  34954. var mesh = meshes[index];
  34955. if (updateExtends) {
  34956. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34957. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34958. var subMesh = mesh.subMeshes[subIndex];
  34959. subMesh.refreshBoundingInfo();
  34960. }
  34961. }
  34962. }
  34963. };
  34964. /** @ignore */
  34965. Geometry.prototype._bind = function (effect, indexToBind) {
  34966. if (!effect) {
  34967. return;
  34968. }
  34969. if (indexToBind === undefined) {
  34970. indexToBind = this._indexBuffer;
  34971. }
  34972. var vbs = this.getVertexBuffers();
  34973. if (!vbs) {
  34974. return;
  34975. }
  34976. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34977. this._engine.bindBuffers(vbs, indexToBind, effect);
  34978. return;
  34979. }
  34980. // Using VAO
  34981. if (!this._vertexArrayObjects[effect.key]) {
  34982. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34983. }
  34984. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34985. };
  34986. /**
  34987. * Gets total number of vertices
  34988. * @returns the total number of vertices
  34989. */
  34990. Geometry.prototype.getTotalVertices = function () {
  34991. if (!this.isReady()) {
  34992. return 0;
  34993. }
  34994. return this._totalVertices;
  34995. };
  34996. /**
  34997. * Gets a specific vertex data attached to this geometry
  34998. * @param kind defines the data kind (Position, normal, etc...)
  34999. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35000. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35001. * @returns a float array containing vertex data
  35002. */
  35003. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35004. var vertexBuffer = this.getVertexBuffer(kind);
  35005. if (!vertexBuffer) {
  35006. return null;
  35007. }
  35008. var orig = vertexBuffer.getData();
  35009. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35010. return orig;
  35011. }
  35012. else {
  35013. var len = orig.length;
  35014. var copy = [];
  35015. for (var i = 0; i < len; i++) {
  35016. copy.push(orig[i]);
  35017. }
  35018. return copy;
  35019. }
  35020. };
  35021. /**
  35022. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35023. * @param kind defines the data kind (Position, normal, etc...)
  35024. * @returns true if the vertex buffer with the specified kind is updatable
  35025. */
  35026. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35027. var vb = this._vertexBuffers[kind];
  35028. if (!vb) {
  35029. return false;
  35030. }
  35031. return vb.isUpdatable();
  35032. };
  35033. /**
  35034. * Gets a specific vertex buffer
  35035. * @param kind defines the data kind (Position, normal, etc...)
  35036. * @returns a {BABYLON.VertexBuffer}
  35037. */
  35038. Geometry.prototype.getVertexBuffer = function (kind) {
  35039. if (!this.isReady()) {
  35040. return null;
  35041. }
  35042. return this._vertexBuffers[kind];
  35043. };
  35044. /**
  35045. * Returns all vertex buffers
  35046. * @return an object holding all vertex buffers indexed by kind
  35047. */
  35048. Geometry.prototype.getVertexBuffers = function () {
  35049. if (!this.isReady()) {
  35050. return null;
  35051. }
  35052. return this._vertexBuffers;
  35053. };
  35054. /**
  35055. * Gets a boolean indicating if specific vertex buffer is present
  35056. * @param kind defines the data kind (Position, normal, etc...)
  35057. * @returns true if data is present
  35058. */
  35059. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35060. if (!this._vertexBuffers) {
  35061. if (this._delayInfo) {
  35062. return this._delayInfo.indexOf(kind) !== -1;
  35063. }
  35064. return false;
  35065. }
  35066. return this._vertexBuffers[kind] !== undefined;
  35067. };
  35068. /**
  35069. * Gets a list of all attached data kinds (Position, normal, etc...)
  35070. * @returns a list of string containing all kinds
  35071. */
  35072. Geometry.prototype.getVerticesDataKinds = function () {
  35073. var result = [];
  35074. var kind;
  35075. if (!this._vertexBuffers && this._delayInfo) {
  35076. for (kind in this._delayInfo) {
  35077. result.push(kind);
  35078. }
  35079. }
  35080. else {
  35081. for (kind in this._vertexBuffers) {
  35082. result.push(kind);
  35083. }
  35084. }
  35085. return result;
  35086. };
  35087. /**
  35088. * Update index buffer
  35089. * @param indices defines the indices to store in the index buffer
  35090. * @param offset defines the offset in the target buffer where to store the data
  35091. */
  35092. Geometry.prototype.updateIndices = function (indices, offset) {
  35093. if (!this._indexBuffer) {
  35094. return;
  35095. }
  35096. if (!this._indexBufferIsUpdatable) {
  35097. this.setIndices(indices, null, true);
  35098. }
  35099. else {
  35100. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35101. }
  35102. };
  35103. /**
  35104. * Creates a new index buffer
  35105. * @param indices defines the indices to store in the index buffer
  35106. * @param totalVertices defines the total number of vertices (could be null)
  35107. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35108. */
  35109. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35110. if (totalVertices === void 0) { totalVertices = null; }
  35111. if (updatable === void 0) { updatable = false; }
  35112. if (this._indexBuffer) {
  35113. this._engine._releaseBuffer(this._indexBuffer);
  35114. }
  35115. this._disposeVertexArrayObjects();
  35116. this._indices = indices;
  35117. this._indexBufferIsUpdatable = updatable;
  35118. if (this._meshes.length !== 0 && this._indices) {
  35119. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35120. }
  35121. if (totalVertices != undefined) {
  35122. this._totalVertices = totalVertices;
  35123. }
  35124. var meshes = this._meshes;
  35125. var numOfMeshes = meshes.length;
  35126. for (var index = 0; index < numOfMeshes; index++) {
  35127. meshes[index]._createGlobalSubMesh(true);
  35128. }
  35129. this.notifyUpdate();
  35130. };
  35131. /**
  35132. * Return the total number of indices
  35133. * @returns the total number of indices
  35134. */
  35135. Geometry.prototype.getTotalIndices = function () {
  35136. if (!this.isReady()) {
  35137. return 0;
  35138. }
  35139. return this._indices.length;
  35140. };
  35141. /**
  35142. * Gets the index buffer array
  35143. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35144. * @returns the index buffer array
  35145. */
  35146. Geometry.prototype.getIndices = function (copyWhenShared) {
  35147. if (!this.isReady()) {
  35148. return null;
  35149. }
  35150. var orig = this._indices;
  35151. if (!copyWhenShared || this._meshes.length === 1) {
  35152. return orig;
  35153. }
  35154. else {
  35155. var len = orig.length;
  35156. var copy = [];
  35157. for (var i = 0; i < len; i++) {
  35158. copy.push(orig[i]);
  35159. }
  35160. return copy;
  35161. }
  35162. };
  35163. /**
  35164. * Gets the index buffer
  35165. * @return the index buffer
  35166. */
  35167. Geometry.prototype.getIndexBuffer = function () {
  35168. if (!this.isReady()) {
  35169. return null;
  35170. }
  35171. return this._indexBuffer;
  35172. };
  35173. /** @ignore */
  35174. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35175. if (effect === void 0) { effect = null; }
  35176. if (!effect || !this._vertexArrayObjects) {
  35177. return;
  35178. }
  35179. if (this._vertexArrayObjects[effect.key]) {
  35180. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35181. delete this._vertexArrayObjects[effect.key];
  35182. }
  35183. };
  35184. /**
  35185. * Release the associated resources for a specific mesh
  35186. * @param mesh defines the source mesh
  35187. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35188. */
  35189. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35190. var meshes = this._meshes;
  35191. var index = meshes.indexOf(mesh);
  35192. if (index === -1) {
  35193. return;
  35194. }
  35195. meshes.splice(index, 1);
  35196. mesh._geometry = null;
  35197. if (meshes.length === 0 && shouldDispose) {
  35198. this.dispose();
  35199. }
  35200. };
  35201. /**
  35202. * Apply current geometry to a given mesh
  35203. * @param mesh defines the mesh to apply geometry to
  35204. */
  35205. Geometry.prototype.applyToMesh = function (mesh) {
  35206. if (mesh._geometry === this) {
  35207. return;
  35208. }
  35209. var previousGeometry = mesh._geometry;
  35210. if (previousGeometry) {
  35211. previousGeometry.releaseForMesh(mesh);
  35212. }
  35213. var meshes = this._meshes;
  35214. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35215. mesh._geometry = this;
  35216. this._scene.pushGeometry(this);
  35217. meshes.push(mesh);
  35218. if (this.isReady()) {
  35219. this._applyToMesh(mesh);
  35220. }
  35221. else {
  35222. mesh._boundingInfo = this._boundingInfo;
  35223. }
  35224. };
  35225. Geometry.prototype.updateExtend = function (data, stride) {
  35226. if (data === void 0) { data = null; }
  35227. if (!data) {
  35228. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35229. }
  35230. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35231. };
  35232. Geometry.prototype._applyToMesh = function (mesh) {
  35233. var numOfMeshes = this._meshes.length;
  35234. // vertexBuffers
  35235. for (var kind in this._vertexBuffers) {
  35236. if (numOfMeshes === 1) {
  35237. this._vertexBuffers[kind].create();
  35238. }
  35239. var buffer = this._vertexBuffers[kind].getBuffer();
  35240. if (buffer)
  35241. buffer.references = numOfMeshes;
  35242. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35243. if (!this._extend) {
  35244. this.updateExtend(this._vertexBuffers[kind].getData());
  35245. }
  35246. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35247. mesh._createGlobalSubMesh(false);
  35248. //bounding info was just created again, world matrix should be applied again.
  35249. mesh._updateBoundingInfo();
  35250. }
  35251. }
  35252. // indexBuffer
  35253. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35254. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35255. }
  35256. if (this._indexBuffer) {
  35257. this._indexBuffer.references = numOfMeshes;
  35258. }
  35259. };
  35260. Geometry.prototype.notifyUpdate = function (kind) {
  35261. if (this.onGeometryUpdated) {
  35262. this.onGeometryUpdated(this, kind);
  35263. }
  35264. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35265. var mesh = _a[_i];
  35266. mesh._markSubMeshesAsAttributesDirty();
  35267. }
  35268. };
  35269. /**
  35270. * Load the geometry if it was flagged as delay loaded
  35271. * @param scene defines the hosting scene
  35272. * @param onLoaded defines a callback called when the geometry is loaded
  35273. */
  35274. Geometry.prototype.load = function (scene, onLoaded) {
  35275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35276. return;
  35277. }
  35278. if (this.isReady()) {
  35279. if (onLoaded) {
  35280. onLoaded();
  35281. }
  35282. return;
  35283. }
  35284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35285. this._queueLoad(scene, onLoaded);
  35286. };
  35287. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35288. var _this = this;
  35289. if (!this.delayLoadingFile) {
  35290. return;
  35291. }
  35292. scene._addPendingData(this);
  35293. scene._loadFile(this.delayLoadingFile, function (data) {
  35294. if (!_this._delayLoadingFunction) {
  35295. return;
  35296. }
  35297. _this._delayLoadingFunction(JSON.parse(data), _this);
  35298. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35299. _this._delayInfo = [];
  35300. scene._removePendingData(_this);
  35301. var meshes = _this._meshes;
  35302. var numOfMeshes = meshes.length;
  35303. for (var index = 0; index < numOfMeshes; index++) {
  35304. _this._applyToMesh(meshes[index]);
  35305. }
  35306. if (onLoaded) {
  35307. onLoaded();
  35308. }
  35309. }, undefined, true);
  35310. };
  35311. /**
  35312. * Invert the geometry to move from a right handed system to a left handed one.
  35313. */
  35314. Geometry.prototype.toLeftHanded = function () {
  35315. // Flip faces
  35316. var tIndices = this.getIndices(false);
  35317. if (tIndices != null && tIndices.length > 0) {
  35318. for (var i = 0; i < tIndices.length; i += 3) {
  35319. var tTemp = tIndices[i + 0];
  35320. tIndices[i + 0] = tIndices[i + 2];
  35321. tIndices[i + 2] = tTemp;
  35322. }
  35323. this.setIndices(tIndices);
  35324. }
  35325. // Negate position.z
  35326. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35327. if (tPositions != null && tPositions.length > 0) {
  35328. for (var i = 0; i < tPositions.length; i += 3) {
  35329. tPositions[i + 2] = -tPositions[i + 2];
  35330. }
  35331. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35332. }
  35333. // Negate normal.z
  35334. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35335. if (tNormals != null && tNormals.length > 0) {
  35336. for (var i = 0; i < tNormals.length; i += 3) {
  35337. tNormals[i + 2] = -tNormals[i + 2];
  35338. }
  35339. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35340. }
  35341. };
  35342. // Cache
  35343. /** @ignore */
  35344. Geometry.prototype._resetPointsArrayCache = function () {
  35345. this._positions = null;
  35346. };
  35347. /** @ignore */
  35348. Geometry.prototype._generatePointsArray = function () {
  35349. if (this._positions)
  35350. return true;
  35351. this._positions = [];
  35352. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35353. if (!data) {
  35354. return false;
  35355. }
  35356. for (var index = 0; index < data.length; index += 3) {
  35357. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35358. }
  35359. return true;
  35360. };
  35361. /**
  35362. * Gets a value indicating if the geometry is disposed
  35363. * @returns true if the geometry was disposed
  35364. */
  35365. Geometry.prototype.isDisposed = function () {
  35366. return this._isDisposed;
  35367. };
  35368. Geometry.prototype._disposeVertexArrayObjects = function () {
  35369. if (this._vertexArrayObjects) {
  35370. for (var kind in this._vertexArrayObjects) {
  35371. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35372. }
  35373. this._vertexArrayObjects = {};
  35374. }
  35375. };
  35376. /**
  35377. * Free all associated resources
  35378. */
  35379. Geometry.prototype.dispose = function () {
  35380. var meshes = this._meshes;
  35381. var numOfMeshes = meshes.length;
  35382. var index;
  35383. for (index = 0; index < numOfMeshes; index++) {
  35384. this.releaseForMesh(meshes[index]);
  35385. }
  35386. this._meshes = [];
  35387. this._disposeVertexArrayObjects();
  35388. for (var kind in this._vertexBuffers) {
  35389. this._vertexBuffers[kind].dispose();
  35390. }
  35391. this._vertexBuffers = {};
  35392. this._totalVertices = 0;
  35393. if (this._indexBuffer) {
  35394. this._engine._releaseBuffer(this._indexBuffer);
  35395. }
  35396. this._indexBuffer = null;
  35397. this._indices = [];
  35398. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35399. this.delayLoadingFile = null;
  35400. this._delayLoadingFunction = null;
  35401. this._delayInfo = [];
  35402. this._boundingInfo = null;
  35403. this._scene.removeGeometry(this);
  35404. this._isDisposed = true;
  35405. };
  35406. /**
  35407. * Clone the current geometry into a new geometry
  35408. * @param id defines the unique ID of the new geometry
  35409. * @returns a new geometry object
  35410. */
  35411. Geometry.prototype.copy = function (id) {
  35412. var vertexData = new BABYLON.VertexData();
  35413. vertexData.indices = [];
  35414. var indices = this.getIndices();
  35415. if (indices) {
  35416. for (var index = 0; index < indices.length; index++) {
  35417. vertexData.indices.push(indices[index]);
  35418. }
  35419. }
  35420. var updatable = false;
  35421. var stopChecking = false;
  35422. var kind;
  35423. for (kind in this._vertexBuffers) {
  35424. // using slice() to make a copy of the array and not just reference it
  35425. var data = this.getVerticesData(kind);
  35426. if (data instanceof Float32Array) {
  35427. vertexData.set(new Float32Array(data), kind);
  35428. }
  35429. else {
  35430. vertexData.set(data.slice(0), kind);
  35431. }
  35432. if (!stopChecking) {
  35433. var vb = this.getVertexBuffer(kind);
  35434. if (vb) {
  35435. updatable = vb.isUpdatable();
  35436. stopChecking = !updatable;
  35437. }
  35438. }
  35439. }
  35440. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35441. geometry.delayLoadState = this.delayLoadState;
  35442. geometry.delayLoadingFile = this.delayLoadingFile;
  35443. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35444. for (kind in this._delayInfo) {
  35445. geometry._delayInfo = geometry._delayInfo || [];
  35446. geometry._delayInfo.push(kind);
  35447. }
  35448. // Bounding info
  35449. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35450. return geometry;
  35451. };
  35452. /**
  35453. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35454. * @return a JSON representation of the current geometry data (without the vertices data)
  35455. */
  35456. Geometry.prototype.serialize = function () {
  35457. var serializationObject = {};
  35458. serializationObject.id = this.id;
  35459. serializationObject.updatable = this._updatable;
  35460. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35461. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35462. }
  35463. return serializationObject;
  35464. };
  35465. Geometry.prototype.toNumberArray = function (origin) {
  35466. if (Array.isArray(origin)) {
  35467. return origin;
  35468. }
  35469. else {
  35470. return Array.prototype.slice.call(origin);
  35471. }
  35472. };
  35473. /**
  35474. * Serialize all vertices data into a JSON oject
  35475. * @returns a JSON representation of the current geometry data
  35476. */
  35477. Geometry.prototype.serializeVerticeData = function () {
  35478. var serializationObject = this.serialize();
  35479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35480. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35481. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35482. serializationObject.positions._updatable = true;
  35483. }
  35484. }
  35485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35486. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35487. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35488. serializationObject.normals._updatable = true;
  35489. }
  35490. }
  35491. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35492. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35493. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35494. serializationObject.tangets._updatable = true;
  35495. }
  35496. }
  35497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35498. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35499. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35500. serializationObject.uvs._updatable = true;
  35501. }
  35502. }
  35503. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35504. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35505. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35506. serializationObject.uv2s._updatable = true;
  35507. }
  35508. }
  35509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35510. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35511. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35512. serializationObject.uv3s._updatable = true;
  35513. }
  35514. }
  35515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35516. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35517. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35518. serializationObject.uv4s._updatable = true;
  35519. }
  35520. }
  35521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35522. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35523. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35524. serializationObject.uv5s._updatable = true;
  35525. }
  35526. }
  35527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35528. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35529. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35530. serializationObject.uv6s._updatable = true;
  35531. }
  35532. }
  35533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35534. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35535. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35536. serializationObject.colors._updatable = true;
  35537. }
  35538. }
  35539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35540. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35541. serializationObject.matricesIndices._isExpanded = true;
  35542. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35543. serializationObject.matricesIndices._updatable = true;
  35544. }
  35545. }
  35546. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35547. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35548. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35549. serializationObject.matricesWeights._updatable = true;
  35550. }
  35551. }
  35552. serializationObject.indices = this.toNumberArray(this.getIndices());
  35553. return serializationObject;
  35554. };
  35555. // Statics
  35556. /**
  35557. * Extracts a clone of a mesh geometry
  35558. * @param mesh defines the source mesh
  35559. * @param id defines the unique ID of the new geometry object
  35560. * @returns the new geometry object
  35561. */
  35562. Geometry.ExtractFromMesh = function (mesh, id) {
  35563. var geometry = mesh._geometry;
  35564. if (!geometry) {
  35565. return null;
  35566. }
  35567. return geometry.copy(id);
  35568. };
  35569. /**
  35570. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35571. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35572. * Be aware Math.random() could cause collisions, but:
  35573. * "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"
  35574. * @returns a string containing a new GUID
  35575. */
  35576. Geometry.RandomId = function () {
  35577. return BABYLON.Tools.RandomId();
  35578. };
  35579. /** @ignore */
  35580. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35581. var scene = mesh.getScene();
  35582. // Geometry
  35583. var geometryId = parsedGeometry.geometryId;
  35584. if (geometryId) {
  35585. var geometry = scene.getGeometryByID(geometryId);
  35586. if (geometry) {
  35587. geometry.applyToMesh(mesh);
  35588. }
  35589. }
  35590. else if (parsedGeometry instanceof ArrayBuffer) {
  35591. var binaryInfo = mesh._binaryInfo;
  35592. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35593. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35594. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35595. }
  35596. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35597. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35598. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35599. }
  35600. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35601. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35602. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35603. }
  35604. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35605. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35606. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35607. }
  35608. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35609. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35610. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35611. }
  35612. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35613. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35614. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35615. }
  35616. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35617. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35618. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35619. }
  35620. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35621. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35622. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35623. }
  35624. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35625. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35626. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35627. }
  35628. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35629. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35630. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35631. }
  35632. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35633. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35635. }
  35636. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35637. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35639. }
  35640. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35641. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35642. mesh.setIndices(indicesData, null);
  35643. }
  35644. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35645. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35646. mesh.subMeshes = [];
  35647. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35648. var materialIndex = subMeshesData[(i * 5) + 0];
  35649. var verticesStart = subMeshesData[(i * 5) + 1];
  35650. var verticesCount = subMeshesData[(i * 5) + 2];
  35651. var indexStart = subMeshesData[(i * 5) + 3];
  35652. var indexCount = subMeshesData[(i * 5) + 4];
  35653. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35654. }
  35655. }
  35656. }
  35657. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35658. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35659. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35660. if (parsedGeometry.tangents) {
  35661. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35662. }
  35663. if (parsedGeometry.uvs) {
  35664. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35665. }
  35666. if (parsedGeometry.uvs2) {
  35667. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35668. }
  35669. if (parsedGeometry.uvs3) {
  35670. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35671. }
  35672. if (parsedGeometry.uvs4) {
  35673. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35674. }
  35675. if (parsedGeometry.uvs5) {
  35676. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35677. }
  35678. if (parsedGeometry.uvs6) {
  35679. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35680. }
  35681. if (parsedGeometry.colors) {
  35682. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35683. }
  35684. if (parsedGeometry.matricesIndices) {
  35685. if (!parsedGeometry.matricesIndices._isExpanded) {
  35686. var floatIndices = [];
  35687. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35688. var matricesIndex = parsedGeometry.matricesIndices[i];
  35689. floatIndices.push(matricesIndex & 0x000000FF);
  35690. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35691. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35692. floatIndices.push(matricesIndex >> 24);
  35693. }
  35694. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35695. }
  35696. else {
  35697. delete parsedGeometry.matricesIndices._isExpanded;
  35698. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35699. }
  35700. }
  35701. if (parsedGeometry.matricesIndicesExtra) {
  35702. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35703. var floatIndices = [];
  35704. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35705. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35706. floatIndices.push(matricesIndex & 0x000000FF);
  35707. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35708. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35709. floatIndices.push(matricesIndex >> 24);
  35710. }
  35711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35712. }
  35713. else {
  35714. delete parsedGeometry.matricesIndices._isExpanded;
  35715. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35716. }
  35717. }
  35718. if (parsedGeometry.matricesWeights) {
  35719. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35721. }
  35722. if (parsedGeometry.matricesWeightsExtra) {
  35723. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35724. }
  35725. mesh.setIndices(parsedGeometry.indices, null);
  35726. }
  35727. // SubMeshes
  35728. if (parsedGeometry.subMeshes) {
  35729. mesh.subMeshes = [];
  35730. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35731. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35732. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35733. }
  35734. }
  35735. // Flat shading
  35736. if (mesh._shouldGenerateFlatShading) {
  35737. mesh.convertToFlatShadedMesh();
  35738. delete mesh._shouldGenerateFlatShading;
  35739. }
  35740. // Update
  35741. mesh.computeWorldMatrix(true);
  35742. // Octree
  35743. var sceneOctree = scene.selectionOctree;
  35744. if (sceneOctree !== undefined && sceneOctree !== null) {
  35745. sceneOctree.addMesh(mesh);
  35746. }
  35747. };
  35748. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35749. var epsilon = 1e-3;
  35750. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35751. return;
  35752. }
  35753. var noInfluenceBoneIndex = 0.0;
  35754. if (parsedGeometry.skeletonId > -1) {
  35755. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35756. if (!skeleton) {
  35757. return;
  35758. }
  35759. noInfluenceBoneIndex = skeleton.bones.length;
  35760. }
  35761. else {
  35762. return;
  35763. }
  35764. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35765. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35766. var matricesWeights = parsedGeometry.matricesWeights;
  35767. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35768. var influencers = parsedGeometry.numBoneInfluencer;
  35769. var size = matricesWeights.length;
  35770. for (var i = 0; i < size; i += 4) {
  35771. var weight = 0.0;
  35772. var firstZeroWeight = -1;
  35773. for (var j = 0; j < 4; j++) {
  35774. var w = matricesWeights[i + j];
  35775. weight += w;
  35776. if (w < epsilon && firstZeroWeight < 0) {
  35777. firstZeroWeight = j;
  35778. }
  35779. }
  35780. if (matricesWeightsExtra) {
  35781. for (var j = 0; j < 4; j++) {
  35782. var w = matricesWeightsExtra[i + j];
  35783. weight += w;
  35784. if (w < epsilon && firstZeroWeight < 0) {
  35785. firstZeroWeight = j + 4;
  35786. }
  35787. }
  35788. }
  35789. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35790. firstZeroWeight = influencers - 1;
  35791. }
  35792. if (weight > epsilon) {
  35793. var mweight = 1.0 / weight;
  35794. for (var j = 0; j < 4; j++) {
  35795. matricesWeights[i + j] *= mweight;
  35796. }
  35797. if (matricesWeightsExtra) {
  35798. for (var j = 0; j < 4; j++) {
  35799. matricesWeightsExtra[i + j] *= mweight;
  35800. }
  35801. }
  35802. }
  35803. else {
  35804. if (firstZeroWeight >= 4) {
  35805. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35806. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35807. }
  35808. else {
  35809. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35810. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35811. }
  35812. }
  35813. }
  35814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35815. if (parsedGeometry.matricesWeightsExtra) {
  35816. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35817. }
  35818. };
  35819. /**
  35820. * Create a new geometry from persisted data (Using .babylon file format)
  35821. * @param parsedVertexData defines the persisted data
  35822. * @param scene defines the hosting scene
  35823. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35824. * @returns the new geometry object
  35825. */
  35826. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35827. if (scene.getGeometryByID(parsedVertexData.id)) {
  35828. return null; // null since geometry could be something else than a box...
  35829. }
  35830. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35831. if (BABYLON.Tags) {
  35832. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35833. }
  35834. if (parsedVertexData.delayLoadingFile) {
  35835. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35836. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35837. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35838. geometry._delayInfo = [];
  35839. if (parsedVertexData.hasUVs) {
  35840. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35841. }
  35842. if (parsedVertexData.hasUVs2) {
  35843. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35844. }
  35845. if (parsedVertexData.hasUVs3) {
  35846. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35847. }
  35848. if (parsedVertexData.hasUVs4) {
  35849. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35850. }
  35851. if (parsedVertexData.hasUVs5) {
  35852. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35853. }
  35854. if (parsedVertexData.hasUVs6) {
  35855. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35856. }
  35857. if (parsedVertexData.hasColors) {
  35858. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35859. }
  35860. if (parsedVertexData.hasMatricesIndices) {
  35861. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35862. }
  35863. if (parsedVertexData.hasMatricesWeights) {
  35864. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35865. }
  35866. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35867. }
  35868. else {
  35869. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35870. }
  35871. scene.pushGeometry(geometry, true);
  35872. return geometry;
  35873. };
  35874. return Geometry;
  35875. }());
  35876. BABYLON.Geometry = Geometry;
  35877. // Primitives
  35878. /// Abstract class
  35879. /**
  35880. * Abstract class used to provide common services for all typed geometries
  35881. */
  35882. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35883. __extends(_PrimitiveGeometry, _super);
  35884. /**
  35885. * Creates a new typed geometry
  35886. * @param id defines the unique ID of the geometry
  35887. * @param scene defines the hosting scene
  35888. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35889. * @param mesh defines the hosting mesh (can be null)
  35890. */
  35891. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35892. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35893. if (mesh === void 0) { mesh = null; }
  35894. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35895. _this._canBeRegenerated = _canBeRegenerated;
  35896. _this._beingRegenerated = true;
  35897. _this.regenerate();
  35898. _this._beingRegenerated = false;
  35899. return _this;
  35900. }
  35901. /**
  35902. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35903. * @returns true if the geometry can be regenerated
  35904. */
  35905. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35906. return this._canBeRegenerated;
  35907. };
  35908. /**
  35909. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35910. */
  35911. _PrimitiveGeometry.prototype.regenerate = function () {
  35912. if (!this._canBeRegenerated) {
  35913. return;
  35914. }
  35915. this._beingRegenerated = true;
  35916. this.setAllVerticesData(this._regenerateVertexData(), false);
  35917. this._beingRegenerated = false;
  35918. };
  35919. /**
  35920. * Clone the geometry
  35921. * @param id defines the unique ID of the new geometry
  35922. * @returns the new geometry
  35923. */
  35924. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35925. return _super.prototype.copy.call(this, id);
  35926. };
  35927. // overrides
  35928. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35929. if (!this._beingRegenerated) {
  35930. return;
  35931. }
  35932. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35933. };
  35934. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35935. if (!this._beingRegenerated) {
  35936. return;
  35937. }
  35938. _super.prototype.setVerticesData.call(this, kind, data, false);
  35939. };
  35940. // to override
  35941. /** @ignore */
  35942. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35943. throw new Error("Abstract method");
  35944. };
  35945. _PrimitiveGeometry.prototype.copy = function (id) {
  35946. throw new Error("Must be overriden in sub-classes.");
  35947. };
  35948. _PrimitiveGeometry.prototype.serialize = function () {
  35949. var serializationObject = _super.prototype.serialize.call(this);
  35950. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35951. return serializationObject;
  35952. };
  35953. return _PrimitiveGeometry;
  35954. }(Geometry));
  35955. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35956. /**
  35957. * Creates a ribbon geometry
  35958. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35959. */
  35960. var RibbonGeometry = /** @class */ (function (_super) {
  35961. __extends(RibbonGeometry, _super);
  35962. /**
  35963. * Creates a ribbon geometry
  35964. * @param id defines the unique ID of the geometry
  35965. * @param scene defines the hosting scene
  35966. * @param pathArray defines the array of paths to use
  35967. * @param closeArray defines if the last path and the first path must be joined
  35968. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35969. * @param offset defines the offset between points
  35970. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35971. * @param mesh defines the hosting mesh (can be null)
  35972. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35973. */
  35974. function RibbonGeometry(id, scene,
  35975. /**
  35976. * Defines the array of paths to use
  35977. */
  35978. pathArray,
  35979. /**
  35980. * Defines if the last and first points of each path in your pathArray must be joined
  35981. */
  35982. closeArray,
  35983. /**
  35984. * Defines if the last and first points of each path in your pathArray must be joined
  35985. */
  35986. closePath,
  35987. /**
  35988. * Defines the offset between points
  35989. */
  35990. offset, canBeRegenerated, mesh,
  35991. /**
  35992. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35993. */
  35994. side) {
  35995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35996. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35997. _this.pathArray = pathArray;
  35998. _this.closeArray = closeArray;
  35999. _this.closePath = closePath;
  36000. _this.offset = offset;
  36001. _this.side = side;
  36002. return _this;
  36003. }
  36004. /** @ignore */
  36005. RibbonGeometry.prototype._regenerateVertexData = function () {
  36006. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36007. };
  36008. RibbonGeometry.prototype.copy = function (id) {
  36009. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36010. };
  36011. return RibbonGeometry;
  36012. }(_PrimitiveGeometry));
  36013. BABYLON.RibbonGeometry = RibbonGeometry;
  36014. /**
  36015. * Creates a box geometry
  36016. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36017. */
  36018. var BoxGeometry = /** @class */ (function (_super) {
  36019. __extends(BoxGeometry, _super);
  36020. /**
  36021. * Creates a box geometry
  36022. * @param id defines the unique ID of the geometry
  36023. * @param scene defines the hosting scene
  36024. * @param size defines the zise of the box (width, height and depth are the same)
  36025. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36026. * @param mesh defines the hosting mesh (can be null)
  36027. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36028. */
  36029. function BoxGeometry(id, scene,
  36030. /**
  36031. * Defines the zise of the box (width, height and depth are the same)
  36032. */
  36033. size, canBeRegenerated, mesh,
  36034. /**
  36035. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36036. */
  36037. side) {
  36038. if (mesh === void 0) { mesh = null; }
  36039. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36040. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36041. _this.size = size;
  36042. _this.side = side;
  36043. return _this;
  36044. }
  36045. BoxGeometry.prototype._regenerateVertexData = function () {
  36046. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36047. };
  36048. BoxGeometry.prototype.copy = function (id) {
  36049. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36050. };
  36051. BoxGeometry.prototype.serialize = function () {
  36052. var serializationObject = _super.prototype.serialize.call(this);
  36053. serializationObject.size = this.size;
  36054. return serializationObject;
  36055. };
  36056. BoxGeometry.Parse = function (parsedBox, scene) {
  36057. if (scene.getGeometryByID(parsedBox.id)) {
  36058. return null; // null since geometry could be something else than a box...
  36059. }
  36060. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36061. if (BABYLON.Tags) {
  36062. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36063. }
  36064. scene.pushGeometry(box, true);
  36065. return box;
  36066. };
  36067. return BoxGeometry;
  36068. }(_PrimitiveGeometry));
  36069. BABYLON.BoxGeometry = BoxGeometry;
  36070. /**
  36071. * Creates a sphere geometry
  36072. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36073. */
  36074. var SphereGeometry = /** @class */ (function (_super) {
  36075. __extends(SphereGeometry, _super);
  36076. /**
  36077. * Create a new sphere geometry
  36078. * @param id defines the unique ID of the geometry
  36079. * @param scene defines the hosting scene
  36080. * @param segments defines the number of segments to use to create the sphere
  36081. * @param diameter defines the diameter of the sphere
  36082. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36083. * @param mesh defines the hosting mesh (can be null)
  36084. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36085. */
  36086. function SphereGeometry(id, scene,
  36087. /**
  36088. * Defines the number of segments to use to create the sphere
  36089. */
  36090. segments,
  36091. /**
  36092. * Defines the diameter of the sphere
  36093. */
  36094. diameter, canBeRegenerated, mesh,
  36095. /**
  36096. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36097. */
  36098. side) {
  36099. if (mesh === void 0) { mesh = null; }
  36100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36102. _this.segments = segments;
  36103. _this.diameter = diameter;
  36104. _this.side = side;
  36105. return _this;
  36106. }
  36107. SphereGeometry.prototype._regenerateVertexData = function () {
  36108. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36109. };
  36110. SphereGeometry.prototype.copy = function (id) {
  36111. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36112. };
  36113. SphereGeometry.prototype.serialize = function () {
  36114. var serializationObject = _super.prototype.serialize.call(this);
  36115. serializationObject.segments = this.segments;
  36116. serializationObject.diameter = this.diameter;
  36117. return serializationObject;
  36118. };
  36119. SphereGeometry.Parse = function (parsedSphere, scene) {
  36120. if (scene.getGeometryByID(parsedSphere.id)) {
  36121. return null; // null since geometry could be something else than a sphere...
  36122. }
  36123. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36124. if (BABYLON.Tags) {
  36125. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36126. }
  36127. scene.pushGeometry(sphere, true);
  36128. return sphere;
  36129. };
  36130. return SphereGeometry;
  36131. }(_PrimitiveGeometry));
  36132. BABYLON.SphereGeometry = SphereGeometry;
  36133. /**
  36134. * Creates a disc geometry
  36135. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36136. */
  36137. var DiscGeometry = /** @class */ (function (_super) {
  36138. __extends(DiscGeometry, _super);
  36139. /**
  36140. * Creates a new disc geometry
  36141. * @param id defines the unique ID of the geometry
  36142. * @param scene defines the hosting scene
  36143. * @param radius defines the radius of the disc
  36144. * @param tessellation defines the tesselation factor to apply to the disc
  36145. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36146. * @param mesh defines the hosting mesh (can be null)
  36147. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36148. */
  36149. function DiscGeometry(id, scene,
  36150. /**
  36151. * Defines the radius of the disc
  36152. */
  36153. radius,
  36154. /**
  36155. * Defines the tesselation factor to apply to the disc
  36156. */
  36157. tessellation, canBeRegenerated, mesh,
  36158. /**
  36159. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36160. */
  36161. side) {
  36162. if (mesh === void 0) { mesh = null; }
  36163. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36164. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36165. _this.radius = radius;
  36166. _this.tessellation = tessellation;
  36167. _this.side = side;
  36168. return _this;
  36169. }
  36170. DiscGeometry.prototype._regenerateVertexData = function () {
  36171. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36172. };
  36173. DiscGeometry.prototype.copy = function (id) {
  36174. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36175. };
  36176. return DiscGeometry;
  36177. }(_PrimitiveGeometry));
  36178. BABYLON.DiscGeometry = DiscGeometry;
  36179. /**
  36180. * Creates a new cylinder geometry
  36181. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36182. */
  36183. var CylinderGeometry = /** @class */ (function (_super) {
  36184. __extends(CylinderGeometry, _super);
  36185. /**
  36186. * Creates a new cylinder geometry
  36187. * @param id defines the unique ID of the geometry
  36188. * @param scene defines the hosting scene
  36189. * @param height defines the height of the cylinder
  36190. * @param diameterTop defines the diameter of the cylinder's top cap
  36191. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36192. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36193. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36194. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36195. * @param mesh defines the hosting mesh (can be null)
  36196. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36197. */
  36198. function CylinderGeometry(id, scene,
  36199. /**
  36200. * Defines the height of the cylinder
  36201. */
  36202. height,
  36203. /**
  36204. * Defines the diameter of the cylinder's top cap
  36205. */
  36206. diameterTop,
  36207. /**
  36208. * Defines the diameter of the cylinder's bottom cap
  36209. */
  36210. diameterBottom,
  36211. /**
  36212. * Defines the tessellation factor to apply to the cylinder
  36213. */
  36214. tessellation,
  36215. /**
  36216. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36217. */
  36218. subdivisions, canBeRegenerated, mesh,
  36219. /**
  36220. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36221. */
  36222. side) {
  36223. if (subdivisions === void 0) { subdivisions = 1; }
  36224. if (mesh === void 0) { mesh = null; }
  36225. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36226. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36227. _this.height = height;
  36228. _this.diameterTop = diameterTop;
  36229. _this.diameterBottom = diameterBottom;
  36230. _this.tessellation = tessellation;
  36231. _this.subdivisions = subdivisions;
  36232. _this.side = side;
  36233. return _this;
  36234. }
  36235. CylinderGeometry.prototype._regenerateVertexData = function () {
  36236. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36237. };
  36238. CylinderGeometry.prototype.copy = function (id) {
  36239. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36240. };
  36241. CylinderGeometry.prototype.serialize = function () {
  36242. var serializationObject = _super.prototype.serialize.call(this);
  36243. serializationObject.height = this.height;
  36244. serializationObject.diameterTop = this.diameterTop;
  36245. serializationObject.diameterBottom = this.diameterBottom;
  36246. serializationObject.tessellation = this.tessellation;
  36247. return serializationObject;
  36248. };
  36249. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36250. if (scene.getGeometryByID(parsedCylinder.id)) {
  36251. return null; // null since geometry could be something else than a cylinder...
  36252. }
  36253. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36254. if (BABYLON.Tags) {
  36255. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36256. }
  36257. scene.pushGeometry(cylinder, true);
  36258. return cylinder;
  36259. };
  36260. return CylinderGeometry;
  36261. }(_PrimitiveGeometry));
  36262. BABYLON.CylinderGeometry = CylinderGeometry;
  36263. /**
  36264. * Creates a new torus geometry
  36265. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36266. */
  36267. var TorusGeometry = /** @class */ (function (_super) {
  36268. __extends(TorusGeometry, _super);
  36269. /**
  36270. * Creates a new torus geometry
  36271. * @param id defines the unique ID of the geometry
  36272. * @param scene defines the hosting scene
  36273. * @param diameter defines the diameter of the torus
  36274. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36275. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36276. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36277. * @param mesh defines the hosting mesh (can be null)
  36278. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36279. */
  36280. function TorusGeometry(id, scene,
  36281. /**
  36282. * Defines the diameter of the torus
  36283. */
  36284. diameter,
  36285. /**
  36286. * Defines the thickness of the torus (ie. internal diameter)
  36287. */
  36288. thickness,
  36289. /**
  36290. * Defines the tesselation factor to apply to the torus
  36291. */
  36292. tessellation, canBeRegenerated, mesh,
  36293. /**
  36294. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36295. */
  36296. side) {
  36297. if (mesh === void 0) { mesh = null; }
  36298. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36299. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36300. _this.diameter = diameter;
  36301. _this.thickness = thickness;
  36302. _this.tessellation = tessellation;
  36303. _this.side = side;
  36304. return _this;
  36305. }
  36306. TorusGeometry.prototype._regenerateVertexData = function () {
  36307. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36308. };
  36309. TorusGeometry.prototype.copy = function (id) {
  36310. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36311. };
  36312. TorusGeometry.prototype.serialize = function () {
  36313. var serializationObject = _super.prototype.serialize.call(this);
  36314. serializationObject.diameter = this.diameter;
  36315. serializationObject.thickness = this.thickness;
  36316. serializationObject.tessellation = this.tessellation;
  36317. return serializationObject;
  36318. };
  36319. TorusGeometry.Parse = function (parsedTorus, scene) {
  36320. if (scene.getGeometryByID(parsedTorus.id)) {
  36321. return null; // null since geometry could be something else than a torus...
  36322. }
  36323. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36324. if (BABYLON.Tags) {
  36325. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36326. }
  36327. scene.pushGeometry(torus, true);
  36328. return torus;
  36329. };
  36330. return TorusGeometry;
  36331. }(_PrimitiveGeometry));
  36332. BABYLON.TorusGeometry = TorusGeometry;
  36333. /**
  36334. * Creates a new ground geometry
  36335. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36336. */
  36337. var GroundGeometry = /** @class */ (function (_super) {
  36338. __extends(GroundGeometry, _super);
  36339. /**
  36340. * Creates a new ground geometry
  36341. * @param id defines the unique ID of the geometry
  36342. * @param scene defines the hosting scene
  36343. * @param width defines the width of the ground
  36344. * @param height defines the height of the ground
  36345. * @param subdivisions defines the subdivisions to apply to the ground
  36346. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36347. * @param mesh defines the hosting mesh (can be null)
  36348. */
  36349. function GroundGeometry(id, scene,
  36350. /**
  36351. * Defines the width of the ground
  36352. */
  36353. width,
  36354. /**
  36355. * Defines the height of the ground
  36356. */
  36357. height,
  36358. /**
  36359. * Defines the subdivisions to apply to the ground
  36360. */
  36361. subdivisions, canBeRegenerated, mesh) {
  36362. if (mesh === void 0) { mesh = null; }
  36363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36364. _this.width = width;
  36365. _this.height = height;
  36366. _this.subdivisions = subdivisions;
  36367. return _this;
  36368. }
  36369. GroundGeometry.prototype._regenerateVertexData = function () {
  36370. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36371. };
  36372. GroundGeometry.prototype.copy = function (id) {
  36373. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36374. };
  36375. GroundGeometry.prototype.serialize = function () {
  36376. var serializationObject = _super.prototype.serialize.call(this);
  36377. serializationObject.width = this.width;
  36378. serializationObject.height = this.height;
  36379. serializationObject.subdivisions = this.subdivisions;
  36380. return serializationObject;
  36381. };
  36382. GroundGeometry.Parse = function (parsedGround, scene) {
  36383. if (scene.getGeometryByID(parsedGround.id)) {
  36384. return null; // null since geometry could be something else than a ground...
  36385. }
  36386. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36387. if (BABYLON.Tags) {
  36388. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36389. }
  36390. scene.pushGeometry(ground, true);
  36391. return ground;
  36392. };
  36393. return GroundGeometry;
  36394. }(_PrimitiveGeometry));
  36395. BABYLON.GroundGeometry = GroundGeometry;
  36396. /**
  36397. * Creates a tiled ground geometry
  36398. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36399. */
  36400. var TiledGroundGeometry = /** @class */ (function (_super) {
  36401. __extends(TiledGroundGeometry, _super);
  36402. /**
  36403. * Creates a tiled ground geometry
  36404. * @param id defines the unique ID of the geometry
  36405. * @param scene defines the hosting scene
  36406. * @param xmin defines the minimum value on X axis
  36407. * @param zmin defines the minimum value on Z axis
  36408. * @param xmax defines the maximum value on X axis
  36409. * @param zmax defines the maximum value on Z axis
  36410. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36411. * @param precision defines the precision to use when computing the tiles
  36412. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36413. * @param mesh defines the hosting mesh (can be null)
  36414. */
  36415. function TiledGroundGeometry(id, scene,
  36416. /**
  36417. * Defines the minimum value on X axis
  36418. */
  36419. xmin,
  36420. /**
  36421. * Defines the minimum value on Z axis
  36422. */
  36423. zmin,
  36424. /**
  36425. * Defines the maximum value on X axis
  36426. */
  36427. xmax,
  36428. /**
  36429. * Defines the maximum value on Z axis
  36430. */
  36431. zmax,
  36432. /**
  36433. * Defines the subdivisions to apply to the ground
  36434. */
  36435. subdivisions,
  36436. /**
  36437. * Defines the precision to use when computing the tiles
  36438. */
  36439. precision, canBeRegenerated, mesh) {
  36440. if (mesh === void 0) { mesh = null; }
  36441. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36442. _this.xmin = xmin;
  36443. _this.zmin = zmin;
  36444. _this.xmax = xmax;
  36445. _this.zmax = zmax;
  36446. _this.subdivisions = subdivisions;
  36447. _this.precision = precision;
  36448. return _this;
  36449. }
  36450. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36451. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36452. };
  36453. TiledGroundGeometry.prototype.copy = function (id) {
  36454. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36455. };
  36456. return TiledGroundGeometry;
  36457. }(_PrimitiveGeometry));
  36458. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36459. /**
  36460. * Creates a plane geometry
  36461. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36462. */
  36463. var PlaneGeometry = /** @class */ (function (_super) {
  36464. __extends(PlaneGeometry, _super);
  36465. /**
  36466. * Creates a plane geometry
  36467. * @param id defines the unique ID of the geometry
  36468. * @param scene defines the hosting scene
  36469. * @param size defines the size of the plane (width === height)
  36470. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36471. * @param mesh defines the hosting mesh (can be null)
  36472. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36473. */
  36474. function PlaneGeometry(id, scene,
  36475. /**
  36476. * Defines the size of the plane (width === height)
  36477. */
  36478. size, canBeRegenerated, mesh,
  36479. /**
  36480. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36481. */
  36482. side) {
  36483. if (mesh === void 0) { mesh = null; }
  36484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36486. _this.size = size;
  36487. _this.side = side;
  36488. return _this;
  36489. }
  36490. PlaneGeometry.prototype._regenerateVertexData = function () {
  36491. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36492. };
  36493. PlaneGeometry.prototype.copy = function (id) {
  36494. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36495. };
  36496. PlaneGeometry.prototype.serialize = function () {
  36497. var serializationObject = _super.prototype.serialize.call(this);
  36498. serializationObject.size = this.size;
  36499. return serializationObject;
  36500. };
  36501. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36502. if (scene.getGeometryByID(parsedPlane.id)) {
  36503. return null; // null since geometry could be something else than a ground...
  36504. }
  36505. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36506. if (BABYLON.Tags) {
  36507. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36508. }
  36509. scene.pushGeometry(plane, true);
  36510. return plane;
  36511. };
  36512. return PlaneGeometry;
  36513. }(_PrimitiveGeometry));
  36514. BABYLON.PlaneGeometry = PlaneGeometry;
  36515. /**
  36516. * Creates a torus knot geometry
  36517. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36518. */
  36519. var TorusKnotGeometry = /** @class */ (function (_super) {
  36520. __extends(TorusKnotGeometry, _super);
  36521. /**
  36522. * Creates a torus knot geometry
  36523. * @param id defines the unique ID of the geometry
  36524. * @param scene defines the hosting scene
  36525. * @param radius defines the radius of the torus knot
  36526. * @param tube defines the thickness of the torus knot tube
  36527. * @param radialSegments defines the number of radial segments
  36528. * @param tubularSegments defines the number of tubular segments
  36529. * @param p defines the first number of windings
  36530. * @param q defines the second number of windings
  36531. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36532. * @param mesh defines the hosting mesh (can be null)
  36533. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36534. */
  36535. function TorusKnotGeometry(id, scene,
  36536. /**
  36537. * Defines the radius of the torus knot
  36538. */
  36539. radius,
  36540. /**
  36541. * Defines the thickness of the torus knot tube
  36542. */
  36543. tube,
  36544. /**
  36545. * Defines the number of radial segments
  36546. */
  36547. radialSegments,
  36548. /**
  36549. * Defines the number of tubular segments
  36550. */
  36551. tubularSegments,
  36552. /**
  36553. * Defines the first number of windings
  36554. */
  36555. p,
  36556. /**
  36557. * Defines the second number of windings
  36558. */
  36559. q, canBeRegenerated, mesh,
  36560. /**
  36561. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36562. */
  36563. side) {
  36564. if (mesh === void 0) { mesh = null; }
  36565. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36566. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36567. _this.radius = radius;
  36568. _this.tube = tube;
  36569. _this.radialSegments = radialSegments;
  36570. _this.tubularSegments = tubularSegments;
  36571. _this.p = p;
  36572. _this.q = q;
  36573. _this.side = side;
  36574. return _this;
  36575. }
  36576. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36577. 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 });
  36578. };
  36579. TorusKnotGeometry.prototype.copy = function (id) {
  36580. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36581. };
  36582. TorusKnotGeometry.prototype.serialize = function () {
  36583. var serializationObject = _super.prototype.serialize.call(this);
  36584. serializationObject.radius = this.radius;
  36585. serializationObject.tube = this.tube;
  36586. serializationObject.radialSegments = this.radialSegments;
  36587. serializationObject.tubularSegments = this.tubularSegments;
  36588. serializationObject.p = this.p;
  36589. serializationObject.q = this.q;
  36590. return serializationObject;
  36591. };
  36592. ;
  36593. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36594. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36595. return null; // null since geometry could be something else than a ground...
  36596. }
  36597. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36598. if (BABYLON.Tags) {
  36599. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36600. }
  36601. scene.pushGeometry(torusKnot, true);
  36602. return torusKnot;
  36603. };
  36604. return TorusKnotGeometry;
  36605. }(_PrimitiveGeometry));
  36606. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36607. //}
  36608. })(BABYLON || (BABYLON = {}));
  36609. //# sourceMappingURL=babylon.geometry.js.map
  36610. var BABYLON;
  36611. (function (BABYLON) {
  36612. /**
  36613. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36614. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36615. */
  36616. var PostProcessManager = /** @class */ (function () {
  36617. /**
  36618. * Creates a new instance of @see PostProcess
  36619. * @param scene The scene that the post process is associated with.
  36620. */
  36621. function PostProcessManager(scene) {
  36622. this._vertexBuffers = {};
  36623. this._scene = scene;
  36624. }
  36625. PostProcessManager.prototype._prepareBuffers = function () {
  36626. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36627. return;
  36628. }
  36629. // VBO
  36630. var vertices = [];
  36631. vertices.push(1, 1);
  36632. vertices.push(-1, 1);
  36633. vertices.push(-1, -1);
  36634. vertices.push(1, -1);
  36635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36636. this._buildIndexBuffer();
  36637. };
  36638. PostProcessManager.prototype._buildIndexBuffer = function () {
  36639. // Indices
  36640. var indices = [];
  36641. indices.push(0);
  36642. indices.push(1);
  36643. indices.push(2);
  36644. indices.push(0);
  36645. indices.push(2);
  36646. indices.push(3);
  36647. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36648. };
  36649. /**
  36650. * Rebuilds the vertex buffers of the manager.
  36651. */
  36652. PostProcessManager.prototype._rebuild = function () {
  36653. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36654. if (!vb) {
  36655. return;
  36656. }
  36657. vb._rebuild();
  36658. this._buildIndexBuffer();
  36659. };
  36660. // Methods
  36661. /**
  36662. * Prepares a frame to be run through a post process.
  36663. * @param sourceTexture The input texture to the post procesess. (default: null)
  36664. * @param postProcesses An array of post processes to be run. (default: null)
  36665. * @returns True if the post processes were able to be run.
  36666. */
  36667. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36668. if (sourceTexture === void 0) { sourceTexture = null; }
  36669. if (postProcesses === void 0) { postProcesses = null; }
  36670. var camera = this._scene.activeCamera;
  36671. if (!camera) {
  36672. return false;
  36673. }
  36674. var postProcesses = postProcesses || camera._postProcesses;
  36675. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36676. return false;
  36677. }
  36678. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36679. return true;
  36680. };
  36681. /**
  36682. * Manually render a set of post processes to a texture.
  36683. * @param postProcesses An array of post processes to be run.
  36684. * @param targetTexture The target texture to render to.
  36685. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36686. */
  36687. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36688. if (targetTexture === void 0) { targetTexture = null; }
  36689. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36690. var engine = this._scene.getEngine();
  36691. for (var index = 0; index < postProcesses.length; index++) {
  36692. if (index < postProcesses.length - 1) {
  36693. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36694. }
  36695. else {
  36696. if (targetTexture) {
  36697. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36698. }
  36699. else {
  36700. engine.restoreDefaultFramebuffer();
  36701. }
  36702. }
  36703. var pp = postProcesses[index];
  36704. var effect = pp.apply();
  36705. if (effect) {
  36706. pp.onBeforeRenderObservable.notifyObservers(effect);
  36707. // VBOs
  36708. this._prepareBuffers();
  36709. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36710. // Draw order
  36711. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36712. pp.onAfterRenderObservable.notifyObservers(effect);
  36713. }
  36714. }
  36715. // Restore depth buffer
  36716. engine.setDepthBuffer(true);
  36717. engine.setDepthWrite(true);
  36718. };
  36719. /**
  36720. * Finalize the result of the output of the postprocesses.
  36721. * @param doNotPresent If true the result will not be displayed to the screen.
  36722. * @param targetTexture The target texture to render to.
  36723. * @param faceIndex The index of the face to bind the target texture to.
  36724. * @param postProcesses The array of post processes to render.
  36725. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36726. */
  36727. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36728. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36729. var camera = this._scene.activeCamera;
  36730. if (!camera) {
  36731. return;
  36732. }
  36733. postProcesses = postProcesses || camera._postProcesses;
  36734. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36735. return;
  36736. }
  36737. var engine = this._scene.getEngine();
  36738. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36739. if (index < len - 1) {
  36740. postProcesses[index + 1].activate(camera, targetTexture);
  36741. }
  36742. else {
  36743. if (targetTexture) {
  36744. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36745. }
  36746. else {
  36747. engine.restoreDefaultFramebuffer();
  36748. }
  36749. }
  36750. if (doNotPresent) {
  36751. break;
  36752. }
  36753. var pp = postProcesses[index];
  36754. var effect = pp.apply();
  36755. if (effect) {
  36756. pp.onBeforeRenderObservable.notifyObservers(effect);
  36757. // VBOs
  36758. this._prepareBuffers();
  36759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36760. // Draw order
  36761. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36762. pp.onAfterRenderObservable.notifyObservers(effect);
  36763. }
  36764. }
  36765. // Restore states
  36766. engine.setDepthBuffer(true);
  36767. engine.setDepthWrite(true);
  36768. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36769. };
  36770. /**
  36771. * Disposes of the post process manager.
  36772. */
  36773. PostProcessManager.prototype.dispose = function () {
  36774. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36775. if (buffer) {
  36776. buffer.dispose();
  36777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36778. }
  36779. if (this._indexBuffer) {
  36780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36781. this._indexBuffer = null;
  36782. }
  36783. };
  36784. return PostProcessManager;
  36785. }());
  36786. BABYLON.PostProcessManager = PostProcessManager;
  36787. })(BABYLON || (BABYLON = {}));
  36788. //# sourceMappingURL=babylon.postProcessManager.js.map
  36789. var BABYLON;
  36790. (function (BABYLON) {
  36791. /**
  36792. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36793. */
  36794. var PerformanceMonitor = /** @class */ (function () {
  36795. /**
  36796. * constructor
  36797. * @param frameSampleSize The number of samples required to saturate the sliding window
  36798. */
  36799. function PerformanceMonitor(frameSampleSize) {
  36800. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36801. this._enabled = true;
  36802. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36803. }
  36804. /**
  36805. * Samples current frame
  36806. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36807. */
  36808. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36809. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36810. if (!this._enabled)
  36811. return;
  36812. if (this._lastFrameTimeMs != null) {
  36813. var dt = timeMs - this._lastFrameTimeMs;
  36814. this._rollingFrameTime.add(dt);
  36815. }
  36816. this._lastFrameTimeMs = timeMs;
  36817. };
  36818. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36819. /**
  36820. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36821. * @return Average frame time in milliseconds
  36822. */
  36823. get: function () {
  36824. return this._rollingFrameTime.average;
  36825. },
  36826. enumerable: true,
  36827. configurable: true
  36828. });
  36829. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36830. /**
  36831. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36832. * @return Frame time variance in milliseconds squared
  36833. */
  36834. get: function () {
  36835. return this._rollingFrameTime.variance;
  36836. },
  36837. enumerable: true,
  36838. configurable: true
  36839. });
  36840. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36841. /**
  36842. * Returns the frame time of the most recent frame
  36843. * @return Frame time in milliseconds
  36844. */
  36845. get: function () {
  36846. return this._rollingFrameTime.history(0);
  36847. },
  36848. enumerable: true,
  36849. configurable: true
  36850. });
  36851. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36852. /**
  36853. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36854. * @return Framerate in frames per second
  36855. */
  36856. get: function () {
  36857. return 1000.0 / this._rollingFrameTime.average;
  36858. },
  36859. enumerable: true,
  36860. configurable: true
  36861. });
  36862. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36863. /**
  36864. * Returns the average framerate in frames per second using the most recent frame time
  36865. * @return Framerate in frames per second
  36866. */
  36867. get: function () {
  36868. var history = this._rollingFrameTime.history(0);
  36869. if (history === 0) {
  36870. return 0;
  36871. }
  36872. return 1000.0 / history;
  36873. },
  36874. enumerable: true,
  36875. configurable: true
  36876. });
  36877. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36878. /**
  36879. * Returns true if enough samples have been taken to completely fill the sliding window
  36880. * @return true if saturated
  36881. */
  36882. get: function () {
  36883. return this._rollingFrameTime.isSaturated();
  36884. },
  36885. enumerable: true,
  36886. configurable: true
  36887. });
  36888. /**
  36889. * Enables contributions to the sliding window sample set
  36890. */
  36891. PerformanceMonitor.prototype.enable = function () {
  36892. this._enabled = true;
  36893. };
  36894. /**
  36895. * Disables contributions to the sliding window sample set
  36896. * Samples will not be interpolated over the disabled period
  36897. */
  36898. PerformanceMonitor.prototype.disable = function () {
  36899. this._enabled = false;
  36900. //clear last sample to avoid interpolating over the disabled period when next enabled
  36901. this._lastFrameTimeMs = null;
  36902. };
  36903. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36904. /**
  36905. * Returns true if sampling is enabled
  36906. * @return true if enabled
  36907. */
  36908. get: function () {
  36909. return this._enabled;
  36910. },
  36911. enumerable: true,
  36912. configurable: true
  36913. });
  36914. /**
  36915. * Resets performance monitor
  36916. */
  36917. PerformanceMonitor.prototype.reset = function () {
  36918. //clear last sample to avoid interpolating over the disabled period when next enabled
  36919. this._lastFrameTimeMs = null;
  36920. //wipe record
  36921. this._rollingFrameTime.reset();
  36922. };
  36923. return PerformanceMonitor;
  36924. }());
  36925. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36926. /**
  36927. * RollingAverage
  36928. *
  36929. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36930. */
  36931. var RollingAverage = /** @class */ (function () {
  36932. /**
  36933. * constructor
  36934. * @param length The number of samples required to saturate the sliding window
  36935. */
  36936. function RollingAverage(length) {
  36937. this._samples = new Array(length);
  36938. this.reset();
  36939. }
  36940. /**
  36941. * Adds a sample to the sample set
  36942. * @param v The sample value
  36943. */
  36944. RollingAverage.prototype.add = function (v) {
  36945. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36946. var delta;
  36947. //we need to check if we've already wrapped round
  36948. if (this.isSaturated()) {
  36949. //remove bottom of stack from mean
  36950. var bottomValue = this._samples[this._pos];
  36951. delta = bottomValue - this.average;
  36952. this.average -= delta / (this._sampleCount - 1);
  36953. this._m2 -= delta * (bottomValue - this.average);
  36954. }
  36955. else {
  36956. this._sampleCount++;
  36957. }
  36958. //add new value to mean
  36959. delta = v - this.average;
  36960. this.average += delta / (this._sampleCount);
  36961. this._m2 += delta * (v - this.average);
  36962. //set the new variance
  36963. this.variance = this._m2 / (this._sampleCount - 1);
  36964. this._samples[this._pos] = v;
  36965. this._pos++;
  36966. this._pos %= this._samples.length; //positive wrap around
  36967. };
  36968. /**
  36969. * Returns previously added values or null if outside of history or outside the sliding window domain
  36970. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36971. * @return Value previously recorded with add() or null if outside of range
  36972. */
  36973. RollingAverage.prototype.history = function (i) {
  36974. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36975. return 0;
  36976. }
  36977. var i0 = this._wrapPosition(this._pos - 1.0);
  36978. return this._samples[this._wrapPosition(i0 - i)];
  36979. };
  36980. /**
  36981. * Returns true if enough samples have been taken to completely fill the sliding window
  36982. * @return true if sample-set saturated
  36983. */
  36984. RollingAverage.prototype.isSaturated = function () {
  36985. return this._sampleCount >= this._samples.length;
  36986. };
  36987. /**
  36988. * Resets the rolling average (equivalent to 0 samples taken so far)
  36989. */
  36990. RollingAverage.prototype.reset = function () {
  36991. this.average = 0;
  36992. this.variance = 0;
  36993. this._sampleCount = 0;
  36994. this._pos = 0;
  36995. this._m2 = 0;
  36996. };
  36997. /**
  36998. * Wraps a value around the sample range boundaries
  36999. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37000. * @return Wrapped position in sample range
  37001. */
  37002. RollingAverage.prototype._wrapPosition = function (i) {
  37003. var max = this._samples.length;
  37004. return ((i % max) + max) % max;
  37005. };
  37006. return RollingAverage;
  37007. }());
  37008. BABYLON.RollingAverage = RollingAverage;
  37009. })(BABYLON || (BABYLON = {}));
  37010. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37011. var BABYLON;
  37012. (function (BABYLON) {
  37013. /**
  37014. * This groups together the common properties used for image processing either in direct forward pass
  37015. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37016. * or not.
  37017. */
  37018. var ImageProcessingConfiguration = /** @class */ (function () {
  37019. function ImageProcessingConfiguration() {
  37020. /**
  37021. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37022. */
  37023. this.colorCurves = new BABYLON.ColorCurves();
  37024. this._colorCurvesEnabled = false;
  37025. this._colorGradingEnabled = false;
  37026. this._colorGradingWithGreenDepth = true;
  37027. this._colorGradingBGR = true;
  37028. this._exposure = 1.0;
  37029. this._toneMappingEnabled = false;
  37030. this._contrast = 1.0;
  37031. /**
  37032. * Vignette stretch size.
  37033. */
  37034. this.vignetteStretch = 0;
  37035. /**
  37036. * Vignette centre X Offset.
  37037. */
  37038. this.vignetteCentreX = 0;
  37039. /**
  37040. * Vignette centre Y Offset.
  37041. */
  37042. this.vignetteCentreY = 0;
  37043. /**
  37044. * Vignette weight or intensity of the vignette effect.
  37045. */
  37046. this.vignetteWeight = 1.5;
  37047. /**
  37048. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37049. * if vignetteEnabled is set to true.
  37050. */
  37051. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37052. /**
  37053. * Camera field of view used by the Vignette effect.
  37054. */
  37055. this.vignetteCameraFov = 0.5;
  37056. this._grainEnabled = false;
  37057. this._grainIntensity = 30;
  37058. this._grainAnimated = false;
  37059. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37060. this._vignetteEnabled = false;
  37061. this._applyByPostProcess = false;
  37062. this._isEnabled = true;
  37063. /**
  37064. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37065. * @type {BABYLON.Observable}
  37066. */
  37067. this.onUpdateParameters = new BABYLON.Observable();
  37068. }
  37069. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37070. /**
  37071. * Gets wether the color curves effect is enabled.
  37072. */
  37073. get: function () {
  37074. return this._colorCurvesEnabled;
  37075. },
  37076. /**
  37077. * Sets wether the color curves effect is enabled.
  37078. */
  37079. set: function (value) {
  37080. if (this._colorCurvesEnabled === value) {
  37081. return;
  37082. }
  37083. this._colorCurvesEnabled = value;
  37084. this._updateParameters();
  37085. },
  37086. enumerable: true,
  37087. configurable: true
  37088. });
  37089. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37090. /**
  37091. * Gets wether the color grading effect is enabled.
  37092. */
  37093. get: function () {
  37094. return this._colorGradingEnabled;
  37095. },
  37096. /**
  37097. * Sets wether the color grading effect is enabled.
  37098. */
  37099. set: function (value) {
  37100. if (this._colorGradingEnabled === value) {
  37101. return;
  37102. }
  37103. this._colorGradingEnabled = value;
  37104. this._updateParameters();
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37110. /**
  37111. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37112. */
  37113. get: function () {
  37114. return this._colorGradingWithGreenDepth;
  37115. },
  37116. /**
  37117. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37118. */
  37119. set: function (value) {
  37120. if (this._colorGradingWithGreenDepth === value) {
  37121. return;
  37122. }
  37123. this._colorGradingWithGreenDepth = value;
  37124. this._updateParameters();
  37125. },
  37126. enumerable: true,
  37127. configurable: true
  37128. });
  37129. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37130. /**
  37131. * Gets wether the color grading texture contains BGR values.
  37132. */
  37133. get: function () {
  37134. return this._colorGradingBGR;
  37135. },
  37136. /**
  37137. * Sets wether the color grading texture contains BGR values.
  37138. */
  37139. set: function (value) {
  37140. if (this._colorGradingBGR === value) {
  37141. return;
  37142. }
  37143. this._colorGradingBGR = value;
  37144. this._updateParameters();
  37145. },
  37146. enumerable: true,
  37147. configurable: true
  37148. });
  37149. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37150. /**
  37151. * Gets the Exposure used in the effect.
  37152. */
  37153. get: function () {
  37154. return this._exposure;
  37155. },
  37156. /**
  37157. * Sets the Exposure used in the effect.
  37158. */
  37159. set: function (value) {
  37160. if (this._exposure === value) {
  37161. return;
  37162. }
  37163. this._exposure = value;
  37164. this._updateParameters();
  37165. },
  37166. enumerable: true,
  37167. configurable: true
  37168. });
  37169. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37170. /**
  37171. * Gets wether the tone mapping effect is enabled.
  37172. */
  37173. get: function () {
  37174. return this._toneMappingEnabled;
  37175. },
  37176. /**
  37177. * Sets wether the tone mapping effect is enabled.
  37178. */
  37179. set: function (value) {
  37180. if (this._toneMappingEnabled === value) {
  37181. return;
  37182. }
  37183. this._toneMappingEnabled = value;
  37184. this._updateParameters();
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37190. /**
  37191. * Gets the contrast used in the effect.
  37192. */
  37193. get: function () {
  37194. return this._contrast;
  37195. },
  37196. /**
  37197. * Sets the contrast used in the effect.
  37198. */
  37199. set: function (value) {
  37200. if (this._contrast === value) {
  37201. return;
  37202. }
  37203. this._contrast = value;
  37204. this._updateParameters();
  37205. },
  37206. enumerable: true,
  37207. configurable: true
  37208. });
  37209. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37210. /**
  37211. * If the grain effect should be enabled.
  37212. */
  37213. get: function () {
  37214. return this._grainEnabled;
  37215. },
  37216. set: function (value) {
  37217. if (this._grainEnabled === value) {
  37218. return;
  37219. }
  37220. this._grainEnabled = value;
  37221. this._updateParameters();
  37222. },
  37223. enumerable: true,
  37224. configurable: true
  37225. });
  37226. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37227. /**
  37228. * Amount of grain to be applied by the grain effect.
  37229. */
  37230. get: function () {
  37231. return this._grainIntensity;
  37232. },
  37233. set: function (value) {
  37234. if (this._grainIntensity === value) {
  37235. return;
  37236. }
  37237. this._grainIntensity = value;
  37238. },
  37239. enumerable: true,
  37240. configurable: true
  37241. });
  37242. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37243. /**
  37244. * If the grain effect should be animated.
  37245. */
  37246. get: function () {
  37247. return this._grainAnimated;
  37248. },
  37249. set: function (value) {
  37250. if (this._grainAnimated === value) {
  37251. return;
  37252. }
  37253. this._grainAnimated = value;
  37254. this._updateParameters();
  37255. },
  37256. enumerable: true,
  37257. configurable: true
  37258. });
  37259. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37260. /**
  37261. * Gets the vignette blend mode allowing different kind of effect.
  37262. */
  37263. get: function () {
  37264. return this._vignetteBlendMode;
  37265. },
  37266. /**
  37267. * Sets the vignette blend mode allowing different kind of effect.
  37268. */
  37269. set: function (value) {
  37270. if (this._vignetteBlendMode === value) {
  37271. return;
  37272. }
  37273. this._vignetteBlendMode = value;
  37274. this._updateParameters();
  37275. },
  37276. enumerable: true,
  37277. configurable: true
  37278. });
  37279. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37280. /**
  37281. * Gets wether the vignette effect is enabled.
  37282. */
  37283. get: function () {
  37284. return this._vignetteEnabled;
  37285. },
  37286. /**
  37287. * Sets wether the vignette effect is enabled.
  37288. */
  37289. set: function (value) {
  37290. if (this._vignetteEnabled === value) {
  37291. return;
  37292. }
  37293. this._vignetteEnabled = value;
  37294. this._updateParameters();
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37300. /**
  37301. * Gets wether the image processing is applied through a post process or not.
  37302. */
  37303. get: function () {
  37304. return this._applyByPostProcess;
  37305. },
  37306. /**
  37307. * Sets wether the image processing is applied through a post process or not.
  37308. */
  37309. set: function (value) {
  37310. if (this._applyByPostProcess === value) {
  37311. return;
  37312. }
  37313. this._applyByPostProcess = value;
  37314. this._updateParameters();
  37315. },
  37316. enumerable: true,
  37317. configurable: true
  37318. });
  37319. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37320. /**
  37321. * Gets wether the image processing is enabled or not.
  37322. */
  37323. get: function () {
  37324. return this._isEnabled;
  37325. },
  37326. /**
  37327. * Sets wether the image processing is enabled or not.
  37328. */
  37329. set: function (value) {
  37330. if (this._isEnabled === value) {
  37331. return;
  37332. }
  37333. this._isEnabled = value;
  37334. this._updateParameters();
  37335. },
  37336. enumerable: true,
  37337. configurable: true
  37338. });
  37339. /**
  37340. * Method called each time the image processing information changes requires to recompile the effect.
  37341. */
  37342. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37343. this.onUpdateParameters.notifyObservers(this);
  37344. };
  37345. ImageProcessingConfiguration.prototype.getClassName = function () {
  37346. return "ImageProcessingConfiguration";
  37347. };
  37348. /**
  37349. * Prepare the list of uniforms associated with the Image Processing effects.
  37350. * @param uniformsList The list of uniforms used in the effect
  37351. * @param defines the list of defines currently in use
  37352. */
  37353. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37354. if (defines.EXPOSURE) {
  37355. uniforms.push("exposureLinear");
  37356. }
  37357. if (defines.CONTRAST) {
  37358. uniforms.push("contrast");
  37359. }
  37360. if (defines.COLORGRADING) {
  37361. uniforms.push("colorTransformSettings");
  37362. }
  37363. if (defines.VIGNETTE) {
  37364. uniforms.push("vInverseScreenSize");
  37365. uniforms.push("vignetteSettings1");
  37366. uniforms.push("vignetteSettings2");
  37367. }
  37368. if (defines.COLORCURVES) {
  37369. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37370. }
  37371. if (defines.GRAIN) {
  37372. uniforms.push("grainVarianceAmount");
  37373. uniforms.push("grainAnimatedSeed");
  37374. }
  37375. };
  37376. /**
  37377. * Prepare the list of samplers associated with the Image Processing effects.
  37378. * @param uniformsList The list of uniforms used in the effect
  37379. * @param defines the list of defines currently in use
  37380. */
  37381. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37382. if (defines.COLORGRADING) {
  37383. samplersList.push("txColorTransform");
  37384. }
  37385. };
  37386. /**
  37387. * Prepare the list of defines associated to the shader.
  37388. * @param defines the list of defines to complete
  37389. */
  37390. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37391. if (forPostProcess === void 0) { forPostProcess = false; }
  37392. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37393. defines.VIGNETTE = false;
  37394. defines.TONEMAPPING = false;
  37395. defines.CONTRAST = false;
  37396. defines.EXPOSURE = false;
  37397. defines.COLORCURVES = false;
  37398. defines.COLORGRADING = false;
  37399. defines.COLORGRADING3D = false;
  37400. defines.IMAGEPROCESSING = false;
  37401. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37402. return;
  37403. }
  37404. defines.VIGNETTE = this.vignetteEnabled;
  37405. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37406. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37407. defines.TONEMAPPING = this.toneMappingEnabled;
  37408. defines.CONTRAST = (this.contrast !== 1.0);
  37409. defines.EXPOSURE = (this.exposure !== 1.0);
  37410. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37411. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37412. if (defines.COLORGRADING) {
  37413. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37414. }
  37415. else {
  37416. defines.COLORGRADING3D = false;
  37417. }
  37418. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37419. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37420. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37421. defines.GRAIN = this.grainEnabled;
  37422. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37423. };
  37424. /**
  37425. * Returns true if all the image processing information are ready.
  37426. */
  37427. ImageProcessingConfiguration.prototype.isReady = function () {
  37428. // Color Grading texure can not be none blocking.
  37429. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37430. };
  37431. /**
  37432. * Binds the image processing to the shader.
  37433. * @param effect The effect to bind to
  37434. */
  37435. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37436. if (aspectRatio === void 0) { aspectRatio = 1; }
  37437. // Color Curves
  37438. if (this._colorCurvesEnabled && this.colorCurves) {
  37439. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37440. }
  37441. // Vignette
  37442. if (this._vignetteEnabled) {
  37443. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37444. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37445. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37446. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37447. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37448. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37449. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37450. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37451. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37452. var vignettePower = -2.0 * this.vignetteWeight;
  37453. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37454. }
  37455. // Exposure
  37456. effect.setFloat("exposureLinear", this.exposure);
  37457. // Contrast
  37458. effect.setFloat("contrast", this.contrast);
  37459. // Color transform settings
  37460. if (this.colorGradingTexture) {
  37461. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37462. var textureSize = this.colorGradingTexture.getSize().height;
  37463. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37464. 0.5 / textureSize, // textureOffset
  37465. textureSize, // textureSize
  37466. this.colorGradingTexture.level // weight
  37467. );
  37468. }
  37469. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37470. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37471. };
  37472. /**
  37473. * Clones the current image processing instance.
  37474. * @return The cloned image processing
  37475. */
  37476. ImageProcessingConfiguration.prototype.clone = function () {
  37477. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37478. };
  37479. /**
  37480. * Serializes the current image processing instance to a json representation.
  37481. * @return a JSON representation
  37482. */
  37483. ImageProcessingConfiguration.prototype.serialize = function () {
  37484. return BABYLON.SerializationHelper.Serialize(this);
  37485. };
  37486. /**
  37487. * Parses the image processing from a json representation.
  37488. * @param source the JSON source to parse
  37489. * @return The parsed image processing
  37490. */
  37491. ImageProcessingConfiguration.Parse = function (source) {
  37492. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37493. };
  37494. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37495. /**
  37496. * Used to apply the vignette as a mix with the pixel color.
  37497. */
  37498. get: function () {
  37499. return this._VIGNETTEMODE_MULTIPLY;
  37500. },
  37501. enumerable: true,
  37502. configurable: true
  37503. });
  37504. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37505. /**
  37506. * Used to apply the vignette as a replacement of the pixel color.
  37507. */
  37508. get: function () {
  37509. return this._VIGNETTEMODE_OPAQUE;
  37510. },
  37511. enumerable: true,
  37512. configurable: true
  37513. });
  37514. // Static constants associated to the image processing.
  37515. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37516. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37517. __decorate([
  37518. BABYLON.serializeAsColorCurves()
  37519. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37520. __decorate([
  37521. BABYLON.serialize()
  37522. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37523. __decorate([
  37524. BABYLON.serializeAsTexture()
  37525. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37526. __decorate([
  37527. BABYLON.serialize()
  37528. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37529. __decorate([
  37530. BABYLON.serialize()
  37531. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37532. __decorate([
  37533. BABYLON.serialize()
  37534. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37535. __decorate([
  37536. BABYLON.serialize()
  37537. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37538. __decorate([
  37539. BABYLON.serialize()
  37540. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37541. __decorate([
  37542. BABYLON.serialize()
  37543. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37544. __decorate([
  37545. BABYLON.serialize()
  37546. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37547. __decorate([
  37548. BABYLON.serialize()
  37549. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37550. __decorate([
  37551. BABYLON.serialize()
  37552. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37553. __decorate([
  37554. BABYLON.serialize()
  37555. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37556. __decorate([
  37557. BABYLON.serializeAsColor4()
  37558. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37559. __decorate([
  37560. BABYLON.serialize()
  37561. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37562. __decorate([
  37563. BABYLON.serialize()
  37564. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37565. __decorate([
  37566. BABYLON.serialize()
  37567. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37568. __decorate([
  37569. BABYLON.serialize()
  37570. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37571. __decorate([
  37572. BABYLON.serialize()
  37573. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37574. __decorate([
  37575. BABYLON.serialize()
  37576. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37577. __decorate([
  37578. BABYLON.serialize()
  37579. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37580. __decorate([
  37581. BABYLON.serialize()
  37582. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37583. return ImageProcessingConfiguration;
  37584. }());
  37585. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37586. })(BABYLON || (BABYLON = {}));
  37587. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37588. var BABYLON;
  37589. (function (BABYLON) {
  37590. /**
  37591. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37592. * It can help converting any input color in a desired output one. This can then be used to create effects
  37593. * from sepia, black and white to sixties or futuristic rendering...
  37594. *
  37595. * The only supported format is currently 3dl.
  37596. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37597. */
  37598. var ColorGradingTexture = /** @class */ (function (_super) {
  37599. __extends(ColorGradingTexture, _super);
  37600. /**
  37601. * Instantiates a ColorGradingTexture from the following parameters.
  37602. *
  37603. * @param url The location of the color gradind data (currently only supporting 3dl)
  37604. * @param scene The scene the texture will be used in
  37605. */
  37606. function ColorGradingTexture(url, scene) {
  37607. var _this = _super.call(this, scene) || this;
  37608. if (!url) {
  37609. return _this;
  37610. }
  37611. _this._engine = scene.getEngine();
  37612. _this._textureMatrix = BABYLON.Matrix.Identity();
  37613. _this.name = url;
  37614. _this.url = url;
  37615. _this.hasAlpha = false;
  37616. _this.isCube = false;
  37617. _this.is3D = _this._engine.webGLVersion > 1;
  37618. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37619. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37620. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37621. _this.anisotropicFilteringLevel = 1;
  37622. _this._texture = _this._getFromCache(url, true);
  37623. if (!_this._texture) {
  37624. if (!scene.useDelayedTextureLoading) {
  37625. _this.loadTexture();
  37626. }
  37627. else {
  37628. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37629. }
  37630. }
  37631. return _this;
  37632. }
  37633. /**
  37634. * Returns the texture matrix used in most of the material.
  37635. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37636. */
  37637. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37638. return this._textureMatrix;
  37639. };
  37640. /**
  37641. * Occurs when the file being loaded is a .3dl LUT file.
  37642. */
  37643. ColorGradingTexture.prototype.load3dlTexture = function () {
  37644. var engine = this._engine;
  37645. var texture;
  37646. if (engine.webGLVersion === 1) {
  37647. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37648. }
  37649. else {
  37650. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37651. }
  37652. this._texture = texture;
  37653. var callback = function (text) {
  37654. if (typeof text !== "string") {
  37655. return;
  37656. }
  37657. var data = null;
  37658. var tempData = null;
  37659. var line;
  37660. var lines = text.split('\n');
  37661. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37662. var maxColor = 0;
  37663. for (var i = 0; i < lines.length; i++) {
  37664. line = lines[i];
  37665. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37666. continue;
  37667. if (line.indexOf('#') === 0)
  37668. continue;
  37669. var words = line.split(" ");
  37670. if (size === 0) {
  37671. // Number of space + one
  37672. size = words.length;
  37673. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37674. tempData = new Float32Array(size * size * size * 4);
  37675. continue;
  37676. }
  37677. if (size != 0) {
  37678. var r = Math.max(parseInt(words[0]), 0);
  37679. var g = Math.max(parseInt(words[1]), 0);
  37680. var b = Math.max(parseInt(words[2]), 0);
  37681. maxColor = Math.max(r, maxColor);
  37682. maxColor = Math.max(g, maxColor);
  37683. maxColor = Math.max(b, maxColor);
  37684. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37685. if (tempData) {
  37686. tempData[pixelStorageIndex + 0] = r;
  37687. tempData[pixelStorageIndex + 1] = g;
  37688. tempData[pixelStorageIndex + 2] = b;
  37689. }
  37690. pixelIndexSlice++;
  37691. if (pixelIndexSlice % size == 0) {
  37692. pixelIndexH++;
  37693. pixelIndexSlice = 0;
  37694. if (pixelIndexH % size == 0) {
  37695. pixelIndexW++;
  37696. pixelIndexH = 0;
  37697. }
  37698. }
  37699. }
  37700. }
  37701. if (tempData && data) {
  37702. for (var i = 0; i < tempData.length; i++) {
  37703. if (i > 0 && (i + 1) % 4 === 0) {
  37704. data[i] = 255;
  37705. }
  37706. else {
  37707. var value = tempData[i];
  37708. data[i] = (value / maxColor * 255);
  37709. }
  37710. }
  37711. }
  37712. if (texture.is3D) {
  37713. texture.updateSize(size, size, size);
  37714. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37715. }
  37716. else {
  37717. texture.updateSize(size * size, size);
  37718. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37719. }
  37720. };
  37721. var scene = this.getScene();
  37722. if (scene) {
  37723. scene._loadFile(this.url, callback);
  37724. }
  37725. else {
  37726. this._engine._loadFile(this.url, callback);
  37727. }
  37728. return this._texture;
  37729. };
  37730. /**
  37731. * Starts the loading process of the texture.
  37732. */
  37733. ColorGradingTexture.prototype.loadTexture = function () {
  37734. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37735. this.load3dlTexture();
  37736. }
  37737. };
  37738. /**
  37739. * Clones the color gradind texture.
  37740. */
  37741. ColorGradingTexture.prototype.clone = function () {
  37742. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37743. // Base texture
  37744. newTexture.level = this.level;
  37745. return newTexture;
  37746. };
  37747. /**
  37748. * Called during delayed load for textures.
  37749. */
  37750. ColorGradingTexture.prototype.delayLoad = function () {
  37751. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37752. return;
  37753. }
  37754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37755. this._texture = this._getFromCache(this.url, true);
  37756. if (!this._texture) {
  37757. this.loadTexture();
  37758. }
  37759. };
  37760. /**
  37761. * Parses a color grading texture serialized by Babylon.
  37762. * @param parsedTexture The texture information being parsedTexture
  37763. * @param scene The scene to load the texture in
  37764. * @param rootUrl The root url of the data assets to load
  37765. * @return A color gradind texture
  37766. */
  37767. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37768. var texture = null;
  37769. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37770. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37771. texture.name = parsedTexture.name;
  37772. texture.level = parsedTexture.level;
  37773. }
  37774. return texture;
  37775. };
  37776. /**
  37777. * Serializes the LUT texture to json format.
  37778. */
  37779. ColorGradingTexture.prototype.serialize = function () {
  37780. if (!this.name) {
  37781. return null;
  37782. }
  37783. var serializationObject = {};
  37784. serializationObject.name = this.name;
  37785. serializationObject.level = this.level;
  37786. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37787. return serializationObject;
  37788. };
  37789. /**
  37790. * Empty line regex stored for GC.
  37791. */
  37792. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37793. return ColorGradingTexture;
  37794. }(BABYLON.BaseTexture));
  37795. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37796. })(BABYLON || (BABYLON = {}));
  37797. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37798. var BABYLON;
  37799. (function (BABYLON) {
  37800. /**
  37801. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37802. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37803. * 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;
  37804. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37805. */
  37806. var ColorCurves = /** @class */ (function () {
  37807. function ColorCurves() {
  37808. this._dirty = true;
  37809. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37810. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37811. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37812. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37813. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37814. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37815. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37816. this._globalHue = 30;
  37817. this._globalDensity = 0;
  37818. this._globalSaturation = 0;
  37819. this._globalExposure = 0;
  37820. this._highlightsHue = 30;
  37821. this._highlightsDensity = 0;
  37822. this._highlightsSaturation = 0;
  37823. this._highlightsExposure = 0;
  37824. this._midtonesHue = 30;
  37825. this._midtonesDensity = 0;
  37826. this._midtonesSaturation = 0;
  37827. this._midtonesExposure = 0;
  37828. this._shadowsHue = 30;
  37829. this._shadowsDensity = 0;
  37830. this._shadowsSaturation = 0;
  37831. this._shadowsExposure = 0;
  37832. }
  37833. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37834. /**
  37835. * Gets the global Hue value.
  37836. * 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).
  37837. */
  37838. get: function () {
  37839. return this._globalHue;
  37840. },
  37841. /**
  37842. * Sets the global Hue value.
  37843. * 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).
  37844. */
  37845. set: function (value) {
  37846. this._globalHue = value;
  37847. this._dirty = true;
  37848. },
  37849. enumerable: true,
  37850. configurable: true
  37851. });
  37852. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37853. /**
  37854. * Gets the global Density value.
  37855. * 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.
  37856. * Values less than zero provide a filter of opposite hue.
  37857. */
  37858. get: function () {
  37859. return this._globalDensity;
  37860. },
  37861. /**
  37862. * Sets the global Density value.
  37863. * 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.
  37864. * Values less than zero provide a filter of opposite hue.
  37865. */
  37866. set: function (value) {
  37867. this._globalDensity = value;
  37868. this._dirty = true;
  37869. },
  37870. enumerable: true,
  37871. configurable: true
  37872. });
  37873. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37874. /**
  37875. * Gets the global Saturation value.
  37876. * 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.
  37877. */
  37878. get: function () {
  37879. return this._globalSaturation;
  37880. },
  37881. /**
  37882. * Sets the global Saturation value.
  37883. * 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.
  37884. */
  37885. set: function (value) {
  37886. this._globalSaturation = value;
  37887. this._dirty = true;
  37888. },
  37889. enumerable: true,
  37890. configurable: true
  37891. });
  37892. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37893. /**
  37894. * Gets the highlights Hue value.
  37895. * 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).
  37896. */
  37897. get: function () {
  37898. return this._highlightsHue;
  37899. },
  37900. /**
  37901. * Sets the highlights Hue value.
  37902. * 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).
  37903. */
  37904. set: function (value) {
  37905. this._highlightsHue = value;
  37906. this._dirty = true;
  37907. },
  37908. enumerable: true,
  37909. configurable: true
  37910. });
  37911. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37912. /**
  37913. * Gets the highlights Density value.
  37914. * 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.
  37915. * Values less than zero provide a filter of opposite hue.
  37916. */
  37917. get: function () {
  37918. return this._highlightsDensity;
  37919. },
  37920. /**
  37921. * Sets the highlights Density value.
  37922. * 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.
  37923. * Values less than zero provide a filter of opposite hue.
  37924. */
  37925. set: function (value) {
  37926. this._highlightsDensity = value;
  37927. this._dirty = true;
  37928. },
  37929. enumerable: true,
  37930. configurable: true
  37931. });
  37932. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37933. /**
  37934. * Gets the highlights Saturation value.
  37935. * 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.
  37936. */
  37937. get: function () {
  37938. return this._highlightsSaturation;
  37939. },
  37940. /**
  37941. * Sets the highlights Saturation value.
  37942. * 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.
  37943. */
  37944. set: function (value) {
  37945. this._highlightsSaturation = value;
  37946. this._dirty = true;
  37947. },
  37948. enumerable: true,
  37949. configurable: true
  37950. });
  37951. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37952. /**
  37953. * Gets the highlights Exposure value.
  37954. * 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.
  37955. */
  37956. get: function () {
  37957. return this._highlightsExposure;
  37958. },
  37959. /**
  37960. * Sets the highlights Exposure value.
  37961. * 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.
  37962. */
  37963. set: function (value) {
  37964. this._highlightsExposure = value;
  37965. this._dirty = true;
  37966. },
  37967. enumerable: true,
  37968. configurable: true
  37969. });
  37970. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37971. /**
  37972. * Gets the midtones Hue value.
  37973. * 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).
  37974. */
  37975. get: function () {
  37976. return this._midtonesHue;
  37977. },
  37978. /**
  37979. * Sets the midtones Hue value.
  37980. * 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).
  37981. */
  37982. set: function (value) {
  37983. this._midtonesHue = value;
  37984. this._dirty = true;
  37985. },
  37986. enumerable: true,
  37987. configurable: true
  37988. });
  37989. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37990. /**
  37991. * Gets the midtones Density value.
  37992. * 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.
  37993. * Values less than zero provide a filter of opposite hue.
  37994. */
  37995. get: function () {
  37996. return this._midtonesDensity;
  37997. },
  37998. /**
  37999. * Sets the midtones Density value.
  38000. * 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.
  38001. * Values less than zero provide a filter of opposite hue.
  38002. */
  38003. set: function (value) {
  38004. this._midtonesDensity = value;
  38005. this._dirty = true;
  38006. },
  38007. enumerable: true,
  38008. configurable: true
  38009. });
  38010. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38011. /**
  38012. * Gets the midtones Saturation value.
  38013. * 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.
  38014. */
  38015. get: function () {
  38016. return this._midtonesSaturation;
  38017. },
  38018. /**
  38019. * Sets the midtones Saturation value.
  38020. * 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.
  38021. */
  38022. set: function (value) {
  38023. this._midtonesSaturation = value;
  38024. this._dirty = true;
  38025. },
  38026. enumerable: true,
  38027. configurable: true
  38028. });
  38029. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38030. /**
  38031. * Gets the midtones Exposure value.
  38032. * 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.
  38033. */
  38034. get: function () {
  38035. return this._midtonesExposure;
  38036. },
  38037. /**
  38038. * Sets the midtones Exposure value.
  38039. * 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.
  38040. */
  38041. set: function (value) {
  38042. this._midtonesExposure = value;
  38043. this._dirty = true;
  38044. },
  38045. enumerable: true,
  38046. configurable: true
  38047. });
  38048. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38049. /**
  38050. * Gets the shadows Hue value.
  38051. * 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).
  38052. */
  38053. get: function () {
  38054. return this._shadowsHue;
  38055. },
  38056. /**
  38057. * Sets the shadows Hue value.
  38058. * 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).
  38059. */
  38060. set: function (value) {
  38061. this._shadowsHue = value;
  38062. this._dirty = true;
  38063. },
  38064. enumerable: true,
  38065. configurable: true
  38066. });
  38067. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38068. /**
  38069. * Gets the shadows Density value.
  38070. * 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.
  38071. * Values less than zero provide a filter of opposite hue.
  38072. */
  38073. get: function () {
  38074. return this._shadowsDensity;
  38075. },
  38076. /**
  38077. * Sets the shadows Density value.
  38078. * 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.
  38079. * Values less than zero provide a filter of opposite hue.
  38080. */
  38081. set: function (value) {
  38082. this._shadowsDensity = value;
  38083. this._dirty = true;
  38084. },
  38085. enumerable: true,
  38086. configurable: true
  38087. });
  38088. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38089. /**
  38090. * Gets the shadows Saturation value.
  38091. * 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.
  38092. */
  38093. get: function () {
  38094. return this._shadowsSaturation;
  38095. },
  38096. /**
  38097. * Sets the shadows Saturation value.
  38098. * 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.
  38099. */
  38100. set: function (value) {
  38101. this._shadowsSaturation = value;
  38102. this._dirty = true;
  38103. },
  38104. enumerable: true,
  38105. configurable: true
  38106. });
  38107. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38108. /**
  38109. * Gets the shadows Exposure value.
  38110. * 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.
  38111. */
  38112. get: function () {
  38113. return this._shadowsExposure;
  38114. },
  38115. /**
  38116. * Sets the shadows Exposure value.
  38117. * 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.
  38118. */
  38119. set: function (value) {
  38120. this._shadowsExposure = value;
  38121. this._dirty = true;
  38122. },
  38123. enumerable: true,
  38124. configurable: true
  38125. });
  38126. ColorCurves.prototype.getClassName = function () {
  38127. return "ColorCurves";
  38128. };
  38129. /**
  38130. * Binds the color curves to the shader.
  38131. * @param colorCurves The color curve to bind
  38132. * @param effect The effect to bind to
  38133. */
  38134. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38135. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38136. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38137. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38138. if (colorCurves._dirty) {
  38139. colorCurves._dirty = false;
  38140. // Fill in global info.
  38141. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38142. // Compute highlights info.
  38143. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38144. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38145. // Compute midtones info.
  38146. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38147. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38148. // Compute shadows info.
  38149. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38150. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38151. // Compute deltas (neutral is midtones).
  38152. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38153. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38154. }
  38155. if (effect) {
  38156. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38157. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38158. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38159. }
  38160. };
  38161. /**
  38162. * Prepare the list of uniforms associated with the ColorCurves effects.
  38163. * @param uniformsList The list of uniforms used in the effect
  38164. */
  38165. ColorCurves.PrepareUniforms = function (uniformsList) {
  38166. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38167. };
  38168. /**
  38169. * Returns color grading data based on a hue, density, saturation and exposure value.
  38170. * @param filterHue The hue of the color filter.
  38171. * @param filterDensity The density of the color filter.
  38172. * @param saturation The saturation.
  38173. * @param exposure The exposure.
  38174. * @param result The result data container.
  38175. */
  38176. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38177. if (hue == null) {
  38178. return;
  38179. }
  38180. hue = ColorCurves.clamp(hue, 0, 360);
  38181. density = ColorCurves.clamp(density, -100, 100);
  38182. saturation = ColorCurves.clamp(saturation, -100, 100);
  38183. exposure = ColorCurves.clamp(exposure, -100, 100);
  38184. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38185. // so that the maximum filter density is only 50% control. This provides fine control
  38186. // for small values and reasonable range.
  38187. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38188. density *= 0.5;
  38189. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38190. if (density < 0) {
  38191. density *= -1;
  38192. hue = (hue + 180) % 360;
  38193. }
  38194. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38195. result.scaleToRef(2, result);
  38196. result.a = 1 + 0.01 * saturation;
  38197. };
  38198. /**
  38199. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38200. * @param value The input slider value in range [-100,100].
  38201. * @returns Adjusted value.
  38202. */
  38203. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38204. value /= 100;
  38205. var x = Math.abs(value);
  38206. x = Math.pow(x, 2);
  38207. if (value < 0) {
  38208. x *= -1;
  38209. }
  38210. x *= 100;
  38211. return x;
  38212. };
  38213. /**
  38214. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38215. * @param hue The hue (H) input.
  38216. * @param saturation The saturation (S) input.
  38217. * @param brightness The brightness (B) input.
  38218. * @result An RGBA color represented as Vector4.
  38219. */
  38220. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38221. var h = ColorCurves.clamp(hue, 0, 360);
  38222. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38223. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38224. if (s === 0) {
  38225. result.r = v;
  38226. result.g = v;
  38227. result.b = v;
  38228. }
  38229. else {
  38230. // sector 0 to 5
  38231. h /= 60;
  38232. var i = Math.floor(h);
  38233. // fractional part of h
  38234. var f = h - i;
  38235. var p = v * (1 - s);
  38236. var q = v * (1 - s * f);
  38237. var t = v * (1 - s * (1 - f));
  38238. switch (i) {
  38239. case 0:
  38240. result.r = v;
  38241. result.g = t;
  38242. result.b = p;
  38243. break;
  38244. case 1:
  38245. result.r = q;
  38246. result.g = v;
  38247. result.b = p;
  38248. break;
  38249. case 2:
  38250. result.r = p;
  38251. result.g = v;
  38252. result.b = t;
  38253. break;
  38254. case 3:
  38255. result.r = p;
  38256. result.g = q;
  38257. result.b = v;
  38258. break;
  38259. case 4:
  38260. result.r = t;
  38261. result.g = p;
  38262. result.b = v;
  38263. break;
  38264. default:// case 5:
  38265. result.r = v;
  38266. result.g = p;
  38267. result.b = q;
  38268. break;
  38269. }
  38270. }
  38271. result.a = 1;
  38272. };
  38273. /**
  38274. * Returns a value clamped between min and max
  38275. * @param value The value to clamp
  38276. * @param min The minimum of value
  38277. * @param max The maximum of value
  38278. * @returns The clamped value.
  38279. */
  38280. ColorCurves.clamp = function (value, min, max) {
  38281. return Math.min(Math.max(value, min), max);
  38282. };
  38283. /**
  38284. * Clones the current color curve instance.
  38285. * @return The cloned curves
  38286. */
  38287. ColorCurves.prototype.clone = function () {
  38288. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38289. };
  38290. /**
  38291. * Serializes the current color curve instance to a json representation.
  38292. * @return a JSON representation
  38293. */
  38294. ColorCurves.prototype.serialize = function () {
  38295. return BABYLON.SerializationHelper.Serialize(this);
  38296. };
  38297. /**
  38298. * Parses the color curve from a json representation.
  38299. * @param source the JSON source to parse
  38300. * @return The parsed curves
  38301. */
  38302. ColorCurves.Parse = function (source) {
  38303. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38304. };
  38305. __decorate([
  38306. BABYLON.serialize()
  38307. ], ColorCurves.prototype, "_globalHue", void 0);
  38308. __decorate([
  38309. BABYLON.serialize()
  38310. ], ColorCurves.prototype, "_globalDensity", void 0);
  38311. __decorate([
  38312. BABYLON.serialize()
  38313. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38314. __decorate([
  38315. BABYLON.serialize()
  38316. ], ColorCurves.prototype, "_globalExposure", void 0);
  38317. __decorate([
  38318. BABYLON.serialize()
  38319. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38320. __decorate([
  38321. BABYLON.serialize()
  38322. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38323. __decorate([
  38324. BABYLON.serialize()
  38325. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38326. __decorate([
  38327. BABYLON.serialize()
  38328. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38329. __decorate([
  38330. BABYLON.serialize()
  38331. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38332. __decorate([
  38333. BABYLON.serialize()
  38334. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38335. __decorate([
  38336. BABYLON.serialize()
  38337. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38338. __decorate([
  38339. BABYLON.serialize()
  38340. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38341. return ColorCurves;
  38342. }());
  38343. BABYLON.ColorCurves = ColorCurves;
  38344. })(BABYLON || (BABYLON = {}));
  38345. //# sourceMappingURL=babylon.colorCurves.js.map
  38346. //# sourceMappingURL=babylon.behavior.js.map
  38347. var BABYLON;
  38348. (function (BABYLON) {
  38349. /**
  38350. * "Static Class" containing the most commonly used helper while dealing with material for
  38351. * rendering purpose.
  38352. *
  38353. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38354. *
  38355. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38356. */
  38357. var MaterialHelper = /** @class */ (function () {
  38358. function MaterialHelper() {
  38359. }
  38360. /**
  38361. * Bind the current view position to an effect.
  38362. * @param effect The effect to be bound
  38363. * @param scene The scene the eyes position is used from
  38364. */
  38365. MaterialHelper.BindEyePosition = function (effect, scene) {
  38366. if (scene._forcedViewPosition) {
  38367. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38368. return;
  38369. }
  38370. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38371. };
  38372. /**
  38373. * Helps preparing the defines values about the UVs in used in the effect.
  38374. * UVs are shared as much as we can accross chanels in the shaders.
  38375. * @param texture The texture we are preparing the UVs for
  38376. * @param defines The defines to update
  38377. * @param key The chanel key "diffuse", "specular"... used in the shader
  38378. */
  38379. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38380. defines._needUVs = true;
  38381. defines[key] = true;
  38382. if (texture.getTextureMatrix().isIdentity(true)) {
  38383. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38384. if (texture.coordinatesIndex === 0) {
  38385. defines["MAINUV1"] = true;
  38386. }
  38387. else {
  38388. defines["MAINUV2"] = true;
  38389. }
  38390. }
  38391. else {
  38392. defines[key + "DIRECTUV"] = 0;
  38393. }
  38394. };
  38395. /**
  38396. * Binds a texture matrix value to its corrsponding uniform
  38397. * @param texture The texture to bind the matrix for
  38398. * @param uniformBuffer The uniform buffer receivin the data
  38399. * @param key The chanel key "diffuse", "specular"... used in the shader
  38400. */
  38401. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38402. var matrix = texture.getTextureMatrix();
  38403. if (!matrix.isIdentity(true)) {
  38404. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38405. }
  38406. };
  38407. /**
  38408. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38409. * @param mesh defines the current mesh
  38410. * @param scene defines the current scene
  38411. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38412. * @param pointsCloud defines if point cloud rendering has to be turned on
  38413. * @param fogEnabled defines if fog has to be turned on
  38414. * @param alphaTest defines if alpha testing has to be turned on
  38415. * @param defines defines the current list of defines
  38416. */
  38417. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38418. if (defines._areMiscDirty) {
  38419. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38420. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38421. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38422. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38423. defines["ALPHATEST"] = alphaTest;
  38424. }
  38425. };
  38426. /**
  38427. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38428. * @param scene defines the current scene
  38429. * @param engine defines the current engine
  38430. * @param defines specifies the list of active defines
  38431. * @param useInstances defines if instances have to be turned on
  38432. * @param useClipPlane defines if clip plane have to be turned on
  38433. */
  38434. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38435. if (useClipPlane === void 0) { useClipPlane = null; }
  38436. var changed = false;
  38437. if (useClipPlane == null) {
  38438. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38439. }
  38440. if (defines["CLIPPLANE"] !== useClipPlane) {
  38441. defines["CLIPPLANE"] = useClipPlane;
  38442. changed = true;
  38443. }
  38444. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38445. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38446. changed = true;
  38447. }
  38448. if (defines["INSTANCES"] !== useInstances) {
  38449. defines["INSTANCES"] = useInstances;
  38450. changed = true;
  38451. }
  38452. if (changed) {
  38453. defines.markAsUnprocessed();
  38454. }
  38455. };
  38456. /**
  38457. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38458. * @param mesh The mesh containing the geometry data we will draw
  38459. * @param defines The defines to update
  38460. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38461. * @param useBones Precise whether bones should be used or not (override mesh info)
  38462. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38463. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38464. * @returns false if defines are considered not dirty and have not been checked
  38465. */
  38466. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38467. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38468. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38469. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38470. return false;
  38471. }
  38472. defines._normals = defines._needNormals;
  38473. defines._uvs = defines._needUVs;
  38474. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38475. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38476. defines["TANGENT"] = true;
  38477. }
  38478. if (defines._needUVs) {
  38479. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38480. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38481. }
  38482. else {
  38483. defines["UV1"] = false;
  38484. defines["UV2"] = false;
  38485. }
  38486. if (useVertexColor) {
  38487. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38488. defines["VERTEXCOLOR"] = hasVertexColors;
  38489. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38490. }
  38491. if (useBones) {
  38492. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38493. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38494. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38495. }
  38496. else {
  38497. defines["NUM_BONE_INFLUENCERS"] = 0;
  38498. defines["BonesPerMesh"] = 0;
  38499. }
  38500. }
  38501. if (useMorphTargets) {
  38502. var manager = mesh.morphTargetManager;
  38503. if (manager) {
  38504. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38505. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38506. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38507. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38508. }
  38509. else {
  38510. defines["MORPHTARGETS_TANGENT"] = false;
  38511. defines["MORPHTARGETS_NORMAL"] = false;
  38512. defines["MORPHTARGETS"] = false;
  38513. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38514. }
  38515. }
  38516. return true;
  38517. };
  38518. /**
  38519. * Prepares the defines related to the light information passed in parameter
  38520. * @param scene The scene we are intending to draw
  38521. * @param mesh The mesh the effect is compiling for
  38522. * @param defines The defines to update
  38523. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38524. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38525. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38526. * @returns true if normals will be required for the rest of the effect
  38527. */
  38528. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38529. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38530. if (disableLighting === void 0) { disableLighting = false; }
  38531. if (!defines._areLightsDirty) {
  38532. return defines._needNormals;
  38533. }
  38534. var lightIndex = 0;
  38535. var needNormals = false;
  38536. var needRebuild = false;
  38537. var lightmapMode = false;
  38538. var shadowEnabled = false;
  38539. var specularEnabled = false;
  38540. if (scene.lightsEnabled && !disableLighting) {
  38541. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38542. var light = _a[_i];
  38543. needNormals = true;
  38544. if (defines["LIGHT" + lightIndex] === undefined) {
  38545. needRebuild = true;
  38546. }
  38547. defines["LIGHT" + lightIndex] = true;
  38548. defines["SPOTLIGHT" + lightIndex] = false;
  38549. defines["HEMILIGHT" + lightIndex] = false;
  38550. defines["POINTLIGHT" + lightIndex] = false;
  38551. defines["DIRLIGHT" + lightIndex] = false;
  38552. var type;
  38553. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38554. type = "SPOTLIGHT" + lightIndex;
  38555. var spotLight = light;
  38556. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38557. }
  38558. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38559. type = "HEMILIGHT" + lightIndex;
  38560. }
  38561. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38562. type = "POINTLIGHT" + lightIndex;
  38563. }
  38564. else {
  38565. type = "DIRLIGHT" + lightIndex;
  38566. }
  38567. defines[type] = true;
  38568. // Specular
  38569. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38570. specularEnabled = true;
  38571. }
  38572. // Shadows
  38573. defines["SHADOW" + lightIndex] = false;
  38574. defines["SHADOWPCF" + lightIndex] = false;
  38575. defines["SHADOWESM" + lightIndex] = false;
  38576. defines["SHADOWCUBE" + lightIndex] = false;
  38577. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38578. var shadowGenerator = light.getShadowGenerator();
  38579. if (shadowGenerator) {
  38580. shadowEnabled = true;
  38581. shadowGenerator.prepareDefines(defines, lightIndex);
  38582. }
  38583. }
  38584. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38585. lightmapMode = true;
  38586. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38587. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38588. }
  38589. else {
  38590. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38591. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38592. }
  38593. lightIndex++;
  38594. if (lightIndex === maxSimultaneousLights)
  38595. break;
  38596. }
  38597. }
  38598. defines["SPECULARTERM"] = specularEnabled;
  38599. defines["SHADOWS"] = shadowEnabled;
  38600. // Resetting all other lights if any
  38601. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38602. if (defines["LIGHT" + index] !== undefined) {
  38603. defines["LIGHT" + index] = false;
  38604. defines["HEMILIGHT" + lightIndex] = false;
  38605. defines["POINTLIGHT" + lightIndex] = false;
  38606. defines["DIRLIGHT" + lightIndex] = false;
  38607. defines["SPOTLIGHT" + lightIndex] = false;
  38608. defines["SHADOW" + lightIndex] = false;
  38609. }
  38610. }
  38611. var caps = scene.getEngine().getCaps();
  38612. if (defines["SHADOWFLOAT"] === undefined) {
  38613. needRebuild = true;
  38614. }
  38615. defines["SHADOWFLOAT"] = shadowEnabled &&
  38616. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38617. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38618. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38619. if (needRebuild) {
  38620. defines.rebuild();
  38621. }
  38622. return needNormals;
  38623. };
  38624. /**
  38625. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38626. * that won t be acctive due to defines being turned off.
  38627. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38628. * @param samplersList The samplers list
  38629. * @param defines The defines helping in the list generation
  38630. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38631. */
  38632. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38633. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38634. var uniformsList;
  38635. var uniformBuffersList = null;
  38636. if (uniformsListOrOptions.uniformsNames) {
  38637. var options = uniformsListOrOptions;
  38638. uniformsList = options.uniformsNames;
  38639. uniformBuffersList = options.uniformBuffersNames;
  38640. samplersList = options.samplers;
  38641. defines = options.defines;
  38642. maxSimultaneousLights = options.maxSimultaneousLights;
  38643. }
  38644. else {
  38645. uniformsList = uniformsListOrOptions;
  38646. if (!samplersList) {
  38647. samplersList = [];
  38648. }
  38649. }
  38650. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38651. if (!defines["LIGHT" + lightIndex]) {
  38652. break;
  38653. }
  38654. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38655. if (uniformBuffersList) {
  38656. uniformBuffersList.push("Light" + lightIndex);
  38657. }
  38658. samplersList.push("shadowSampler" + lightIndex);
  38659. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38660. samplersList.push("projectionLightSampler" + lightIndex);
  38661. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38662. }
  38663. }
  38664. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38665. uniformsList.push("morphTargetInfluences");
  38666. }
  38667. };
  38668. /**
  38669. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38670. * @param defines The defines to update while falling back
  38671. * @param fallbacks The authorized effect fallbacks
  38672. * @param maxSimultaneousLights The maximum number of lights allowed
  38673. * @param rank the current rank of the Effect
  38674. * @returns The newly affected rank
  38675. */
  38676. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38677. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38678. if (rank === void 0) { rank = 0; }
  38679. var lightFallbackRank = 0;
  38680. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38681. if (!defines["LIGHT" + lightIndex]) {
  38682. break;
  38683. }
  38684. if (lightIndex > 0) {
  38685. lightFallbackRank = rank + lightIndex;
  38686. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38687. }
  38688. if (!defines["SHADOWS"]) {
  38689. if (defines["SHADOW" + lightIndex]) {
  38690. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38691. }
  38692. if (defines["SHADOWPCF" + lightIndex]) {
  38693. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38694. }
  38695. if (defines["SHADOWESM" + lightIndex]) {
  38696. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38697. }
  38698. }
  38699. }
  38700. return lightFallbackRank++;
  38701. };
  38702. /**
  38703. * Prepares the list of attributes required for morph targets according to the effect defines.
  38704. * @param attribs The current list of supported attribs
  38705. * @param mesh The mesh to prepare the morph targets attributes for
  38706. * @param defines The current Defines of the effect
  38707. */
  38708. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38709. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38710. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38711. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38712. var manager = mesh.morphTargetManager;
  38713. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38714. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38715. for (var index = 0; index < influencers; index++) {
  38716. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38717. if (normal) {
  38718. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38719. }
  38720. if (tangent) {
  38721. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38722. }
  38723. if (attribs.length > maxAttributesCount) {
  38724. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38725. }
  38726. }
  38727. }
  38728. };
  38729. /**
  38730. * Prepares the list of attributes required for bones according to the effect defines.
  38731. * @param attribs The current list of supported attribs
  38732. * @param mesh The mesh to prepare the bones attributes for
  38733. * @param defines The current Defines of the effect
  38734. * @param fallbacks The current efffect fallback strategy
  38735. */
  38736. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38737. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38738. fallbacks.addCPUSkinningFallback(0, mesh);
  38739. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38740. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38741. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38744. }
  38745. }
  38746. };
  38747. /**
  38748. * Prepares the list of attributes required for instances according to the effect defines.
  38749. * @param attribs The current list of supported attribs
  38750. * @param defines The current Defines of the effect
  38751. */
  38752. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38753. if (defines["INSTANCES"]) {
  38754. attribs.push("world0");
  38755. attribs.push("world1");
  38756. attribs.push("world2");
  38757. attribs.push("world3");
  38758. }
  38759. };
  38760. /**
  38761. * Binds the light shadow information to the effect for the given mesh.
  38762. * @param light The light containing the generator
  38763. * @param scene The scene the lights belongs to
  38764. * @param mesh The mesh we are binding the information to render
  38765. * @param lightIndex The light index in the effect used to render the mesh
  38766. * @param effect The effect we are binding the data to
  38767. */
  38768. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38769. if (light.shadowEnabled && mesh.receiveShadows) {
  38770. var shadowGenerator = light.getShadowGenerator();
  38771. if (shadowGenerator) {
  38772. shadowGenerator.bindShadowLight(lightIndex, effect);
  38773. }
  38774. }
  38775. };
  38776. /**
  38777. * Binds the light information to the effect.
  38778. * @param light The light containing the generator
  38779. * @param effect The effect we are binding the data to
  38780. * @param lightIndex The light index in the effect used to render
  38781. */
  38782. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38783. light.transferToEffect(effect, lightIndex + "");
  38784. };
  38785. /**
  38786. * Binds the lights information from the scene to the effect for the given mesh.
  38787. * @param scene The scene the lights belongs to
  38788. * @param mesh The mesh we are binding the information to render
  38789. * @param effect The effect we are binding the data to
  38790. * @param defines The generated defines for the effect
  38791. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38792. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38793. */
  38794. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38795. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38796. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38797. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38798. for (var i = 0; i < len; i++) {
  38799. var light = mesh._lightSources[i];
  38800. var iAsString = i.toString();
  38801. var scaledIntensity = light.getScaledIntensity();
  38802. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38803. MaterialHelper.BindLightProperties(light, effect, i);
  38804. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38805. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38806. if (defines["SPECULARTERM"]) {
  38807. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38808. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38809. }
  38810. // Shadows
  38811. if (scene.shadowsEnabled) {
  38812. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38813. }
  38814. light._uniformBuffer.update();
  38815. }
  38816. };
  38817. /**
  38818. * Binds the fog information from the scene to the effect for the given mesh.
  38819. * @param scene The scene the lights belongs to
  38820. * @param mesh The mesh we are binding the information to render
  38821. * @param effect The effect we are binding the data to
  38822. */
  38823. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38824. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38825. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38826. effect.setColor3("vFogColor", scene.fogColor);
  38827. }
  38828. };
  38829. /**
  38830. * Binds the bones information from the mesh to the effect.
  38831. * @param mesh The mesh we are binding the information to render
  38832. * @param effect The effect we are binding the data to
  38833. */
  38834. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38835. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38836. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38837. if (matrices && effect) {
  38838. effect.setMatrices("mBones", matrices);
  38839. }
  38840. }
  38841. };
  38842. /**
  38843. * Binds the morph targets information from the mesh to the effect.
  38844. * @param abstractMesh The mesh we are binding the information to render
  38845. * @param effect The effect we are binding the data to
  38846. */
  38847. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38848. var manager = abstractMesh.morphTargetManager;
  38849. if (!abstractMesh || !manager) {
  38850. return;
  38851. }
  38852. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38853. };
  38854. /**
  38855. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38856. * @param defines The generated defines used in the effect
  38857. * @param effect The effect we are binding the data to
  38858. * @param scene The scene we are willing to render with logarithmic scale for
  38859. */
  38860. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38861. if (defines["LOGARITHMICDEPTH"]) {
  38862. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38863. }
  38864. };
  38865. /**
  38866. * Binds the clip plane information from the scene to the effect.
  38867. * @param scene The scene the clip plane information are extracted from
  38868. * @param effect The effect we are binding the data to
  38869. */
  38870. MaterialHelper.BindClipPlane = function (effect, scene) {
  38871. if (scene.clipPlane) {
  38872. var clipPlane = scene.clipPlane;
  38873. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38874. }
  38875. };
  38876. return MaterialHelper;
  38877. }());
  38878. BABYLON.MaterialHelper = MaterialHelper;
  38879. })(BABYLON || (BABYLON = {}));
  38880. //# sourceMappingURL=babylon.materialHelper.js.map
  38881. var BABYLON;
  38882. (function (BABYLON) {
  38883. var PushMaterial = /** @class */ (function (_super) {
  38884. __extends(PushMaterial, _super);
  38885. function PushMaterial(name, scene) {
  38886. var _this = _super.call(this, name, scene) || this;
  38887. _this._normalMatrix = new BABYLON.Matrix();
  38888. _this.storeEffectOnSubMeshes = true;
  38889. return _this;
  38890. }
  38891. PushMaterial.prototype.getEffect = function () {
  38892. return this._activeEffect;
  38893. };
  38894. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38895. if (!mesh) {
  38896. return false;
  38897. }
  38898. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38899. return true;
  38900. }
  38901. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38902. };
  38903. /**
  38904. * Binds the given world matrix to the active effect
  38905. *
  38906. * @param world the matrix to bind
  38907. */
  38908. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38909. this._activeEffect.setMatrix("world", world);
  38910. };
  38911. /**
  38912. * Binds the given normal matrix to the active effect
  38913. *
  38914. * @param normalMatrix the matrix to bind
  38915. */
  38916. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38917. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38918. };
  38919. PushMaterial.prototype.bind = function (world, mesh) {
  38920. if (!mesh) {
  38921. return;
  38922. }
  38923. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38924. };
  38925. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38926. if (effect === void 0) { effect = null; }
  38927. _super.prototype._afterBind.call(this, mesh);
  38928. this.getScene()._cachedEffect = effect;
  38929. };
  38930. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38931. if (visibility === void 0) { visibility = 1; }
  38932. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38933. };
  38934. return PushMaterial;
  38935. }(BABYLON.Material));
  38936. BABYLON.PushMaterial = PushMaterial;
  38937. })(BABYLON || (BABYLON = {}));
  38938. //# sourceMappingURL=babylon.pushMaterial.js.map
  38939. var BABYLON;
  38940. (function (BABYLON) {
  38941. /** @ignore */
  38942. var StandardMaterialDefines = /** @class */ (function (_super) {
  38943. __extends(StandardMaterialDefines, _super);
  38944. function StandardMaterialDefines() {
  38945. var _this = _super.call(this) || this;
  38946. _this.MAINUV1 = false;
  38947. _this.MAINUV2 = false;
  38948. _this.DIFFUSE = false;
  38949. _this.DIFFUSEDIRECTUV = 0;
  38950. _this.AMBIENT = false;
  38951. _this.AMBIENTDIRECTUV = 0;
  38952. _this.OPACITY = false;
  38953. _this.OPACITYDIRECTUV = 0;
  38954. _this.OPACITYRGB = false;
  38955. _this.REFLECTION = false;
  38956. _this.EMISSIVE = false;
  38957. _this.EMISSIVEDIRECTUV = 0;
  38958. _this.SPECULAR = false;
  38959. _this.SPECULARDIRECTUV = 0;
  38960. _this.BUMP = false;
  38961. _this.BUMPDIRECTUV = 0;
  38962. _this.PARALLAX = false;
  38963. _this.PARALLAXOCCLUSION = false;
  38964. _this.SPECULAROVERALPHA = false;
  38965. _this.CLIPPLANE = false;
  38966. _this.ALPHATEST = false;
  38967. _this.DEPTHPREPASS = false;
  38968. _this.ALPHAFROMDIFFUSE = false;
  38969. _this.POINTSIZE = false;
  38970. _this.FOG = false;
  38971. _this.SPECULARTERM = false;
  38972. _this.DIFFUSEFRESNEL = false;
  38973. _this.OPACITYFRESNEL = false;
  38974. _this.REFLECTIONFRESNEL = false;
  38975. _this.REFRACTIONFRESNEL = false;
  38976. _this.EMISSIVEFRESNEL = false;
  38977. _this.FRESNEL = false;
  38978. _this.NORMAL = false;
  38979. _this.UV1 = false;
  38980. _this.UV2 = false;
  38981. _this.VERTEXCOLOR = false;
  38982. _this.VERTEXALPHA = false;
  38983. _this.NUM_BONE_INFLUENCERS = 0;
  38984. _this.BonesPerMesh = 0;
  38985. _this.INSTANCES = false;
  38986. _this.GLOSSINESS = false;
  38987. _this.ROUGHNESS = false;
  38988. _this.EMISSIVEASILLUMINATION = false;
  38989. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38990. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38991. _this.LIGHTMAP = false;
  38992. _this.LIGHTMAPDIRECTUV = 0;
  38993. _this.OBJECTSPACE_NORMALMAP = false;
  38994. _this.USELIGHTMAPASSHADOWMAP = false;
  38995. _this.REFLECTIONMAP_3D = false;
  38996. _this.REFLECTIONMAP_SPHERICAL = false;
  38997. _this.REFLECTIONMAP_PLANAR = false;
  38998. _this.REFLECTIONMAP_CUBIC = false;
  38999. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39000. _this.REFLECTIONMAP_PROJECTION = false;
  39001. _this.REFLECTIONMAP_SKYBOX = false;
  39002. _this.REFLECTIONMAP_EXPLICIT = false;
  39003. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39004. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39005. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39006. _this.INVERTCUBICMAP = false;
  39007. _this.LOGARITHMICDEPTH = false;
  39008. _this.REFRACTION = false;
  39009. _this.REFRACTIONMAP_3D = false;
  39010. _this.REFLECTIONOVERALPHA = false;
  39011. _this.TWOSIDEDLIGHTING = false;
  39012. _this.SHADOWFLOAT = false;
  39013. _this.MORPHTARGETS = false;
  39014. _this.MORPHTARGETS_NORMAL = false;
  39015. _this.MORPHTARGETS_TANGENT = false;
  39016. _this.NUM_MORPH_INFLUENCERS = 0;
  39017. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39018. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39019. _this.IMAGEPROCESSING = false;
  39020. _this.VIGNETTE = false;
  39021. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39022. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39023. _this.TONEMAPPING = false;
  39024. _this.CONTRAST = false;
  39025. _this.COLORCURVES = false;
  39026. _this.COLORGRADING = false;
  39027. _this.COLORGRADING3D = false;
  39028. _this.SAMPLER3DGREENDEPTH = false;
  39029. _this.SAMPLER3DBGRMAP = false;
  39030. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39031. _this.EXPOSURE = false;
  39032. _this.GRAIN = false;
  39033. _this.rebuild();
  39034. return _this;
  39035. }
  39036. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39037. var modes = [
  39038. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39039. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39040. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39041. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39042. ];
  39043. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39044. var mode = modes_1[_i];
  39045. this[mode] = (mode === modeToEnable);
  39046. }
  39047. };
  39048. return StandardMaterialDefines;
  39049. }(BABYLON.MaterialDefines));
  39050. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39051. var StandardMaterial = /** @class */ (function (_super) {
  39052. __extends(StandardMaterial, _super);
  39053. function StandardMaterial(name, scene) {
  39054. var _this = _super.call(this, name, scene) || this;
  39055. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39056. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39057. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39058. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39059. _this.specularPower = 64;
  39060. _this._useAlphaFromDiffuseTexture = false;
  39061. _this._useEmissiveAsIllumination = false;
  39062. _this._linkEmissiveWithDiffuse = false;
  39063. _this._useSpecularOverAlpha = false;
  39064. _this._useReflectionOverAlpha = false;
  39065. _this._disableLighting = false;
  39066. _this._useObjectSpaceNormalMap = false;
  39067. _this._useParallax = false;
  39068. _this._useParallaxOcclusion = false;
  39069. _this.parallaxScaleBias = 0.05;
  39070. _this._roughness = 0;
  39071. _this.indexOfRefraction = 0.98;
  39072. _this.invertRefractionY = true;
  39073. _this._useLightmapAsShadowmap = false;
  39074. _this._useReflectionFresnelFromSpecular = false;
  39075. _this._useGlossinessFromSpecularMapAlpha = false;
  39076. _this._maxSimultaneousLights = 4;
  39077. /**
  39078. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39079. */
  39080. _this._invertNormalMapX = false;
  39081. /**
  39082. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39083. */
  39084. _this._invertNormalMapY = false;
  39085. /**
  39086. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39087. */
  39088. _this._twoSidedLighting = false;
  39089. _this._renderTargets = new BABYLON.SmartArray(16);
  39090. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39091. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39092. // Setup the default processing configuration to the scene.
  39093. _this._attachImageProcessingConfiguration(null);
  39094. _this.getRenderTargetTextures = function () {
  39095. _this._renderTargets.reset();
  39096. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39097. _this._renderTargets.push(_this._reflectionTexture);
  39098. }
  39099. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39100. _this._renderTargets.push(_this._refractionTexture);
  39101. }
  39102. return _this._renderTargets;
  39103. };
  39104. return _this;
  39105. }
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. ;
  39112. ;
  39113. ;
  39114. ;
  39115. ;
  39116. ;
  39117. ;
  39118. ;
  39119. ;
  39120. ;
  39121. ;
  39122. ;
  39123. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39124. /**
  39125. * Gets the image processing configuration used either in this material.
  39126. */
  39127. get: function () {
  39128. return this._imageProcessingConfiguration;
  39129. },
  39130. /**
  39131. * Sets the Default image processing configuration used either in the this material.
  39132. *
  39133. * If sets to null, the scene one is in use.
  39134. */
  39135. set: function (value) {
  39136. this._attachImageProcessingConfiguration(value);
  39137. // Ensure the effect will be rebuilt.
  39138. this._markAllSubMeshesAsTexturesDirty();
  39139. },
  39140. enumerable: true,
  39141. configurable: true
  39142. });
  39143. /**
  39144. * Attaches a new image processing configuration to the Standard Material.
  39145. * @param configuration
  39146. */
  39147. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39148. var _this = this;
  39149. if (configuration === this._imageProcessingConfiguration) {
  39150. return;
  39151. }
  39152. // Detaches observer.
  39153. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39154. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39155. }
  39156. // Pick the scene configuration if needed.
  39157. if (!configuration) {
  39158. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39159. }
  39160. else {
  39161. this._imageProcessingConfiguration = configuration;
  39162. }
  39163. // Attaches observer.
  39164. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39165. _this._markAllSubMeshesAsImageProcessingDirty();
  39166. });
  39167. };
  39168. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39169. /**
  39170. * Gets wether the color curves effect is enabled.
  39171. */
  39172. get: function () {
  39173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39174. },
  39175. /**
  39176. * Sets wether the color curves effect is enabled.
  39177. */
  39178. set: function (value) {
  39179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39180. },
  39181. enumerable: true,
  39182. configurable: true
  39183. });
  39184. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39185. /**
  39186. * Gets wether the color grading effect is enabled.
  39187. */
  39188. get: function () {
  39189. return this.imageProcessingConfiguration.colorGradingEnabled;
  39190. },
  39191. /**
  39192. * Gets wether the color grading effect is enabled.
  39193. */
  39194. set: function (value) {
  39195. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39196. },
  39197. enumerable: true,
  39198. configurable: true
  39199. });
  39200. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39201. /**
  39202. * Gets wether tonemapping is enabled or not.
  39203. */
  39204. get: function () {
  39205. return this._imageProcessingConfiguration.toneMappingEnabled;
  39206. },
  39207. /**
  39208. * Sets wether tonemapping is enabled or not
  39209. */
  39210. set: function (value) {
  39211. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39212. },
  39213. enumerable: true,
  39214. configurable: true
  39215. });
  39216. ;
  39217. ;
  39218. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39219. /**
  39220. * The camera exposure used on this material.
  39221. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39222. * This corresponds to a photographic exposure.
  39223. */
  39224. get: function () {
  39225. return this._imageProcessingConfiguration.exposure;
  39226. },
  39227. /**
  39228. * The camera exposure used on this material.
  39229. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39230. * This corresponds to a photographic exposure.
  39231. */
  39232. set: function (value) {
  39233. this._imageProcessingConfiguration.exposure = value;
  39234. },
  39235. enumerable: true,
  39236. configurable: true
  39237. });
  39238. ;
  39239. ;
  39240. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39241. /**
  39242. * Gets The camera contrast used on this material.
  39243. */
  39244. get: function () {
  39245. return this._imageProcessingConfiguration.contrast;
  39246. },
  39247. /**
  39248. * Sets The camera contrast used on this material.
  39249. */
  39250. set: function (value) {
  39251. this._imageProcessingConfiguration.contrast = value;
  39252. },
  39253. enumerable: true,
  39254. configurable: true
  39255. });
  39256. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39257. /**
  39258. * Gets the Color Grading 2D Lookup Texture.
  39259. */
  39260. get: function () {
  39261. return this._imageProcessingConfiguration.colorGradingTexture;
  39262. },
  39263. /**
  39264. * Sets the Color Grading 2D Lookup Texture.
  39265. */
  39266. set: function (value) {
  39267. this._imageProcessingConfiguration.colorGradingTexture = value;
  39268. },
  39269. enumerable: true,
  39270. configurable: true
  39271. });
  39272. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39273. /**
  39274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39276. * 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;
  39277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39278. */
  39279. get: function () {
  39280. return this._imageProcessingConfiguration.colorCurves;
  39281. },
  39282. /**
  39283. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39284. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39285. * 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;
  39286. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39287. */
  39288. set: function (value) {
  39289. this._imageProcessingConfiguration.colorCurves = value;
  39290. },
  39291. enumerable: true,
  39292. configurable: true
  39293. });
  39294. StandardMaterial.prototype.getClassName = function () {
  39295. return "StandardMaterial";
  39296. };
  39297. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39298. get: function () {
  39299. return this._useLogarithmicDepth;
  39300. },
  39301. set: function (value) {
  39302. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39303. this._markAllSubMeshesAsMiscDirty();
  39304. },
  39305. enumerable: true,
  39306. configurable: true
  39307. });
  39308. StandardMaterial.prototype.needAlphaBlending = function () {
  39309. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39310. };
  39311. StandardMaterial.prototype.needAlphaTesting = function () {
  39312. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39313. };
  39314. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39315. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39316. };
  39317. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39318. return this._diffuseTexture;
  39319. };
  39320. /**
  39321. * Child classes can use it to update shaders
  39322. */
  39323. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39324. if (useInstances === void 0) { useInstances = false; }
  39325. if (subMesh.effect && this.isFrozen) {
  39326. if (this._wasPreviouslyReady && subMesh.effect) {
  39327. return true;
  39328. }
  39329. }
  39330. if (!subMesh._materialDefines) {
  39331. subMesh._materialDefines = new StandardMaterialDefines();
  39332. }
  39333. var scene = this.getScene();
  39334. var defines = subMesh._materialDefines;
  39335. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39336. if (defines._renderId === scene.getRenderId()) {
  39337. return true;
  39338. }
  39339. }
  39340. var engine = scene.getEngine();
  39341. // Lights
  39342. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39343. // Textures
  39344. if (defines._areTexturesDirty) {
  39345. defines._needUVs = false;
  39346. defines.MAINUV1 = false;
  39347. defines.MAINUV2 = false;
  39348. if (scene.texturesEnabled) {
  39349. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39350. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39351. return false;
  39352. }
  39353. else {
  39354. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39355. }
  39356. }
  39357. else {
  39358. defines.DIFFUSE = false;
  39359. }
  39360. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39361. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39362. return false;
  39363. }
  39364. else {
  39365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39366. }
  39367. }
  39368. else {
  39369. defines.AMBIENT = false;
  39370. }
  39371. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39372. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39373. return false;
  39374. }
  39375. else {
  39376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39377. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39378. }
  39379. }
  39380. else {
  39381. defines.OPACITY = false;
  39382. }
  39383. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39384. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39385. return false;
  39386. }
  39387. else {
  39388. defines._needNormals = true;
  39389. defines.REFLECTION = true;
  39390. defines.ROUGHNESS = (this._roughness > 0);
  39391. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39392. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39393. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39394. switch (this._reflectionTexture.coordinatesMode) {
  39395. case BABYLON.Texture.CUBIC_MODE:
  39396. case BABYLON.Texture.INVCUBIC_MODE:
  39397. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39398. break;
  39399. case BABYLON.Texture.EXPLICIT_MODE:
  39400. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39401. break;
  39402. case BABYLON.Texture.PLANAR_MODE:
  39403. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39404. break;
  39405. case BABYLON.Texture.PROJECTION_MODE:
  39406. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39407. break;
  39408. case BABYLON.Texture.SKYBOX_MODE:
  39409. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39410. break;
  39411. case BABYLON.Texture.SPHERICAL_MODE:
  39412. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39413. break;
  39414. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39415. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39416. break;
  39417. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39418. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39419. break;
  39420. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39421. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39422. break;
  39423. }
  39424. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39425. }
  39426. }
  39427. else {
  39428. defines.REFLECTION = false;
  39429. }
  39430. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39431. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39432. return false;
  39433. }
  39434. else {
  39435. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39436. }
  39437. }
  39438. else {
  39439. defines.EMISSIVE = false;
  39440. }
  39441. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39442. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39443. return false;
  39444. }
  39445. else {
  39446. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39447. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39448. }
  39449. }
  39450. else {
  39451. defines.LIGHTMAP = false;
  39452. }
  39453. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39454. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39455. return false;
  39456. }
  39457. else {
  39458. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39459. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39460. }
  39461. }
  39462. else {
  39463. defines.SPECULAR = false;
  39464. }
  39465. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39466. // Bump texure can not be not blocking.
  39467. if (!this._bumpTexture.isReady()) {
  39468. return false;
  39469. }
  39470. else {
  39471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39472. defines.PARALLAX = this._useParallax;
  39473. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39474. }
  39475. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39476. }
  39477. else {
  39478. defines.BUMP = false;
  39479. }
  39480. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39481. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39482. return false;
  39483. }
  39484. else {
  39485. defines._needUVs = true;
  39486. defines.REFRACTION = true;
  39487. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39488. }
  39489. }
  39490. else {
  39491. defines.REFRACTION = false;
  39492. }
  39493. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39494. }
  39495. else {
  39496. defines.DIFFUSE = false;
  39497. defines.AMBIENT = false;
  39498. defines.OPACITY = false;
  39499. defines.REFLECTION = false;
  39500. defines.EMISSIVE = false;
  39501. defines.LIGHTMAP = false;
  39502. defines.BUMP = false;
  39503. defines.REFRACTION = false;
  39504. }
  39505. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39506. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39507. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39508. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39509. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39510. }
  39511. if (defines._areImageProcessingDirty) {
  39512. if (!this._imageProcessingConfiguration.isReady()) {
  39513. return false;
  39514. }
  39515. this._imageProcessingConfiguration.prepareDefines(defines);
  39516. }
  39517. if (defines._areFresnelDirty) {
  39518. if (StandardMaterial.FresnelEnabled) {
  39519. // Fresnel
  39520. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39521. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39522. this._reflectionFresnelParameters) {
  39523. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39524. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39525. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39526. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39527. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39528. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39529. defines._needNormals = true;
  39530. defines.FRESNEL = true;
  39531. }
  39532. }
  39533. else {
  39534. defines.FRESNEL = false;
  39535. }
  39536. }
  39537. // Misc.
  39538. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39539. // Attribs
  39540. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39541. // Values that need to be evaluated on every frame
  39542. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39543. // Get correct effect
  39544. if (defines.isDirty) {
  39545. defines.markAsProcessed();
  39546. scene.resetCachedMaterial();
  39547. // Fallbacks
  39548. var fallbacks = new BABYLON.EffectFallbacks();
  39549. if (defines.REFLECTION) {
  39550. fallbacks.addFallback(0, "REFLECTION");
  39551. }
  39552. if (defines.SPECULAR) {
  39553. fallbacks.addFallback(0, "SPECULAR");
  39554. }
  39555. if (defines.BUMP) {
  39556. fallbacks.addFallback(0, "BUMP");
  39557. }
  39558. if (defines.PARALLAX) {
  39559. fallbacks.addFallback(1, "PARALLAX");
  39560. }
  39561. if (defines.PARALLAXOCCLUSION) {
  39562. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39563. }
  39564. if (defines.SPECULAROVERALPHA) {
  39565. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39566. }
  39567. if (defines.FOG) {
  39568. fallbacks.addFallback(1, "FOG");
  39569. }
  39570. if (defines.POINTSIZE) {
  39571. fallbacks.addFallback(0, "POINTSIZE");
  39572. }
  39573. if (defines.LOGARITHMICDEPTH) {
  39574. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39575. }
  39576. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39577. if (defines.SPECULARTERM) {
  39578. fallbacks.addFallback(0, "SPECULARTERM");
  39579. }
  39580. if (defines.DIFFUSEFRESNEL) {
  39581. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39582. }
  39583. if (defines.OPACITYFRESNEL) {
  39584. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39585. }
  39586. if (defines.REFLECTIONFRESNEL) {
  39587. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39588. }
  39589. if (defines.EMISSIVEFRESNEL) {
  39590. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39591. }
  39592. if (defines.FRESNEL) {
  39593. fallbacks.addFallback(4, "FRESNEL");
  39594. }
  39595. //Attributes
  39596. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39597. if (defines.NORMAL) {
  39598. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39599. }
  39600. if (defines.UV1) {
  39601. attribs.push(BABYLON.VertexBuffer.UVKind);
  39602. }
  39603. if (defines.UV2) {
  39604. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39605. }
  39606. if (defines.VERTEXCOLOR) {
  39607. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39608. }
  39609. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39610. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39611. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39612. var shaderName = "default";
  39613. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39614. "vFogInfos", "vFogColor", "pointSize",
  39615. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39616. "mBones",
  39617. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39618. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39619. "vReflectionPosition", "vReflectionSize",
  39620. "logarithmicDepthConstant", "vTangentSpaceParams"
  39621. ];
  39622. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39623. var uniformBuffers = ["Material", "Scene"];
  39624. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39625. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39626. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39627. uniformsNames: uniforms,
  39628. uniformBuffersNames: uniformBuffers,
  39629. samplers: samplers,
  39630. defines: defines,
  39631. maxSimultaneousLights: this._maxSimultaneousLights
  39632. });
  39633. if (this.customShaderNameResolve) {
  39634. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39635. }
  39636. var join = defines.toString();
  39637. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39638. attributes: attribs,
  39639. uniformsNames: uniforms,
  39640. uniformBuffersNames: uniformBuffers,
  39641. samplers: samplers,
  39642. defines: join,
  39643. fallbacks: fallbacks,
  39644. onCompiled: this.onCompiled,
  39645. onError: this.onError,
  39646. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39647. }, engine), defines);
  39648. this.buildUniformLayout();
  39649. }
  39650. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39651. return false;
  39652. }
  39653. defines._renderId = scene.getRenderId();
  39654. this._wasPreviouslyReady = true;
  39655. return true;
  39656. };
  39657. StandardMaterial.prototype.buildUniformLayout = function () {
  39658. // Order is important !
  39659. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39660. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39661. this._uniformBuffer.addUniform("opacityParts", 4);
  39662. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39663. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39664. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39665. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39666. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39667. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39668. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39669. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39670. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39671. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39672. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39673. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39674. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39675. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39676. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39677. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39678. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39679. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39680. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39681. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39682. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39683. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39684. this._uniformBuffer.addUniform("specularMatrix", 16);
  39685. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39686. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39687. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39688. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39689. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39690. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39691. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39692. this._uniformBuffer.addUniform("pointSize", 1);
  39693. this._uniformBuffer.create();
  39694. };
  39695. StandardMaterial.prototype.unbind = function () {
  39696. if (this._activeEffect) {
  39697. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39698. this._activeEffect.setTexture("reflection2DSampler", null);
  39699. }
  39700. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39701. this._activeEffect.setTexture("refraction2DSampler", null);
  39702. }
  39703. }
  39704. _super.prototype.unbind.call(this);
  39705. };
  39706. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39707. var scene = this.getScene();
  39708. var defines = subMesh._materialDefines;
  39709. if (!defines) {
  39710. return;
  39711. }
  39712. var effect = subMesh.effect;
  39713. if (!effect) {
  39714. return;
  39715. }
  39716. this._activeEffect = effect;
  39717. // Matrices
  39718. this.bindOnlyWorldMatrix(world);
  39719. // Normal Matrix
  39720. if (defines.OBJECTSPACE_NORMALMAP) {
  39721. world.toNormalMatrix(this._normalMatrix);
  39722. this.bindOnlyNormalMatrix(this._normalMatrix);
  39723. }
  39724. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39725. // Bones
  39726. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39727. if (mustRebind) {
  39728. this._uniformBuffer.bindToEffect(effect, "Material");
  39729. this.bindViewProjection(effect);
  39730. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39731. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39732. // Fresnel
  39733. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39734. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39735. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39736. }
  39737. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39738. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39739. }
  39740. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39741. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39742. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39743. }
  39744. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39745. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39746. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39747. }
  39748. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39749. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39750. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39751. }
  39752. }
  39753. // Textures
  39754. if (scene.texturesEnabled) {
  39755. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39756. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39757. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39758. }
  39759. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39760. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39761. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39762. }
  39763. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39764. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39765. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39766. }
  39767. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39768. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39769. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39770. if (this._reflectionTexture.boundingBoxSize) {
  39771. var cubeTexture = this._reflectionTexture;
  39772. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39773. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39774. }
  39775. }
  39776. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39777. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39778. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39779. }
  39780. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39781. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39782. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39783. }
  39784. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39785. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39786. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39787. }
  39788. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39789. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39790. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39791. if (scene._mirroredCameraPosition) {
  39792. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39793. }
  39794. else {
  39795. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39796. }
  39797. }
  39798. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39799. var depth = 1.0;
  39800. if (!this._refractionTexture.isCube) {
  39801. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39802. if (this._refractionTexture.depth) {
  39803. depth = this._refractionTexture.depth;
  39804. }
  39805. }
  39806. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39807. }
  39808. }
  39809. // Point size
  39810. if (this.pointsCloud) {
  39811. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39812. }
  39813. if (defines.SPECULARTERM) {
  39814. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39815. }
  39816. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39817. // Diffuse
  39818. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39819. }
  39820. // Textures
  39821. if (scene.texturesEnabled) {
  39822. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39823. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39824. }
  39825. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39826. effect.setTexture("ambientSampler", this._ambientTexture);
  39827. }
  39828. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39829. effect.setTexture("opacitySampler", this._opacityTexture);
  39830. }
  39831. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39832. if (this._reflectionTexture.isCube) {
  39833. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39834. }
  39835. else {
  39836. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39837. }
  39838. }
  39839. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39840. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39841. }
  39842. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39843. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39844. }
  39845. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39846. effect.setTexture("specularSampler", this._specularTexture);
  39847. }
  39848. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39849. effect.setTexture("bumpSampler", this._bumpTexture);
  39850. }
  39851. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39852. var depth = 1.0;
  39853. if (this._refractionTexture.isCube) {
  39854. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39855. }
  39856. else {
  39857. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39858. }
  39859. }
  39860. }
  39861. // Clip plane
  39862. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39863. // Colors
  39864. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39865. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39866. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39867. }
  39868. if (mustRebind || !this.isFrozen) {
  39869. // Lights
  39870. if (scene.lightsEnabled && !this._disableLighting) {
  39871. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39872. }
  39873. // View
  39874. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39875. this.bindView(effect);
  39876. }
  39877. // Fog
  39878. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39879. // Morph targets
  39880. if (defines.NUM_MORPH_INFLUENCERS) {
  39881. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39882. }
  39883. // Log. depth
  39884. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39885. // image processing
  39886. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39887. this._imageProcessingConfiguration.bind(this._activeEffect);
  39888. }
  39889. }
  39890. this._uniformBuffer.update();
  39891. this._afterBind(mesh, this._activeEffect);
  39892. };
  39893. StandardMaterial.prototype.getAnimatables = function () {
  39894. var results = [];
  39895. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39896. results.push(this._diffuseTexture);
  39897. }
  39898. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39899. results.push(this._ambientTexture);
  39900. }
  39901. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39902. results.push(this._opacityTexture);
  39903. }
  39904. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39905. results.push(this._reflectionTexture);
  39906. }
  39907. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39908. results.push(this._emissiveTexture);
  39909. }
  39910. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39911. results.push(this._specularTexture);
  39912. }
  39913. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39914. results.push(this._bumpTexture);
  39915. }
  39916. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39917. results.push(this._lightmapTexture);
  39918. }
  39919. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39920. results.push(this._refractionTexture);
  39921. }
  39922. return results;
  39923. };
  39924. StandardMaterial.prototype.getActiveTextures = function () {
  39925. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39926. if (this._diffuseTexture) {
  39927. activeTextures.push(this._diffuseTexture);
  39928. }
  39929. if (this._ambientTexture) {
  39930. activeTextures.push(this._ambientTexture);
  39931. }
  39932. if (this._opacityTexture) {
  39933. activeTextures.push(this._opacityTexture);
  39934. }
  39935. if (this._reflectionTexture) {
  39936. activeTextures.push(this._reflectionTexture);
  39937. }
  39938. if (this._emissiveTexture) {
  39939. activeTextures.push(this._emissiveTexture);
  39940. }
  39941. if (this._specularTexture) {
  39942. activeTextures.push(this._specularTexture);
  39943. }
  39944. if (this._bumpTexture) {
  39945. activeTextures.push(this._bumpTexture);
  39946. }
  39947. if (this._lightmapTexture) {
  39948. activeTextures.push(this._lightmapTexture);
  39949. }
  39950. if (this._refractionTexture) {
  39951. activeTextures.push(this._refractionTexture);
  39952. }
  39953. return activeTextures;
  39954. };
  39955. StandardMaterial.prototype.hasTexture = function (texture) {
  39956. if (_super.prototype.hasTexture.call(this, texture)) {
  39957. return true;
  39958. }
  39959. if (this._diffuseTexture === texture) {
  39960. return true;
  39961. }
  39962. if (this._ambientTexture === texture) {
  39963. return true;
  39964. }
  39965. if (this._opacityTexture === texture) {
  39966. return true;
  39967. }
  39968. if (this._reflectionTexture === texture) {
  39969. return true;
  39970. }
  39971. if (this._emissiveTexture === texture) {
  39972. return true;
  39973. }
  39974. if (this._specularTexture === texture) {
  39975. return true;
  39976. }
  39977. if (this._bumpTexture === texture) {
  39978. return true;
  39979. }
  39980. if (this._lightmapTexture === texture) {
  39981. return true;
  39982. }
  39983. if (this._refractionTexture === texture) {
  39984. return true;
  39985. }
  39986. return false;
  39987. };
  39988. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39989. if (forceDisposeTextures) {
  39990. if (this._diffuseTexture) {
  39991. this._diffuseTexture.dispose();
  39992. }
  39993. if (this._ambientTexture) {
  39994. this._ambientTexture.dispose();
  39995. }
  39996. if (this._opacityTexture) {
  39997. this._opacityTexture.dispose();
  39998. }
  39999. if (this._reflectionTexture) {
  40000. this._reflectionTexture.dispose();
  40001. }
  40002. if (this._emissiveTexture) {
  40003. this._emissiveTexture.dispose();
  40004. }
  40005. if (this._specularTexture) {
  40006. this._specularTexture.dispose();
  40007. }
  40008. if (this._bumpTexture) {
  40009. this._bumpTexture.dispose();
  40010. }
  40011. if (this._lightmapTexture) {
  40012. this._lightmapTexture.dispose();
  40013. }
  40014. if (this._refractionTexture) {
  40015. this._refractionTexture.dispose();
  40016. }
  40017. }
  40018. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40019. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40020. }
  40021. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40022. };
  40023. StandardMaterial.prototype.clone = function (name) {
  40024. var _this = this;
  40025. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40026. result.name = name;
  40027. result.id = name;
  40028. return result;
  40029. };
  40030. StandardMaterial.prototype.serialize = function () {
  40031. return BABYLON.SerializationHelper.Serialize(this);
  40032. };
  40033. // Statics
  40034. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40035. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40036. };
  40037. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40038. get: function () {
  40039. return StandardMaterial._DiffuseTextureEnabled;
  40040. },
  40041. set: function (value) {
  40042. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40043. return;
  40044. }
  40045. StandardMaterial._DiffuseTextureEnabled = value;
  40046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40047. },
  40048. enumerable: true,
  40049. configurable: true
  40050. });
  40051. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40052. get: function () {
  40053. return StandardMaterial._AmbientTextureEnabled;
  40054. },
  40055. set: function (value) {
  40056. if (StandardMaterial._AmbientTextureEnabled === value) {
  40057. return;
  40058. }
  40059. StandardMaterial._AmbientTextureEnabled = value;
  40060. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40061. },
  40062. enumerable: true,
  40063. configurable: true
  40064. });
  40065. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40066. get: function () {
  40067. return StandardMaterial._OpacityTextureEnabled;
  40068. },
  40069. set: function (value) {
  40070. if (StandardMaterial._OpacityTextureEnabled === value) {
  40071. return;
  40072. }
  40073. StandardMaterial._OpacityTextureEnabled = value;
  40074. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40075. },
  40076. enumerable: true,
  40077. configurable: true
  40078. });
  40079. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40080. get: function () {
  40081. return StandardMaterial._ReflectionTextureEnabled;
  40082. },
  40083. set: function (value) {
  40084. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40085. return;
  40086. }
  40087. StandardMaterial._ReflectionTextureEnabled = value;
  40088. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40089. },
  40090. enumerable: true,
  40091. configurable: true
  40092. });
  40093. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40094. get: function () {
  40095. return StandardMaterial._EmissiveTextureEnabled;
  40096. },
  40097. set: function (value) {
  40098. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40099. return;
  40100. }
  40101. StandardMaterial._EmissiveTextureEnabled = value;
  40102. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40108. get: function () {
  40109. return StandardMaterial._SpecularTextureEnabled;
  40110. },
  40111. set: function (value) {
  40112. if (StandardMaterial._SpecularTextureEnabled === value) {
  40113. return;
  40114. }
  40115. StandardMaterial._SpecularTextureEnabled = value;
  40116. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40117. },
  40118. enumerable: true,
  40119. configurable: true
  40120. });
  40121. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40122. get: function () {
  40123. return StandardMaterial._BumpTextureEnabled;
  40124. },
  40125. set: function (value) {
  40126. if (StandardMaterial._BumpTextureEnabled === value) {
  40127. return;
  40128. }
  40129. StandardMaterial._BumpTextureEnabled = value;
  40130. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40131. },
  40132. enumerable: true,
  40133. configurable: true
  40134. });
  40135. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40136. get: function () {
  40137. return StandardMaterial._LightmapTextureEnabled;
  40138. },
  40139. set: function (value) {
  40140. if (StandardMaterial._LightmapTextureEnabled === value) {
  40141. return;
  40142. }
  40143. StandardMaterial._LightmapTextureEnabled = value;
  40144. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40145. },
  40146. enumerable: true,
  40147. configurable: true
  40148. });
  40149. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40150. get: function () {
  40151. return StandardMaterial._RefractionTextureEnabled;
  40152. },
  40153. set: function (value) {
  40154. if (StandardMaterial._RefractionTextureEnabled === value) {
  40155. return;
  40156. }
  40157. StandardMaterial._RefractionTextureEnabled = value;
  40158. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40159. },
  40160. enumerable: true,
  40161. configurable: true
  40162. });
  40163. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40164. get: function () {
  40165. return StandardMaterial._ColorGradingTextureEnabled;
  40166. },
  40167. set: function (value) {
  40168. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40169. return;
  40170. }
  40171. StandardMaterial._ColorGradingTextureEnabled = value;
  40172. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40173. },
  40174. enumerable: true,
  40175. configurable: true
  40176. });
  40177. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40178. get: function () {
  40179. return StandardMaterial._FresnelEnabled;
  40180. },
  40181. set: function (value) {
  40182. if (StandardMaterial._FresnelEnabled === value) {
  40183. return;
  40184. }
  40185. StandardMaterial._FresnelEnabled = value;
  40186. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40187. },
  40188. enumerable: true,
  40189. configurable: true
  40190. });
  40191. // Flags used to enable or disable a type of texture for all Standard Materials
  40192. StandardMaterial._DiffuseTextureEnabled = true;
  40193. StandardMaterial._AmbientTextureEnabled = true;
  40194. StandardMaterial._OpacityTextureEnabled = true;
  40195. StandardMaterial._ReflectionTextureEnabled = true;
  40196. StandardMaterial._EmissiveTextureEnabled = true;
  40197. StandardMaterial._SpecularTextureEnabled = true;
  40198. StandardMaterial._BumpTextureEnabled = true;
  40199. StandardMaterial._LightmapTextureEnabled = true;
  40200. StandardMaterial._RefractionTextureEnabled = true;
  40201. StandardMaterial._ColorGradingTextureEnabled = true;
  40202. StandardMaterial._FresnelEnabled = true;
  40203. __decorate([
  40204. BABYLON.serializeAsTexture("diffuseTexture")
  40205. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40206. __decorate([
  40207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40208. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40209. __decorate([
  40210. BABYLON.serializeAsTexture("ambientTexture")
  40211. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40212. __decorate([
  40213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40214. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40215. __decorate([
  40216. BABYLON.serializeAsTexture("opacityTexture")
  40217. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40218. __decorate([
  40219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40220. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40221. __decorate([
  40222. BABYLON.serializeAsTexture("reflectionTexture")
  40223. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40224. __decorate([
  40225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40226. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40227. __decorate([
  40228. BABYLON.serializeAsTexture("emissiveTexture")
  40229. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40230. __decorate([
  40231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40232. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40233. __decorate([
  40234. BABYLON.serializeAsTexture("specularTexture")
  40235. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40236. __decorate([
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], StandardMaterial.prototype, "specularTexture", void 0);
  40239. __decorate([
  40240. BABYLON.serializeAsTexture("bumpTexture")
  40241. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40242. __decorate([
  40243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40244. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40245. __decorate([
  40246. BABYLON.serializeAsTexture("lightmapTexture")
  40247. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40248. __decorate([
  40249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40250. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40251. __decorate([
  40252. BABYLON.serializeAsTexture("refractionTexture")
  40253. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40254. __decorate([
  40255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40256. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40257. __decorate([
  40258. BABYLON.serializeAsColor3("ambient")
  40259. ], StandardMaterial.prototype, "ambientColor", void 0);
  40260. __decorate([
  40261. BABYLON.serializeAsColor3("diffuse")
  40262. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40263. __decorate([
  40264. BABYLON.serializeAsColor3("specular")
  40265. ], StandardMaterial.prototype, "specularColor", void 0);
  40266. __decorate([
  40267. BABYLON.serializeAsColor3("emissive")
  40268. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40269. __decorate([
  40270. BABYLON.serialize()
  40271. ], StandardMaterial.prototype, "specularPower", void 0);
  40272. __decorate([
  40273. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40274. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40275. __decorate([
  40276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40277. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40278. __decorate([
  40279. BABYLON.serialize("useEmissiveAsIllumination")
  40280. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40281. __decorate([
  40282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40283. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40284. __decorate([
  40285. BABYLON.serialize("linkEmissiveWithDiffuse")
  40286. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40287. __decorate([
  40288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40289. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40290. __decorate([
  40291. BABYLON.serialize("useSpecularOverAlpha")
  40292. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40293. __decorate([
  40294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40295. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40296. __decorate([
  40297. BABYLON.serialize("useReflectionOverAlpha")
  40298. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40299. __decorate([
  40300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40301. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40302. __decorate([
  40303. BABYLON.serialize("disableLighting")
  40304. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40307. ], StandardMaterial.prototype, "disableLighting", void 0);
  40308. __decorate([
  40309. BABYLON.serialize("useObjectSpaceNormalMap")
  40310. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40311. __decorate([
  40312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40313. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40314. __decorate([
  40315. BABYLON.serialize("useParallax")
  40316. ], StandardMaterial.prototype, "_useParallax", void 0);
  40317. __decorate([
  40318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40319. ], StandardMaterial.prototype, "useParallax", void 0);
  40320. __decorate([
  40321. BABYLON.serialize("useParallaxOcclusion")
  40322. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40323. __decorate([
  40324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40325. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40326. __decorate([
  40327. BABYLON.serialize()
  40328. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40329. __decorate([
  40330. BABYLON.serialize("roughness")
  40331. ], StandardMaterial.prototype, "_roughness", void 0);
  40332. __decorate([
  40333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40334. ], StandardMaterial.prototype, "roughness", void 0);
  40335. __decorate([
  40336. BABYLON.serialize()
  40337. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40338. __decorate([
  40339. BABYLON.serialize()
  40340. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40341. __decorate([
  40342. BABYLON.serialize("useLightmapAsShadowmap")
  40343. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40344. __decorate([
  40345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40346. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40347. __decorate([
  40348. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40349. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40350. __decorate([
  40351. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40352. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40353. __decorate([
  40354. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40355. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40356. __decorate([
  40357. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40358. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40359. __decorate([
  40360. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40361. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40362. __decorate([
  40363. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40364. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40365. __decorate([
  40366. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40367. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40368. __decorate([
  40369. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40370. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40371. __decorate([
  40372. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40373. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40374. __decorate([
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40376. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40377. __decorate([
  40378. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40379. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40380. __decorate([
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40382. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40383. __decorate([
  40384. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40385. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40386. __decorate([
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40389. __decorate([
  40390. BABYLON.serialize("maxSimultaneousLights")
  40391. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40392. __decorate([
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40394. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40395. __decorate([
  40396. BABYLON.serialize("invertNormalMapX")
  40397. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40398. __decorate([
  40399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40400. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40401. __decorate([
  40402. BABYLON.serialize("invertNormalMapY")
  40403. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40404. __decorate([
  40405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40406. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40407. __decorate([
  40408. BABYLON.serialize("twoSidedLighting")
  40409. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40410. __decorate([
  40411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40412. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40413. __decorate([
  40414. BABYLON.serialize()
  40415. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40416. return StandardMaterial;
  40417. }(BABYLON.PushMaterial));
  40418. BABYLON.StandardMaterial = StandardMaterial;
  40419. })(BABYLON || (BABYLON = {}));
  40420. //# sourceMappingURL=babylon.standardMaterial.js.map
  40421. var BABYLON;
  40422. (function (BABYLON) {
  40423. /**
  40424. * Manages the defines for the PBR Material.
  40425. */
  40426. var PBRMaterialDefines = /** @class */ (function (_super) {
  40427. __extends(PBRMaterialDefines, _super);
  40428. /**
  40429. * Initializes the PBR Material defines.
  40430. */
  40431. function PBRMaterialDefines() {
  40432. var _this = _super.call(this) || this;
  40433. _this.PBR = true;
  40434. _this.MAINUV1 = false;
  40435. _this.MAINUV2 = false;
  40436. _this.UV1 = false;
  40437. _this.UV2 = false;
  40438. _this.ALBEDO = false;
  40439. _this.ALBEDODIRECTUV = 0;
  40440. _this.VERTEXCOLOR = false;
  40441. _this.AMBIENT = false;
  40442. _this.AMBIENTDIRECTUV = 0;
  40443. _this.AMBIENTINGRAYSCALE = false;
  40444. _this.OPACITY = false;
  40445. _this.VERTEXALPHA = false;
  40446. _this.OPACITYDIRECTUV = 0;
  40447. _this.OPACITYRGB = false;
  40448. _this.ALPHATEST = false;
  40449. _this.DEPTHPREPASS = false;
  40450. _this.ALPHABLEND = false;
  40451. _this.ALPHAFROMALBEDO = false;
  40452. _this.ALPHATESTVALUE = 0.5;
  40453. _this.SPECULAROVERALPHA = false;
  40454. _this.RADIANCEOVERALPHA = false;
  40455. _this.ALPHAFRESNEL = false;
  40456. _this.LINEARALPHAFRESNEL = false;
  40457. _this.PREMULTIPLYALPHA = false;
  40458. _this.EMISSIVE = false;
  40459. _this.EMISSIVEDIRECTUV = 0;
  40460. _this.REFLECTIVITY = false;
  40461. _this.REFLECTIVITYDIRECTUV = 0;
  40462. _this.SPECULARTERM = false;
  40463. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40464. _this.MICROSURFACEAUTOMATIC = false;
  40465. _this.LODBASEDMICROSFURACE = false;
  40466. _this.MICROSURFACEMAP = false;
  40467. _this.MICROSURFACEMAPDIRECTUV = 0;
  40468. _this.METALLICWORKFLOW = false;
  40469. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40470. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40471. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40472. _this.AOSTOREINMETALMAPRED = false;
  40473. _this.ENVIRONMENTBRDF = false;
  40474. _this.NORMAL = false;
  40475. _this.TANGENT = false;
  40476. _this.BUMP = false;
  40477. _this.BUMPDIRECTUV = 0;
  40478. _this.OBJECTSPACE_NORMALMAP = false;
  40479. _this.PARALLAX = false;
  40480. _this.PARALLAXOCCLUSION = false;
  40481. _this.NORMALXYSCALE = true;
  40482. _this.LIGHTMAP = false;
  40483. _this.LIGHTMAPDIRECTUV = 0;
  40484. _this.USELIGHTMAPASSHADOWMAP = false;
  40485. _this.REFLECTION = false;
  40486. _this.REFLECTIONMAP_3D = false;
  40487. _this.REFLECTIONMAP_SPHERICAL = false;
  40488. _this.REFLECTIONMAP_PLANAR = false;
  40489. _this.REFLECTIONMAP_CUBIC = false;
  40490. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40491. _this.REFLECTIONMAP_PROJECTION = false;
  40492. _this.REFLECTIONMAP_SKYBOX = false;
  40493. _this.REFLECTIONMAP_EXPLICIT = false;
  40494. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40495. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40496. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40497. _this.INVERTCUBICMAP = false;
  40498. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40499. _this.USESPHERICALINVERTEX = false;
  40500. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40501. _this.LODINREFLECTIONALPHA = false;
  40502. _this.GAMMAREFLECTION = false;
  40503. _this.RADIANCEOCCLUSION = false;
  40504. _this.HORIZONOCCLUSION = false;
  40505. _this.REFRACTION = false;
  40506. _this.REFRACTIONMAP_3D = false;
  40507. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40508. _this.LODINREFRACTIONALPHA = false;
  40509. _this.GAMMAREFRACTION = false;
  40510. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40511. _this.INSTANCES = false;
  40512. _this.NUM_BONE_INFLUENCERS = 0;
  40513. _this.BonesPerMesh = 0;
  40514. _this.NONUNIFORMSCALING = false;
  40515. _this.MORPHTARGETS = false;
  40516. _this.MORPHTARGETS_NORMAL = false;
  40517. _this.MORPHTARGETS_TANGENT = false;
  40518. _this.NUM_MORPH_INFLUENCERS = 0;
  40519. _this.IMAGEPROCESSING = false;
  40520. _this.VIGNETTE = false;
  40521. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40522. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40523. _this.TONEMAPPING = false;
  40524. _this.CONTRAST = false;
  40525. _this.COLORCURVES = false;
  40526. _this.COLORGRADING = false;
  40527. _this.COLORGRADING3D = false;
  40528. _this.SAMPLER3DGREENDEPTH = false;
  40529. _this.SAMPLER3DBGRMAP = false;
  40530. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40531. _this.EXPOSURE = false;
  40532. _this.GRAIN = false;
  40533. _this.USEPHYSICALLIGHTFALLOFF = false;
  40534. _this.TWOSIDEDLIGHTING = false;
  40535. _this.SHADOWFLOAT = false;
  40536. _this.CLIPPLANE = false;
  40537. _this.POINTSIZE = false;
  40538. _this.FOG = false;
  40539. _this.LOGARITHMICDEPTH = false;
  40540. _this.FORCENORMALFORWARD = false;
  40541. _this.rebuild();
  40542. return _this;
  40543. }
  40544. /**
  40545. * Resets the PBR Material defines.
  40546. */
  40547. PBRMaterialDefines.prototype.reset = function () {
  40548. _super.prototype.reset.call(this);
  40549. this.ALPHATESTVALUE = 0.5;
  40550. this.PBR = true;
  40551. };
  40552. return PBRMaterialDefines;
  40553. }(BABYLON.MaterialDefines));
  40554. /**
  40555. * The Physically based material base class of BJS.
  40556. *
  40557. * This offers the main features of a standard PBR material.
  40558. * For more information, please refer to the documentation :
  40559. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40560. */
  40561. var PBRBaseMaterial = /** @class */ (function (_super) {
  40562. __extends(PBRBaseMaterial, _super);
  40563. /**
  40564. * Instantiates a new PBRMaterial instance.
  40565. *
  40566. * @param name The material name
  40567. * @param scene The scene the material will be use in.
  40568. */
  40569. function PBRBaseMaterial(name, scene) {
  40570. var _this = _super.call(this, name, scene) || this;
  40571. /**
  40572. * Intensity of the direct lights e.g. the four lights available in your scene.
  40573. * This impacts both the direct diffuse and specular highlights.
  40574. */
  40575. _this._directIntensity = 1.0;
  40576. /**
  40577. * Intensity of the emissive part of the material.
  40578. * This helps controlling the emissive effect without modifying the emissive color.
  40579. */
  40580. _this._emissiveIntensity = 1.0;
  40581. /**
  40582. * Intensity of the environment e.g. how much the environment will light the object
  40583. * either through harmonics for rough material or through the refelction for shiny ones.
  40584. */
  40585. _this._environmentIntensity = 1.0;
  40586. /**
  40587. * This is a special control allowing the reduction of the specular highlights coming from the
  40588. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40589. */
  40590. _this._specularIntensity = 1.0;
  40591. /**
  40592. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40593. */
  40594. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40595. /**
  40596. * Debug Control allowing disabling the bump map on this material.
  40597. */
  40598. _this._disableBumpMap = false;
  40599. /**
  40600. * AKA Occlusion Texture Intensity in other nomenclature.
  40601. */
  40602. _this._ambientTextureStrength = 1.0;
  40603. /**
  40604. * The color of a material in ambient lighting.
  40605. */
  40606. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40607. /**
  40608. * AKA Diffuse Color in other nomenclature.
  40609. */
  40610. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40611. /**
  40612. * AKA Specular Color in other nomenclature.
  40613. */
  40614. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40615. /**
  40616. * The color applied when light is reflected from a material.
  40617. */
  40618. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40619. /**
  40620. * The color applied when light is emitted from a material.
  40621. */
  40622. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40623. /**
  40624. * AKA Glossiness in other nomenclature.
  40625. */
  40626. _this._microSurface = 0.9;
  40627. /**
  40628. * source material index of refraction (IOR)' / 'destination material IOR.
  40629. */
  40630. _this._indexOfRefraction = 0.66;
  40631. /**
  40632. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40633. */
  40634. _this._invertRefractionY = false;
  40635. /**
  40636. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40637. * Materials half opaque for instance using refraction could benefit from this control.
  40638. */
  40639. _this._linkRefractionWithTransparency = false;
  40640. /**
  40641. * Specifies that the material will use the light map as a show map.
  40642. */
  40643. _this._useLightmapAsShadowmap = false;
  40644. /**
  40645. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40646. * makes the reflect vector face the model (under horizon).
  40647. */
  40648. _this._useHorizonOcclusion = true;
  40649. /**
  40650. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40651. * too much the area relying on ambient texture to define their ambient occlusion.
  40652. */
  40653. _this._useRadianceOcclusion = true;
  40654. /**
  40655. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40656. */
  40657. _this._useAlphaFromAlbedoTexture = false;
  40658. /**
  40659. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40660. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40661. */
  40662. _this._useSpecularOverAlpha = true;
  40663. /**
  40664. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40665. */
  40666. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40667. /**
  40668. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40669. */
  40670. _this._useRoughnessFromMetallicTextureAlpha = true;
  40671. /**
  40672. * Specifies if the metallic texture contains the roughness information in its green channel.
  40673. */
  40674. _this._useRoughnessFromMetallicTextureGreen = false;
  40675. /**
  40676. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40677. */
  40678. _this._useMetallnessFromMetallicTextureBlue = false;
  40679. /**
  40680. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40681. */
  40682. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40683. /**
  40684. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40685. */
  40686. _this._useAmbientInGrayScale = false;
  40687. /**
  40688. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40689. * The material will try to infer what glossiness each pixel should be.
  40690. */
  40691. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40692. /**
  40693. * BJS is using an harcoded light falloff based on a manually sets up range.
  40694. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40695. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40696. */
  40697. _this._usePhysicalLightFalloff = true;
  40698. /**
  40699. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40700. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40701. */
  40702. _this._useRadianceOverAlpha = true;
  40703. /**
  40704. * Allows using an object space normal map (instead of tangent space).
  40705. */
  40706. _this._useObjectSpaceNormalMap = false;
  40707. /**
  40708. * Allows using the bump map in parallax mode.
  40709. */
  40710. _this._useParallax = false;
  40711. /**
  40712. * Allows using the bump map in parallax occlusion mode.
  40713. */
  40714. _this._useParallaxOcclusion = false;
  40715. /**
  40716. * Controls the scale bias of the parallax mode.
  40717. */
  40718. _this._parallaxScaleBias = 0.05;
  40719. /**
  40720. * If sets to true, disables all the lights affecting the material.
  40721. */
  40722. _this._disableLighting = false;
  40723. /**
  40724. * Number of Simultaneous lights allowed on the material.
  40725. */
  40726. _this._maxSimultaneousLights = 4;
  40727. /**
  40728. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40729. */
  40730. _this._invertNormalMapX = false;
  40731. /**
  40732. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40733. */
  40734. _this._invertNormalMapY = false;
  40735. /**
  40736. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40737. */
  40738. _this._twoSidedLighting = false;
  40739. /**
  40740. * Defines the alpha limits in alpha test mode.
  40741. */
  40742. _this._alphaCutOff = 0.4;
  40743. /**
  40744. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40745. */
  40746. _this._forceAlphaTest = false;
  40747. /**
  40748. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40749. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40750. */
  40751. _this._useAlphaFresnel = false;
  40752. /**
  40753. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40754. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40755. */
  40756. _this._useLinearAlphaFresnel = false;
  40757. /**
  40758. * The transparency mode of the material.
  40759. */
  40760. _this._transparencyMode = null;
  40761. /**
  40762. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40763. * from cos thetav and roughness:
  40764. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40765. */
  40766. _this._environmentBRDFTexture = null;
  40767. /**
  40768. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40769. */
  40770. _this._forceIrradianceInFragment = false;
  40771. /**
  40772. * Force normal to face away from face.
  40773. */
  40774. _this._forceNormalForward = false;
  40775. /**
  40776. * Stores the available render targets.
  40777. */
  40778. _this._renderTargets = new BABYLON.SmartArray(16);
  40779. /**
  40780. * Sets the global ambient color for the material used in lighting calculations.
  40781. */
  40782. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40783. // Setup the default processing configuration to the scene.
  40784. _this._attachImageProcessingConfiguration(null);
  40785. _this.getRenderTargetTextures = function () {
  40786. _this._renderTargets.reset();
  40787. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40788. _this._renderTargets.push(_this._reflectionTexture);
  40789. }
  40790. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40791. _this._renderTargets.push(_this._refractionTexture);
  40792. }
  40793. return _this._renderTargets;
  40794. };
  40795. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40796. return _this;
  40797. }
  40798. /**
  40799. * Attaches a new image processing configuration to the PBR Material.
  40800. * @param configuration
  40801. */
  40802. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40803. var _this = this;
  40804. if (configuration === this._imageProcessingConfiguration) {
  40805. return;
  40806. }
  40807. // Detaches observer.
  40808. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40809. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40810. }
  40811. // Pick the scene configuration if needed.
  40812. if (!configuration) {
  40813. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40814. }
  40815. else {
  40816. this._imageProcessingConfiguration = configuration;
  40817. }
  40818. // Attaches observer.
  40819. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40820. _this._markAllSubMeshesAsImageProcessingDirty();
  40821. });
  40822. };
  40823. /**
  40824. * Gets the name of the material class.
  40825. */
  40826. PBRBaseMaterial.prototype.getClassName = function () {
  40827. return "PBRBaseMaterial";
  40828. };
  40829. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40830. /**
  40831. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40832. */
  40833. get: function () {
  40834. return this._useLogarithmicDepth;
  40835. },
  40836. /**
  40837. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40838. */
  40839. set: function (value) {
  40840. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40846. /**
  40847. * Gets the current transparency mode.
  40848. */
  40849. get: function () {
  40850. return this._transparencyMode;
  40851. },
  40852. /**
  40853. * Sets the transparency mode of the material.
  40854. */
  40855. set: function (value) {
  40856. if (this._transparencyMode === value) {
  40857. return;
  40858. }
  40859. this._transparencyMode = value;
  40860. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40861. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40862. },
  40863. enumerable: true,
  40864. configurable: true
  40865. });
  40866. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40867. /**
  40868. * Returns true if alpha blending should be disabled.
  40869. */
  40870. get: function () {
  40871. return (this._linkRefractionWithTransparency ||
  40872. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40873. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40874. },
  40875. enumerable: true,
  40876. configurable: true
  40877. });
  40878. /**
  40879. * Specifies whether or not this material should be rendered in alpha blend mode.
  40880. */
  40881. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40882. if (this._disableAlphaBlending) {
  40883. return false;
  40884. }
  40885. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40886. };
  40887. /**
  40888. * Specifies if the mesh will require alpha blending.
  40889. * @param mesh - BJS mesh.
  40890. */
  40891. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40892. if (this._disableAlphaBlending) {
  40893. return false;
  40894. }
  40895. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40896. };
  40897. /**
  40898. * Specifies whether or not this material should be rendered in alpha test mode.
  40899. */
  40900. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40901. if (this._forceAlphaTest) {
  40902. return true;
  40903. }
  40904. if (this._linkRefractionWithTransparency) {
  40905. return false;
  40906. }
  40907. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40908. };
  40909. /**
  40910. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40911. */
  40912. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40913. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40914. };
  40915. /**
  40916. * Gets the texture used for the alpha test.
  40917. */
  40918. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40919. return this._albedoTexture;
  40920. };
  40921. /**
  40922. * Specifies that the submesh is ready to be used.
  40923. * @param mesh - BJS mesh.
  40924. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40925. * @param useInstances - Specifies that instances should be used.
  40926. * @returns - boolean indicating that the submesh is ready or not.
  40927. */
  40928. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40929. if (subMesh.effect && this.isFrozen) {
  40930. if (this._wasPreviouslyReady) {
  40931. return true;
  40932. }
  40933. }
  40934. if (!subMesh._materialDefines) {
  40935. subMesh._materialDefines = new PBRMaterialDefines();
  40936. }
  40937. var defines = subMesh._materialDefines;
  40938. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40939. if (defines._renderId === this.getScene().getRenderId()) {
  40940. return true;
  40941. }
  40942. }
  40943. var scene = this.getScene();
  40944. var engine = scene.getEngine();
  40945. if (defines._areTexturesDirty) {
  40946. if (scene.texturesEnabled) {
  40947. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40948. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40949. return false;
  40950. }
  40951. }
  40952. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40953. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40954. return false;
  40955. }
  40956. }
  40957. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40958. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40959. return false;
  40960. }
  40961. }
  40962. var reflectionTexture = this._getReflectionTexture();
  40963. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40964. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40965. return false;
  40966. }
  40967. }
  40968. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40969. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40970. return false;
  40971. }
  40972. }
  40973. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40974. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40975. return false;
  40976. }
  40977. }
  40978. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40979. if (this._metallicTexture) {
  40980. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40981. return false;
  40982. }
  40983. }
  40984. else if (this._reflectivityTexture) {
  40985. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40986. return false;
  40987. }
  40988. }
  40989. if (this._microSurfaceTexture) {
  40990. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40991. return false;
  40992. }
  40993. }
  40994. }
  40995. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40996. // Bump texture cannot be not blocking.
  40997. if (!this._bumpTexture.isReady()) {
  40998. return false;
  40999. }
  41000. }
  41001. var refractionTexture = this._getRefractionTexture();
  41002. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41003. if (!refractionTexture.isReadyOrNotBlocking()) {
  41004. return false;
  41005. }
  41006. }
  41007. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41008. // This is blocking.
  41009. if (!this._environmentBRDFTexture.isReady()) {
  41010. return false;
  41011. }
  41012. }
  41013. }
  41014. }
  41015. if (defines._areImageProcessingDirty) {
  41016. if (!this._imageProcessingConfiguration.isReady()) {
  41017. return false;
  41018. }
  41019. }
  41020. if (!engine.getCaps().standardDerivatives) {
  41021. var bufferMesh = null;
  41022. if (mesh.getClassName() === "InstancedMesh") {
  41023. bufferMesh = mesh.sourceMesh;
  41024. }
  41025. else if (mesh.getClassName() === "Mesh") {
  41026. bufferMesh = mesh;
  41027. }
  41028. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41029. bufferMesh.createNormals(true);
  41030. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41031. }
  41032. }
  41033. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41034. if (effect) {
  41035. scene.resetCachedMaterial();
  41036. subMesh.setEffect(effect, defines);
  41037. this.buildUniformLayout();
  41038. }
  41039. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41040. return false;
  41041. }
  41042. defines._renderId = scene.getRenderId();
  41043. this._wasPreviouslyReady = true;
  41044. return true;
  41045. };
  41046. /**
  41047. * Specifies if the material uses metallic roughness workflow.
  41048. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41049. */
  41050. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41051. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41052. return true;
  41053. }
  41054. return false;
  41055. };
  41056. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41057. if (onCompiled === void 0) { onCompiled = null; }
  41058. if (onError === void 0) { onError = null; }
  41059. if (useInstances === void 0) { useInstances = null; }
  41060. if (useClipPlane === void 0) { useClipPlane = null; }
  41061. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41062. if (!defines.isDirty) {
  41063. return null;
  41064. }
  41065. defines.markAsProcessed();
  41066. var scene = this.getScene();
  41067. var engine = scene.getEngine();
  41068. // Fallbacks
  41069. var fallbacks = new BABYLON.EffectFallbacks();
  41070. var fallbackRank = 0;
  41071. if (defines.USESPHERICALINVERTEX) {
  41072. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41073. }
  41074. if (defines.FOG) {
  41075. fallbacks.addFallback(fallbackRank, "FOG");
  41076. }
  41077. if (defines.POINTSIZE) {
  41078. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41079. }
  41080. if (defines.LOGARITHMICDEPTH) {
  41081. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41082. }
  41083. if (defines.PARALLAX) {
  41084. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41085. }
  41086. if (defines.PARALLAXOCCLUSION) {
  41087. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41088. }
  41089. if (defines.ENVIRONMENTBRDF) {
  41090. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41091. }
  41092. if (defines.TANGENT) {
  41093. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41094. }
  41095. if (defines.BUMP) {
  41096. fallbacks.addFallback(fallbackRank++, "BUMP");
  41097. }
  41098. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41099. if (defines.SPECULARTERM) {
  41100. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41101. }
  41102. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41103. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41104. }
  41105. if (defines.LIGHTMAP) {
  41106. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41107. }
  41108. if (defines.NORMAL) {
  41109. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41110. }
  41111. if (defines.AMBIENT) {
  41112. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41113. }
  41114. if (defines.EMISSIVE) {
  41115. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41116. }
  41117. if (defines.VERTEXCOLOR) {
  41118. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41119. }
  41120. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41121. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41122. }
  41123. if (defines.MORPHTARGETS) {
  41124. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41125. }
  41126. //Attributes
  41127. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41128. if (defines.NORMAL) {
  41129. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41130. }
  41131. if (defines.TANGENT) {
  41132. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41133. }
  41134. if (defines.UV1) {
  41135. attribs.push(BABYLON.VertexBuffer.UVKind);
  41136. }
  41137. if (defines.UV2) {
  41138. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41139. }
  41140. if (defines.VERTEXCOLOR) {
  41141. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41142. }
  41143. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41144. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41145. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41146. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41147. "vFogInfos", "vFogColor", "pointSize",
  41148. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41149. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41150. "mBones",
  41151. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41152. "vLightingIntensity",
  41153. "logarithmicDepthConstant",
  41154. "vSphericalX", "vSphericalY", "vSphericalZ",
  41155. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41156. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41157. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41158. "vTangentSpaceParams"
  41159. ];
  41160. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41161. "bumpSampler", "lightmapSampler", "opacitySampler",
  41162. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41163. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41164. "microSurfaceSampler", "environmentBrdfSampler"];
  41165. var uniformBuffers = ["Material", "Scene"];
  41166. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41167. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41168. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41169. uniformsNames: uniforms,
  41170. uniformBuffersNames: uniformBuffers,
  41171. samplers: samplers,
  41172. defines: defines,
  41173. maxSimultaneousLights: this._maxSimultaneousLights
  41174. });
  41175. var join = defines.toString();
  41176. return engine.createEffect("pbr", {
  41177. attributes: attribs,
  41178. uniformsNames: uniforms,
  41179. uniformBuffersNames: uniformBuffers,
  41180. samplers: samplers,
  41181. defines: join,
  41182. fallbacks: fallbacks,
  41183. onCompiled: onCompiled,
  41184. onError: onError,
  41185. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41186. }, engine);
  41187. };
  41188. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41189. if (useInstances === void 0) { useInstances = null; }
  41190. if (useClipPlane === void 0) { useClipPlane = null; }
  41191. var scene = this.getScene();
  41192. var engine = scene.getEngine();
  41193. // Lights
  41194. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41195. defines._needNormals = true;
  41196. // Textures
  41197. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41198. if (defines._areTexturesDirty) {
  41199. defines._needUVs = false;
  41200. if (scene.texturesEnabled) {
  41201. if (scene.getEngine().getCaps().textureLOD) {
  41202. defines.LODBASEDMICROSFURACE = true;
  41203. }
  41204. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41205. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41206. }
  41207. else {
  41208. defines.ALBEDO = false;
  41209. }
  41210. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41212. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41213. }
  41214. else {
  41215. defines.AMBIENT = false;
  41216. }
  41217. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41219. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41220. }
  41221. else {
  41222. defines.OPACITY = false;
  41223. }
  41224. var reflectionTexture = this._getReflectionTexture();
  41225. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41226. defines.REFLECTION = true;
  41227. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41228. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41229. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41230. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41231. defines.INVERTCUBICMAP = true;
  41232. }
  41233. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41234. switch (reflectionTexture.coordinatesMode) {
  41235. case BABYLON.Texture.CUBIC_MODE:
  41236. case BABYLON.Texture.INVCUBIC_MODE:
  41237. defines.REFLECTIONMAP_CUBIC = true;
  41238. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41239. break;
  41240. case BABYLON.Texture.EXPLICIT_MODE:
  41241. defines.REFLECTIONMAP_EXPLICIT = true;
  41242. break;
  41243. case BABYLON.Texture.PLANAR_MODE:
  41244. defines.REFLECTIONMAP_PLANAR = true;
  41245. break;
  41246. case BABYLON.Texture.PROJECTION_MODE:
  41247. defines.REFLECTIONMAP_PROJECTION = true;
  41248. break;
  41249. case BABYLON.Texture.SKYBOX_MODE:
  41250. defines.REFLECTIONMAP_SKYBOX = true;
  41251. break;
  41252. case BABYLON.Texture.SPHERICAL_MODE:
  41253. defines.REFLECTIONMAP_SPHERICAL = true;
  41254. break;
  41255. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41256. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41257. break;
  41258. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41259. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41260. break;
  41261. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41262. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41263. break;
  41264. }
  41265. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41266. if (reflectionTexture.sphericalPolynomial) {
  41267. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41268. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41269. defines.USESPHERICALINVERTEX = false;
  41270. }
  41271. else {
  41272. defines.USESPHERICALINVERTEX = true;
  41273. }
  41274. }
  41275. }
  41276. }
  41277. else {
  41278. defines.REFLECTION = false;
  41279. defines.REFLECTIONMAP_3D = false;
  41280. defines.REFLECTIONMAP_SPHERICAL = false;
  41281. defines.REFLECTIONMAP_PLANAR = false;
  41282. defines.REFLECTIONMAP_CUBIC = false;
  41283. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41284. defines.REFLECTIONMAP_PROJECTION = false;
  41285. defines.REFLECTIONMAP_SKYBOX = false;
  41286. defines.REFLECTIONMAP_EXPLICIT = false;
  41287. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41288. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41289. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41290. defines.INVERTCUBICMAP = false;
  41291. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41292. defines.USESPHERICALINVERTEX = false;
  41293. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41294. defines.LODINREFLECTIONALPHA = false;
  41295. defines.GAMMAREFLECTION = false;
  41296. }
  41297. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41298. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41299. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41300. }
  41301. else {
  41302. defines.LIGHTMAP = false;
  41303. }
  41304. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41305. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41306. }
  41307. else {
  41308. defines.EMISSIVE = false;
  41309. }
  41310. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41311. if (this._metallicTexture) {
  41312. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41313. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41314. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41315. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41316. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41317. }
  41318. else if (this._reflectivityTexture) {
  41319. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41320. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41321. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41322. }
  41323. else {
  41324. defines.REFLECTIVITY = false;
  41325. }
  41326. if (this._microSurfaceTexture) {
  41327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41328. }
  41329. else {
  41330. defines.MICROSURFACEMAP = false;
  41331. }
  41332. }
  41333. else {
  41334. defines.REFLECTIVITY = false;
  41335. defines.MICROSURFACEMAP = false;
  41336. }
  41337. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41339. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41340. defines.PARALLAX = true;
  41341. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41342. }
  41343. else {
  41344. defines.PARALLAX = false;
  41345. }
  41346. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41347. }
  41348. else {
  41349. defines.BUMP = false;
  41350. }
  41351. var refractionTexture = this._getRefractionTexture();
  41352. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41353. defines.REFRACTION = true;
  41354. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41355. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41356. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41357. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41358. if (this._linkRefractionWithTransparency) {
  41359. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41360. }
  41361. }
  41362. else {
  41363. defines.REFRACTION = false;
  41364. }
  41365. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41366. defines.ENVIRONMENTBRDF = true;
  41367. }
  41368. else {
  41369. defines.ENVIRONMENTBRDF = false;
  41370. }
  41371. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41372. defines.ALPHAFROMALBEDO = true;
  41373. }
  41374. else {
  41375. defines.ALPHAFROMALBEDO = false;
  41376. }
  41377. }
  41378. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41379. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41380. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41381. if (!this.backFaceCulling && this._twoSidedLighting) {
  41382. defines.TWOSIDEDLIGHTING = true;
  41383. }
  41384. else {
  41385. defines.TWOSIDEDLIGHTING = false;
  41386. }
  41387. defines.ALPHATESTVALUE = this._alphaCutOff;
  41388. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41389. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41390. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41391. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41392. }
  41393. if (defines._areImageProcessingDirty) {
  41394. this._imageProcessingConfiguration.prepareDefines(defines);
  41395. }
  41396. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41397. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41398. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41399. // Misc.
  41400. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41401. // Values that need to be evaluated on every frame
  41402. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41403. // Attribs
  41404. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41405. };
  41406. /**
  41407. * Force shader compilation
  41408. */
  41409. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41410. var _this = this;
  41411. var localOptions = __assign({ clipPlane: false }, options);
  41412. var defines = new PBRMaterialDefines();
  41413. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41414. if (effect.isReady()) {
  41415. if (onCompiled) {
  41416. onCompiled(this);
  41417. }
  41418. }
  41419. else {
  41420. effect.onCompileObservable.add(function () {
  41421. if (onCompiled) {
  41422. onCompiled(_this);
  41423. }
  41424. });
  41425. }
  41426. };
  41427. /**
  41428. * Initializes the uniform buffer layout for the shader.
  41429. */
  41430. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41431. // Order is important !
  41432. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41433. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41434. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41435. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41436. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41437. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41438. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41439. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41440. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41441. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41442. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41443. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41444. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41445. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41446. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41447. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41448. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41449. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41450. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41451. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41452. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41453. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41454. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41455. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41456. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41457. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41458. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41459. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41460. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41461. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41462. this._uniformBuffer.addUniform("pointSize", 1);
  41463. this._uniformBuffer.create();
  41464. };
  41465. /**
  41466. * Unbinds the textures.
  41467. */
  41468. PBRBaseMaterial.prototype.unbind = function () {
  41469. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41470. this._uniformBuffer.setTexture("reflectionSampler", null);
  41471. }
  41472. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41473. this._uniformBuffer.setTexture("refractionSampler", null);
  41474. }
  41475. _super.prototype.unbind.call(this);
  41476. };
  41477. /**
  41478. * Binds the submesh data.
  41479. * @param world - The world matrix.
  41480. * @param mesh - The BJS mesh.
  41481. * @param subMesh - A submesh of the BJS mesh.
  41482. */
  41483. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41484. var scene = this.getScene();
  41485. var defines = subMesh._materialDefines;
  41486. if (!defines) {
  41487. return;
  41488. }
  41489. var effect = subMesh.effect;
  41490. if (!effect) {
  41491. return;
  41492. }
  41493. this._activeEffect = effect;
  41494. // Matrices
  41495. this.bindOnlyWorldMatrix(world);
  41496. // Normal Matrix
  41497. if (defines.OBJECTSPACE_NORMALMAP) {
  41498. world.toNormalMatrix(this._normalMatrix);
  41499. this.bindOnlyNormalMatrix(this._normalMatrix);
  41500. }
  41501. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41502. // Bones
  41503. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41504. var reflectionTexture = null;
  41505. if (mustRebind) {
  41506. this._uniformBuffer.bindToEffect(effect, "Material");
  41507. this.bindViewProjection(effect);
  41508. reflectionTexture = this._getReflectionTexture();
  41509. var refractionTexture = this._getRefractionTexture();
  41510. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41511. // Texture uniforms
  41512. if (scene.texturesEnabled) {
  41513. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41514. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41515. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41516. }
  41517. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41518. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41519. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41520. }
  41521. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41522. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41523. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41524. }
  41525. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41526. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41527. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41528. if (reflectionTexture.boundingBoxSize) {
  41529. var cubeTexture = reflectionTexture;
  41530. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41531. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41532. }
  41533. var polynomials = reflectionTexture.sphericalPolynomial;
  41534. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41535. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41536. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41537. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41538. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41539. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41540. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41541. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41542. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41543. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41544. }
  41545. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41546. }
  41547. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41548. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41549. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41550. }
  41551. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41552. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41553. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41554. }
  41555. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41556. if (this._metallicTexture) {
  41557. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41558. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41559. }
  41560. else if (this._reflectivityTexture) {
  41561. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41562. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41563. }
  41564. if (this._microSurfaceTexture) {
  41565. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41566. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41567. }
  41568. }
  41569. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41570. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41571. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41572. if (scene._mirroredCameraPosition) {
  41573. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41574. }
  41575. else {
  41576. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41577. }
  41578. }
  41579. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41580. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41581. var depth = 1.0;
  41582. if (!refractionTexture.isCube) {
  41583. if (refractionTexture.depth) {
  41584. depth = refractionTexture.depth;
  41585. }
  41586. }
  41587. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41588. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41589. }
  41590. }
  41591. // Point size
  41592. if (this.pointsCloud) {
  41593. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41594. }
  41595. // Colors
  41596. if (defines.METALLICWORKFLOW) {
  41597. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41598. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41599. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41600. }
  41601. else {
  41602. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41603. }
  41604. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41605. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41606. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41607. // Misc
  41608. this._lightingInfos.x = this._directIntensity;
  41609. this._lightingInfos.y = this._emissiveIntensity;
  41610. this._lightingInfos.z = this._environmentIntensity;
  41611. this._lightingInfos.w = this._specularIntensity;
  41612. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41613. }
  41614. // Textures
  41615. if (scene.texturesEnabled) {
  41616. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41617. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41618. }
  41619. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41620. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41621. }
  41622. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41623. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41624. }
  41625. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41626. if (defines.LODBASEDMICROSFURACE) {
  41627. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41628. }
  41629. else {
  41630. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41631. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41632. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41633. }
  41634. }
  41635. if (defines.ENVIRONMENTBRDF) {
  41636. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41637. }
  41638. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41639. if (defines.LODBASEDMICROSFURACE) {
  41640. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41641. }
  41642. else {
  41643. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41644. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41645. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41646. }
  41647. }
  41648. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41649. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41650. }
  41651. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41652. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41653. }
  41654. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41655. if (this._metallicTexture) {
  41656. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41657. }
  41658. else if (this._reflectivityTexture) {
  41659. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41660. }
  41661. if (this._microSurfaceTexture) {
  41662. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41663. }
  41664. }
  41665. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41666. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41667. }
  41668. }
  41669. // Clip plane
  41670. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41671. // Colors
  41672. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41673. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41674. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41675. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41676. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41677. }
  41678. if (mustRebind || !this.isFrozen) {
  41679. // Lights
  41680. if (scene.lightsEnabled && !this._disableLighting) {
  41681. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41682. }
  41683. // View
  41684. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41685. this.bindView(effect);
  41686. }
  41687. // Fog
  41688. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41689. // Morph targets
  41690. if (defines.NUM_MORPH_INFLUENCERS) {
  41691. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41692. }
  41693. // image processing
  41694. this._imageProcessingConfiguration.bind(this._activeEffect);
  41695. // Log. depth
  41696. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41697. }
  41698. this._uniformBuffer.update();
  41699. this._afterBind(mesh);
  41700. };
  41701. /**
  41702. * Returns the animatable textures.
  41703. * @returns - Array of animatable textures.
  41704. */
  41705. PBRBaseMaterial.prototype.getAnimatables = function () {
  41706. var results = [];
  41707. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41708. results.push(this._albedoTexture);
  41709. }
  41710. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41711. results.push(this._ambientTexture);
  41712. }
  41713. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41714. results.push(this._opacityTexture);
  41715. }
  41716. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41717. results.push(this._reflectionTexture);
  41718. }
  41719. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41720. results.push(this._emissiveTexture);
  41721. }
  41722. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41723. results.push(this._metallicTexture);
  41724. }
  41725. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41726. results.push(this._reflectivityTexture);
  41727. }
  41728. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41729. results.push(this._bumpTexture);
  41730. }
  41731. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41732. results.push(this._lightmapTexture);
  41733. }
  41734. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41735. results.push(this._refractionTexture);
  41736. }
  41737. return results;
  41738. };
  41739. /**
  41740. * Returns the texture used for reflections.
  41741. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41742. */
  41743. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41744. if (this._reflectionTexture) {
  41745. return this._reflectionTexture;
  41746. }
  41747. return this.getScene().environmentTexture;
  41748. };
  41749. /**
  41750. * Returns the texture used for refraction or null if none is used.
  41751. * @returns - Refection texture if present. If no refraction texture and refraction
  41752. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41753. */
  41754. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41755. if (this._refractionTexture) {
  41756. return this._refractionTexture;
  41757. }
  41758. if (this._linkRefractionWithTransparency) {
  41759. return this.getScene().environmentTexture;
  41760. }
  41761. return null;
  41762. };
  41763. /**
  41764. * Disposes the resources of the material.
  41765. * @param forceDisposeEffect - Forces the disposal of effects.
  41766. * @param forceDisposeTextures - Forces the disposal of all textures.
  41767. */
  41768. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41769. if (forceDisposeTextures) {
  41770. if (this._albedoTexture) {
  41771. this._albedoTexture.dispose();
  41772. }
  41773. if (this._ambientTexture) {
  41774. this._ambientTexture.dispose();
  41775. }
  41776. if (this._opacityTexture) {
  41777. this._opacityTexture.dispose();
  41778. }
  41779. if (this._reflectionTexture) {
  41780. this._reflectionTexture.dispose();
  41781. }
  41782. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41783. this._environmentBRDFTexture.dispose();
  41784. }
  41785. if (this._emissiveTexture) {
  41786. this._emissiveTexture.dispose();
  41787. }
  41788. if (this._metallicTexture) {
  41789. this._metallicTexture.dispose();
  41790. }
  41791. if (this._reflectivityTexture) {
  41792. this._reflectivityTexture.dispose();
  41793. }
  41794. if (this._bumpTexture) {
  41795. this._bumpTexture.dispose();
  41796. }
  41797. if (this._lightmapTexture) {
  41798. this._lightmapTexture.dispose();
  41799. }
  41800. if (this._refractionTexture) {
  41801. this._refractionTexture.dispose();
  41802. }
  41803. }
  41804. this._renderTargets.dispose();
  41805. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41806. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41807. }
  41808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41809. };
  41810. /**
  41811. * Stores the reflectivity values based on metallic roughness workflow.
  41812. */
  41813. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41814. __decorate([
  41815. BABYLON.serializeAsImageProcessingConfiguration()
  41816. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41817. __decorate([
  41818. BABYLON.serialize()
  41819. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41820. __decorate([
  41821. BABYLON.serialize()
  41822. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41823. return PBRBaseMaterial;
  41824. }(BABYLON.PushMaterial));
  41825. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41826. })(BABYLON || (BABYLON = {}));
  41827. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41828. var BABYLON;
  41829. (function (BABYLON) {
  41830. /**
  41831. * The Physically based simple base material of BJS.
  41832. *
  41833. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41834. * It is used as the base class for both the specGloss and metalRough conventions.
  41835. */
  41836. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41837. __extends(PBRBaseSimpleMaterial, _super);
  41838. /**
  41839. * Instantiates a new PBRMaterial instance.
  41840. *
  41841. * @param name The material name
  41842. * @param scene The scene the material will be use in.
  41843. */
  41844. function PBRBaseSimpleMaterial(name, scene) {
  41845. var _this = _super.call(this, name, scene) || this;
  41846. /**
  41847. * Number of Simultaneous lights allowed on the material.
  41848. */
  41849. _this.maxSimultaneousLights = 4;
  41850. /**
  41851. * If sets to true, disables all the lights affecting the material.
  41852. */
  41853. _this.disableLighting = false;
  41854. /**
  41855. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41856. */
  41857. _this.invertNormalMapX = false;
  41858. /**
  41859. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41860. */
  41861. _this.invertNormalMapY = false;
  41862. /**
  41863. * Emissivie color used to self-illuminate the model.
  41864. */
  41865. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41866. /**
  41867. * Occlusion Channel Strenght.
  41868. */
  41869. _this.occlusionStrength = 1.0;
  41870. _this.useLightmapAsShadowmap = false;
  41871. _this._useAlphaFromAlbedoTexture = true;
  41872. _this._useAmbientInGrayScale = true;
  41873. return _this;
  41874. }
  41875. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41876. /**
  41877. * Gets the current double sided mode.
  41878. */
  41879. get: function () {
  41880. return this._twoSidedLighting;
  41881. },
  41882. /**
  41883. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41884. */
  41885. set: function (value) {
  41886. if (this._twoSidedLighting === value) {
  41887. return;
  41888. }
  41889. this._twoSidedLighting = value;
  41890. this.backFaceCulling = !value;
  41891. this._markAllSubMeshesAsTexturesDirty();
  41892. },
  41893. enumerable: true,
  41894. configurable: true
  41895. });
  41896. /**
  41897. * Return the active textures of the material.
  41898. */
  41899. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41900. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41901. if (this.environmentTexture) {
  41902. activeTextures.push(this.environmentTexture);
  41903. }
  41904. if (this.normalTexture) {
  41905. activeTextures.push(this.normalTexture);
  41906. }
  41907. if (this.emissiveTexture) {
  41908. activeTextures.push(this.emissiveTexture);
  41909. }
  41910. if (this.occlusionTexture) {
  41911. activeTextures.push(this.occlusionTexture);
  41912. }
  41913. if (this.lightmapTexture) {
  41914. activeTextures.push(this.lightmapTexture);
  41915. }
  41916. return activeTextures;
  41917. };
  41918. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41919. if (_super.prototype.hasTexture.call(this, texture)) {
  41920. return true;
  41921. }
  41922. if (this.lightmapTexture === texture) {
  41923. return true;
  41924. }
  41925. return false;
  41926. };
  41927. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41928. return "PBRBaseSimpleMaterial";
  41929. };
  41930. __decorate([
  41931. BABYLON.serialize(),
  41932. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41933. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41934. __decorate([
  41935. BABYLON.serialize(),
  41936. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41937. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41938. __decorate([
  41939. BABYLON.serializeAsTexture(),
  41940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41941. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41942. __decorate([
  41943. BABYLON.serialize(),
  41944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41945. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41946. __decorate([
  41947. BABYLON.serialize(),
  41948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41949. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41950. __decorate([
  41951. BABYLON.serializeAsTexture(),
  41952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41953. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41954. __decorate([
  41955. BABYLON.serializeAsColor3("emissive"),
  41956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41957. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41958. __decorate([
  41959. BABYLON.serializeAsTexture(),
  41960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41961. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41962. __decorate([
  41963. BABYLON.serialize(),
  41964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41965. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41966. __decorate([
  41967. BABYLON.serializeAsTexture(),
  41968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41969. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41970. __decorate([
  41971. BABYLON.serialize(),
  41972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41973. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41974. __decorate([
  41975. BABYLON.serialize()
  41976. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41977. __decorate([
  41978. BABYLON.serializeAsTexture(),
  41979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41980. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41981. __decorate([
  41982. BABYLON.serialize(),
  41983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41984. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41985. return PBRBaseSimpleMaterial;
  41986. }(BABYLON.PBRBaseMaterial));
  41987. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41988. })(BABYLON || (BABYLON = {}));
  41989. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. /**
  41993. * The Physically based material of BJS.
  41994. *
  41995. * This offers the main features of a standard PBR material.
  41996. * For more information, please refer to the documentation :
  41997. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41998. */
  41999. var PBRMaterial = /** @class */ (function (_super) {
  42000. __extends(PBRMaterial, _super);
  42001. /**
  42002. * Instantiates a new PBRMaterial instance.
  42003. *
  42004. * @param name The material name
  42005. * @param scene The scene the material will be use in.
  42006. */
  42007. function PBRMaterial(name, scene) {
  42008. var _this = _super.call(this, name, scene) || this;
  42009. /**
  42010. * Intensity of the direct lights e.g. the four lights available in your scene.
  42011. * This impacts both the direct diffuse and specular highlights.
  42012. */
  42013. _this.directIntensity = 1.0;
  42014. /**
  42015. * Intensity of the emissive part of the material.
  42016. * This helps controlling the emissive effect without modifying the emissive color.
  42017. */
  42018. _this.emissiveIntensity = 1.0;
  42019. /**
  42020. * Intensity of the environment e.g. how much the environment will light the object
  42021. * either through harmonics for rough material or through the refelction for shiny ones.
  42022. */
  42023. _this.environmentIntensity = 1.0;
  42024. /**
  42025. * This is a special control allowing the reduction of the specular highlights coming from the
  42026. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42027. */
  42028. _this.specularIntensity = 1.0;
  42029. /**
  42030. * Debug Control allowing disabling the bump map on this material.
  42031. */
  42032. _this.disableBumpMap = false;
  42033. /**
  42034. * AKA Occlusion Texture Intensity in other nomenclature.
  42035. */
  42036. _this.ambientTextureStrength = 1.0;
  42037. /**
  42038. * The color of a material in ambient lighting.
  42039. */
  42040. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42041. /**
  42042. * AKA Diffuse Color in other nomenclature.
  42043. */
  42044. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42045. /**
  42046. * AKA Specular Color in other nomenclature.
  42047. */
  42048. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42049. /**
  42050. * The color reflected from the material.
  42051. */
  42052. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42053. /**
  42054. * The color emitted from the material.
  42055. */
  42056. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42057. /**
  42058. * AKA Glossiness in other nomenclature.
  42059. */
  42060. _this.microSurface = 1.0;
  42061. /**
  42062. * source material index of refraction (IOR)' / 'destination material IOR.
  42063. */
  42064. _this.indexOfRefraction = 0.66;
  42065. /**
  42066. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42067. */
  42068. _this.invertRefractionY = false;
  42069. /**
  42070. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42071. * Materials half opaque for instance using refraction could benefit from this control.
  42072. */
  42073. _this.linkRefractionWithTransparency = false;
  42074. _this.useLightmapAsShadowmap = false;
  42075. /**
  42076. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42077. */
  42078. _this.useAlphaFromAlbedoTexture = false;
  42079. /**
  42080. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42081. */
  42082. _this.forceAlphaTest = false;
  42083. /**
  42084. * Defines the alpha limits in alpha test mode.
  42085. */
  42086. _this.alphaCutOff = 0.4;
  42087. /**
  42088. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42089. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42090. */
  42091. _this.useSpecularOverAlpha = true;
  42092. /**
  42093. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42094. */
  42095. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42096. /**
  42097. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42098. */
  42099. _this.useRoughnessFromMetallicTextureAlpha = true;
  42100. /**
  42101. * Specifies if the metallic texture contains the roughness information in its green channel.
  42102. */
  42103. _this.useRoughnessFromMetallicTextureGreen = false;
  42104. /**
  42105. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42106. */
  42107. _this.useMetallnessFromMetallicTextureBlue = false;
  42108. /**
  42109. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42110. */
  42111. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42112. /**
  42113. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42114. */
  42115. _this.useAmbientInGrayScale = false;
  42116. /**
  42117. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42118. * The material will try to infer what glossiness each pixel should be.
  42119. */
  42120. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42121. /**
  42122. * BJS is using an harcoded light falloff based on a manually sets up range.
  42123. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42124. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42125. */
  42126. _this.usePhysicalLightFalloff = true;
  42127. /**
  42128. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42129. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42130. */
  42131. _this.useRadianceOverAlpha = true;
  42132. /**
  42133. * Allows using an object space normal map (instead of tangent space).
  42134. */
  42135. _this.useObjectSpaceNormalMap = false;
  42136. /**
  42137. * Allows using the bump map in parallax mode.
  42138. */
  42139. _this.useParallax = false;
  42140. /**
  42141. * Allows using the bump map in parallax occlusion mode.
  42142. */
  42143. _this.useParallaxOcclusion = false;
  42144. /**
  42145. * Controls the scale bias of the parallax mode.
  42146. */
  42147. _this.parallaxScaleBias = 0.05;
  42148. /**
  42149. * If sets to true, disables all the lights affecting the material.
  42150. */
  42151. _this.disableLighting = false;
  42152. /**
  42153. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42154. */
  42155. _this.forceIrradianceInFragment = false;
  42156. /**
  42157. * Number of Simultaneous lights allowed on the material.
  42158. */
  42159. _this.maxSimultaneousLights = 4;
  42160. /**
  42161. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42162. */
  42163. _this.invertNormalMapX = false;
  42164. /**
  42165. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42166. */
  42167. _this.invertNormalMapY = false;
  42168. /**
  42169. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42170. */
  42171. _this.twoSidedLighting = false;
  42172. /**
  42173. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42174. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42175. */
  42176. _this.useAlphaFresnel = false;
  42177. /**
  42178. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42179. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42180. */
  42181. _this.useLinearAlphaFresnel = false;
  42182. /**
  42183. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42184. * And/Or occlude the blended part.
  42185. */
  42186. _this.environmentBRDFTexture = null;
  42187. /**
  42188. * Force normal to face away from face.
  42189. */
  42190. _this.forceNormalForward = false;
  42191. /**
  42192. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42193. * makes the reflect vector face the model (under horizon).
  42194. */
  42195. _this.useHorizonOcclusion = true;
  42196. /**
  42197. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42198. * too much the area relying on ambient texture to define their ambient occlusion.
  42199. */
  42200. _this.useRadianceOcclusion = true;
  42201. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42202. return _this;
  42203. }
  42204. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42205. /**
  42206. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42207. */
  42208. get: function () {
  42209. return this._PBRMATERIAL_OPAQUE;
  42210. },
  42211. enumerable: true,
  42212. configurable: true
  42213. });
  42214. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42215. /**
  42216. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42217. */
  42218. get: function () {
  42219. return this._PBRMATERIAL_ALPHATEST;
  42220. },
  42221. enumerable: true,
  42222. configurable: true
  42223. });
  42224. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42225. /**
  42226. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42227. */
  42228. get: function () {
  42229. return this._PBRMATERIAL_ALPHABLEND;
  42230. },
  42231. enumerable: true,
  42232. configurable: true
  42233. });
  42234. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42235. /**
  42236. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42237. * They are also discarded below the alpha cutoff threshold to improve performances.
  42238. */
  42239. get: function () {
  42240. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42241. },
  42242. enumerable: true,
  42243. configurable: true
  42244. });
  42245. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42246. /**
  42247. * Gets the image processing configuration used either in this material.
  42248. */
  42249. get: function () {
  42250. return this._imageProcessingConfiguration;
  42251. },
  42252. /**
  42253. * Sets the Default image processing configuration used either in the this material.
  42254. *
  42255. * If sets to null, the scene one is in use.
  42256. */
  42257. set: function (value) {
  42258. this._attachImageProcessingConfiguration(value);
  42259. // Ensure the effect will be rebuilt.
  42260. this._markAllSubMeshesAsTexturesDirty();
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42266. /**
  42267. * Gets wether the color curves effect is enabled.
  42268. */
  42269. get: function () {
  42270. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42271. },
  42272. /**
  42273. * Sets wether the color curves effect is enabled.
  42274. */
  42275. set: function (value) {
  42276. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42277. },
  42278. enumerable: true,
  42279. configurable: true
  42280. });
  42281. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42282. /**
  42283. * Gets wether the color grading effect is enabled.
  42284. */
  42285. get: function () {
  42286. return this.imageProcessingConfiguration.colorGradingEnabled;
  42287. },
  42288. /**
  42289. * Gets wether the color grading effect is enabled.
  42290. */
  42291. set: function (value) {
  42292. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42298. /**
  42299. * Gets wether tonemapping is enabled or not.
  42300. */
  42301. get: function () {
  42302. return this._imageProcessingConfiguration.toneMappingEnabled;
  42303. },
  42304. /**
  42305. * Sets wether tonemapping is enabled or not
  42306. */
  42307. set: function (value) {
  42308. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42309. },
  42310. enumerable: true,
  42311. configurable: true
  42312. });
  42313. ;
  42314. ;
  42315. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42316. /**
  42317. * The camera exposure used on this material.
  42318. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42319. * This corresponds to a photographic exposure.
  42320. */
  42321. get: function () {
  42322. return this._imageProcessingConfiguration.exposure;
  42323. },
  42324. /**
  42325. * The camera exposure used on this material.
  42326. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42327. * This corresponds to a photographic exposure.
  42328. */
  42329. set: function (value) {
  42330. this._imageProcessingConfiguration.exposure = value;
  42331. },
  42332. enumerable: true,
  42333. configurable: true
  42334. });
  42335. ;
  42336. ;
  42337. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42338. /**
  42339. * Gets The camera contrast used on this material.
  42340. */
  42341. get: function () {
  42342. return this._imageProcessingConfiguration.contrast;
  42343. },
  42344. /**
  42345. * Sets The camera contrast used on this material.
  42346. */
  42347. set: function (value) {
  42348. this._imageProcessingConfiguration.contrast = value;
  42349. },
  42350. enumerable: true,
  42351. configurable: true
  42352. });
  42353. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42354. /**
  42355. * Gets the Color Grading 2D Lookup Texture.
  42356. */
  42357. get: function () {
  42358. return this._imageProcessingConfiguration.colorGradingTexture;
  42359. },
  42360. /**
  42361. * Sets the Color Grading 2D Lookup Texture.
  42362. */
  42363. set: function (value) {
  42364. this._imageProcessingConfiguration.colorGradingTexture = value;
  42365. },
  42366. enumerable: true,
  42367. configurable: true
  42368. });
  42369. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42370. /**
  42371. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42372. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42373. * 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;
  42374. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42375. */
  42376. get: function () {
  42377. return this._imageProcessingConfiguration.colorCurves;
  42378. },
  42379. /**
  42380. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42381. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42382. * 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;
  42383. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42384. */
  42385. set: function (value) {
  42386. this._imageProcessingConfiguration.colorCurves = value;
  42387. },
  42388. enumerable: true,
  42389. configurable: true
  42390. });
  42391. /**
  42392. * Returns the name of this material class.
  42393. */
  42394. PBRMaterial.prototype.getClassName = function () {
  42395. return "PBRMaterial";
  42396. };
  42397. /**
  42398. * Returns an array of the actively used textures.
  42399. * @returns - Array of BaseTextures
  42400. */
  42401. PBRMaterial.prototype.getActiveTextures = function () {
  42402. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42403. if (this._albedoTexture) {
  42404. activeTextures.push(this._albedoTexture);
  42405. }
  42406. if (this._ambientTexture) {
  42407. activeTextures.push(this._ambientTexture);
  42408. }
  42409. if (this._opacityTexture) {
  42410. activeTextures.push(this._opacityTexture);
  42411. }
  42412. if (this._reflectionTexture) {
  42413. activeTextures.push(this._reflectionTexture);
  42414. }
  42415. if (this._emissiveTexture) {
  42416. activeTextures.push(this._emissiveTexture);
  42417. }
  42418. if (this._reflectivityTexture) {
  42419. activeTextures.push(this._reflectivityTexture);
  42420. }
  42421. if (this._metallicTexture) {
  42422. activeTextures.push(this._metallicTexture);
  42423. }
  42424. if (this._microSurfaceTexture) {
  42425. activeTextures.push(this._microSurfaceTexture);
  42426. }
  42427. if (this._bumpTexture) {
  42428. activeTextures.push(this._bumpTexture);
  42429. }
  42430. if (this._lightmapTexture) {
  42431. activeTextures.push(this._lightmapTexture);
  42432. }
  42433. if (this._refractionTexture) {
  42434. activeTextures.push(this._refractionTexture);
  42435. }
  42436. return activeTextures;
  42437. };
  42438. /**
  42439. * Checks to see if a texture is used in the material.
  42440. * @param texture - Base texture to use.
  42441. * @returns - Boolean specifying if a texture is used in the material.
  42442. */
  42443. PBRMaterial.prototype.hasTexture = function (texture) {
  42444. if (_super.prototype.hasTexture.call(this, texture)) {
  42445. return true;
  42446. }
  42447. if (this._albedoTexture === texture) {
  42448. return true;
  42449. }
  42450. if (this._ambientTexture === texture) {
  42451. return true;
  42452. }
  42453. if (this._opacityTexture === texture) {
  42454. return true;
  42455. }
  42456. if (this._reflectionTexture === texture) {
  42457. return true;
  42458. }
  42459. if (this._reflectivityTexture === texture) {
  42460. return true;
  42461. }
  42462. if (this._metallicTexture === texture) {
  42463. return true;
  42464. }
  42465. if (this._microSurfaceTexture === texture) {
  42466. return true;
  42467. }
  42468. if (this._bumpTexture === texture) {
  42469. return true;
  42470. }
  42471. if (this._lightmapTexture === texture) {
  42472. return true;
  42473. }
  42474. if (this._refractionTexture === texture) {
  42475. return true;
  42476. }
  42477. return false;
  42478. };
  42479. /**
  42480. * Makes a duplicate of the current material.
  42481. * @param name - name to use for the new material.
  42482. */
  42483. PBRMaterial.prototype.clone = function (name) {
  42484. var _this = this;
  42485. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42486. clone.id = name;
  42487. clone.name = name;
  42488. return clone;
  42489. };
  42490. /**
  42491. * Serializes this PBR Material.
  42492. * @returns - An object with the serialized material.
  42493. */
  42494. PBRMaterial.prototype.serialize = function () {
  42495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42496. serializationObject.customType = "BABYLON.PBRMaterial";
  42497. return serializationObject;
  42498. };
  42499. // Statics
  42500. /**
  42501. * Parses a PBR Material from a serialized object.
  42502. * @param source - Serialized object.
  42503. * @param scene - BJS scene instance.
  42504. * @param rootUrl - url for the scene object
  42505. * @returns - PBRMaterial
  42506. */
  42507. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42508. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42509. };
  42510. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42511. /**
  42512. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42513. */
  42514. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42515. /**
  42516. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42517. */
  42518. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42519. /**
  42520. * 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.
  42521. * They are also discarded below the alpha cutoff threshold to improve performances.
  42522. */
  42523. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42524. __decorate([
  42525. BABYLON.serialize(),
  42526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42527. ], PBRMaterial.prototype, "directIntensity", void 0);
  42528. __decorate([
  42529. BABYLON.serialize(),
  42530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42531. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42532. __decorate([
  42533. BABYLON.serialize(),
  42534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42535. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42536. __decorate([
  42537. BABYLON.serialize(),
  42538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42539. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42540. __decorate([
  42541. BABYLON.serialize(),
  42542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42543. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42544. __decorate([
  42545. BABYLON.serializeAsTexture(),
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42547. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42548. __decorate([
  42549. BABYLON.serializeAsTexture(),
  42550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42551. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42552. __decorate([
  42553. BABYLON.serialize(),
  42554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42555. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42556. __decorate([
  42557. BABYLON.serializeAsTexture(),
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42559. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42560. __decorate([
  42561. BABYLON.serializeAsTexture(),
  42562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42563. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42564. __decorate([
  42565. BABYLON.serializeAsTexture(),
  42566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42567. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42568. __decorate([
  42569. BABYLON.serializeAsTexture(),
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42571. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42572. __decorate([
  42573. BABYLON.serializeAsTexture(),
  42574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42575. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42576. __decorate([
  42577. BABYLON.serialize(),
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42579. ], PBRMaterial.prototype, "metallic", void 0);
  42580. __decorate([
  42581. BABYLON.serialize(),
  42582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42583. ], PBRMaterial.prototype, "roughness", void 0);
  42584. __decorate([
  42585. BABYLON.serializeAsTexture(),
  42586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42587. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42588. __decorate([
  42589. BABYLON.serializeAsTexture(),
  42590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42591. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42592. __decorate([
  42593. BABYLON.serializeAsTexture(),
  42594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42595. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42596. __decorate([
  42597. BABYLON.serializeAsTexture(),
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42599. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42600. __decorate([
  42601. BABYLON.serializeAsColor3("ambient"),
  42602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42603. ], PBRMaterial.prototype, "ambientColor", void 0);
  42604. __decorate([
  42605. BABYLON.serializeAsColor3("albedo"),
  42606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42607. ], PBRMaterial.prototype, "albedoColor", void 0);
  42608. __decorate([
  42609. BABYLON.serializeAsColor3("reflectivity"),
  42610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42611. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42612. __decorate([
  42613. BABYLON.serializeAsColor3("reflection"),
  42614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42615. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42616. __decorate([
  42617. BABYLON.serializeAsColor3("emissive"),
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42619. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42620. __decorate([
  42621. BABYLON.serialize(),
  42622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42623. ], PBRMaterial.prototype, "microSurface", void 0);
  42624. __decorate([
  42625. BABYLON.serialize(),
  42626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42627. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42628. __decorate([
  42629. BABYLON.serialize(),
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42631. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42632. __decorate([
  42633. BABYLON.serialize(),
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42635. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42636. __decorate([
  42637. BABYLON.serialize(),
  42638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42639. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42640. __decorate([
  42641. BABYLON.serialize(),
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42643. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42644. __decorate([
  42645. BABYLON.serialize(),
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42647. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42648. __decorate([
  42649. BABYLON.serialize(),
  42650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42651. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42652. __decorate([
  42653. BABYLON.serialize(),
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42656. __decorate([
  42657. BABYLON.serialize(),
  42658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42659. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42660. __decorate([
  42661. BABYLON.serialize(),
  42662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42663. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42664. __decorate([
  42665. BABYLON.serialize(),
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42668. __decorate([
  42669. BABYLON.serialize(),
  42670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42671. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42672. __decorate([
  42673. BABYLON.serialize(),
  42674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42675. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42676. __decorate([
  42677. BABYLON.serialize(),
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42679. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42680. __decorate([
  42681. BABYLON.serialize(),
  42682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42683. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42684. __decorate([
  42685. BABYLON.serialize(),
  42686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42687. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42688. __decorate([
  42689. BABYLON.serialize(),
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42692. __decorate([
  42693. BABYLON.serialize(),
  42694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42695. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42696. __decorate([
  42697. BABYLON.serialize(),
  42698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42699. ], PBRMaterial.prototype, "useParallax", void 0);
  42700. __decorate([
  42701. BABYLON.serialize(),
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42703. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42704. __decorate([
  42705. BABYLON.serialize(),
  42706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42707. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42708. __decorate([
  42709. BABYLON.serialize(),
  42710. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42711. ], PBRMaterial.prototype, "disableLighting", void 0);
  42712. __decorate([
  42713. BABYLON.serialize(),
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42716. __decorate([
  42717. BABYLON.serialize(),
  42718. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42719. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42720. __decorate([
  42721. BABYLON.serialize(),
  42722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42723. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42724. __decorate([
  42725. BABYLON.serialize(),
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42727. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42728. __decorate([
  42729. BABYLON.serialize(),
  42730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42731. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42732. __decorate([
  42733. BABYLON.serialize(),
  42734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42735. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42736. __decorate([
  42737. BABYLON.serialize(),
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42739. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42740. __decorate([
  42741. BABYLON.serializeAsTexture(),
  42742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42743. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42744. __decorate([
  42745. BABYLON.serialize(),
  42746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42747. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42748. __decorate([
  42749. BABYLON.serialize(),
  42750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42751. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42752. __decorate([
  42753. BABYLON.serialize(),
  42754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42755. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42756. return PBRMaterial;
  42757. }(BABYLON.PBRBaseMaterial));
  42758. BABYLON.PBRMaterial = PBRMaterial;
  42759. })(BABYLON || (BABYLON = {}));
  42760. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42761. var BABYLON;
  42762. (function (BABYLON) {
  42763. /**
  42764. * The PBR material of BJS following the metal roughness convention.
  42765. *
  42766. * This fits to the PBR convention in the GLTF definition:
  42767. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42768. */
  42769. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42770. __extends(PBRMetallicRoughnessMaterial, _super);
  42771. /**
  42772. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42773. *
  42774. * @param name The material name
  42775. * @param scene The scene the material will be use in.
  42776. */
  42777. function PBRMetallicRoughnessMaterial(name, scene) {
  42778. var _this = _super.call(this, name, scene) || this;
  42779. _this._useRoughnessFromMetallicTextureAlpha = false;
  42780. _this._useRoughnessFromMetallicTextureGreen = true;
  42781. _this._useMetallnessFromMetallicTextureBlue = true;
  42782. _this.metallic = 1.0;
  42783. _this.roughness = 1.0;
  42784. return _this;
  42785. }
  42786. /**
  42787. * Return the currrent class name of the material.
  42788. */
  42789. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42790. return "PBRMetallicRoughnessMaterial";
  42791. };
  42792. /**
  42793. * Return the active textures of the material.
  42794. */
  42795. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42796. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42797. if (this.baseTexture) {
  42798. activeTextures.push(this.baseTexture);
  42799. }
  42800. if (this.metallicRoughnessTexture) {
  42801. activeTextures.push(this.metallicRoughnessTexture);
  42802. }
  42803. return activeTextures;
  42804. };
  42805. /**
  42806. * Checks to see if a texture is used in the material.
  42807. * @param texture - Base texture to use.
  42808. * @returns - Boolean specifying if a texture is used in the material.
  42809. */
  42810. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42811. if (_super.prototype.hasTexture.call(this, texture)) {
  42812. return true;
  42813. }
  42814. if (this.baseTexture === texture) {
  42815. return true;
  42816. }
  42817. if (this.metallicRoughnessTexture === texture) {
  42818. return true;
  42819. }
  42820. return false;
  42821. };
  42822. /**
  42823. * Makes a duplicate of the current material.
  42824. * @param name - name to use for the new material.
  42825. */
  42826. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42827. var _this = this;
  42828. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42829. clone.id = name;
  42830. clone.name = name;
  42831. return clone;
  42832. };
  42833. /**
  42834. * Serialize the material to a parsable JSON object.
  42835. */
  42836. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42837. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42838. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42839. return serializationObject;
  42840. };
  42841. /**
  42842. * Parses a JSON object correponding to the serialize function.
  42843. */
  42844. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42845. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42846. };
  42847. __decorate([
  42848. BABYLON.serializeAsColor3(),
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42850. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42851. __decorate([
  42852. BABYLON.serializeAsTexture(),
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42854. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42855. __decorate([
  42856. BABYLON.serialize(),
  42857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42858. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42859. __decorate([
  42860. BABYLON.serialize(),
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42862. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42863. __decorate([
  42864. BABYLON.serializeAsTexture(),
  42865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42866. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42867. return PBRMetallicRoughnessMaterial;
  42868. }(BABYLON.PBRBaseSimpleMaterial));
  42869. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42870. })(BABYLON || (BABYLON = {}));
  42871. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42872. var BABYLON;
  42873. (function (BABYLON) {
  42874. /**
  42875. * The PBR material of BJS following the specular glossiness convention.
  42876. *
  42877. * This fits to the PBR convention in the GLTF definition:
  42878. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42879. */
  42880. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42881. __extends(PBRSpecularGlossinessMaterial, _super);
  42882. /**
  42883. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42884. *
  42885. * @param name The material name
  42886. * @param scene The scene the material will be use in.
  42887. */
  42888. function PBRSpecularGlossinessMaterial(name, scene) {
  42889. var _this = _super.call(this, name, scene) || this;
  42890. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42891. return _this;
  42892. }
  42893. /**
  42894. * Return the currrent class name of the material.
  42895. */
  42896. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42897. return "PBRSpecularGlossinessMaterial";
  42898. };
  42899. /**
  42900. * Return the active textures of the material.
  42901. */
  42902. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42903. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42904. if (this.diffuseTexture) {
  42905. activeTextures.push(this.diffuseTexture);
  42906. }
  42907. if (this.specularGlossinessTexture) {
  42908. activeTextures.push(this.specularGlossinessTexture);
  42909. }
  42910. return activeTextures;
  42911. };
  42912. /**
  42913. * Checks to see if a texture is used in the material.
  42914. * @param texture - Base texture to use.
  42915. * @returns - Boolean specifying if a texture is used in the material.
  42916. */
  42917. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42918. if (_super.prototype.hasTexture.call(this, texture)) {
  42919. return true;
  42920. }
  42921. if (this.diffuseTexture === texture) {
  42922. return true;
  42923. }
  42924. if (this.specularGlossinessTexture === texture) {
  42925. return true;
  42926. }
  42927. return false;
  42928. };
  42929. /**
  42930. * Makes a duplicate of the current material.
  42931. * @param name - name to use for the new material.
  42932. */
  42933. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42934. var _this = this;
  42935. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42936. clone.id = name;
  42937. clone.name = name;
  42938. return clone;
  42939. };
  42940. /**
  42941. * Serialize the material to a parsable JSON object.
  42942. */
  42943. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42944. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42945. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42946. return serializationObject;
  42947. };
  42948. /**
  42949. * Parses a JSON object correponding to the serialize function.
  42950. */
  42951. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42952. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42953. };
  42954. __decorate([
  42955. BABYLON.serializeAsColor3("diffuse"),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42957. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42958. __decorate([
  42959. BABYLON.serializeAsTexture(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42961. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42962. __decorate([
  42963. BABYLON.serializeAsColor3("specular"),
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42965. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42966. __decorate([
  42967. BABYLON.serialize(),
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42969. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42970. __decorate([
  42971. BABYLON.serializeAsTexture(),
  42972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42973. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42974. return PBRSpecularGlossinessMaterial;
  42975. }(BABYLON.PBRBaseSimpleMaterial));
  42976. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42977. })(BABYLON || (BABYLON = {}));
  42978. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42979. var BABYLON;
  42980. (function (BABYLON) {
  42981. BABYLON.CameraInputTypes = {};
  42982. var CameraInputsManager = /** @class */ (function () {
  42983. function CameraInputsManager(camera) {
  42984. this.attached = {};
  42985. this.camera = camera;
  42986. this.checkInputs = function () { };
  42987. }
  42988. /**
  42989. * Add an input method to a camera.
  42990. * builtin inputs example: camera.inputs.addGamepad();
  42991. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42992. * @param input camera input method
  42993. */
  42994. CameraInputsManager.prototype.add = function (input) {
  42995. var type = input.getSimpleName();
  42996. if (this.attached[type]) {
  42997. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42998. return;
  42999. }
  43000. this.attached[type] = input;
  43001. input.camera = this.camera;
  43002. //for checkInputs, we are dynamically creating a function
  43003. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43004. if (input.checkInputs) {
  43005. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43006. }
  43007. if (this.attachedElement) {
  43008. input.attachControl(this.attachedElement);
  43009. }
  43010. };
  43011. /**
  43012. * Remove a specific input method from a camera
  43013. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43014. * @param inputToRemove camera input method
  43015. */
  43016. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43017. for (var cam in this.attached) {
  43018. var input = this.attached[cam];
  43019. if (input === inputToRemove) {
  43020. input.detachControl(this.attachedElement);
  43021. input.camera = null;
  43022. delete this.attached[cam];
  43023. this.rebuildInputCheck();
  43024. }
  43025. }
  43026. };
  43027. CameraInputsManager.prototype.removeByType = function (inputType) {
  43028. for (var cam in this.attached) {
  43029. var input = this.attached[cam];
  43030. if (input.getClassName() === inputType) {
  43031. input.detachControl(this.attachedElement);
  43032. input.camera = null;
  43033. delete this.attached[cam];
  43034. this.rebuildInputCheck();
  43035. }
  43036. }
  43037. };
  43038. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43039. var current = this.checkInputs;
  43040. return function () {
  43041. current();
  43042. fn();
  43043. };
  43044. };
  43045. CameraInputsManager.prototype.attachInput = function (input) {
  43046. if (this.attachedElement) {
  43047. input.attachControl(this.attachedElement, this.noPreventDefault);
  43048. }
  43049. };
  43050. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43051. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43052. if (this.attachedElement) {
  43053. return;
  43054. }
  43055. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43056. this.attachedElement = element;
  43057. this.noPreventDefault = noPreventDefault;
  43058. for (var cam in this.attached) {
  43059. this.attached[cam].attachControl(element, noPreventDefault);
  43060. }
  43061. };
  43062. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43063. if (disconnect === void 0) { disconnect = false; }
  43064. if (this.attachedElement !== element) {
  43065. return;
  43066. }
  43067. for (var cam in this.attached) {
  43068. this.attached[cam].detachControl(element);
  43069. if (disconnect) {
  43070. this.attached[cam].camera = null;
  43071. }
  43072. }
  43073. this.attachedElement = null;
  43074. };
  43075. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43076. this.checkInputs = function () { };
  43077. for (var cam in this.attached) {
  43078. var input = this.attached[cam];
  43079. if (input.checkInputs) {
  43080. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43081. }
  43082. }
  43083. };
  43084. /**
  43085. * Remove all attached input methods from a camera
  43086. */
  43087. CameraInputsManager.prototype.clear = function () {
  43088. if (this.attachedElement) {
  43089. this.detachElement(this.attachedElement, true);
  43090. }
  43091. this.attached = {};
  43092. this.attachedElement = null;
  43093. this.checkInputs = function () { };
  43094. };
  43095. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43096. var inputs = {};
  43097. for (var cam in this.attached) {
  43098. var input = this.attached[cam];
  43099. var res = BABYLON.SerializationHelper.Serialize(input);
  43100. inputs[input.getClassName()] = res;
  43101. }
  43102. serializedCamera.inputsmgr = inputs;
  43103. };
  43104. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43105. var parsedInputs = parsedCamera.inputsmgr;
  43106. if (parsedInputs) {
  43107. this.clear();
  43108. for (var n in parsedInputs) {
  43109. var construct = BABYLON.CameraInputTypes[n];
  43110. if (construct) {
  43111. var parsedinput = parsedInputs[n];
  43112. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43113. this.add(input);
  43114. }
  43115. }
  43116. }
  43117. else {
  43118. //2016-03-08 this part is for managing backward compatibility
  43119. for (var n in this.attached) {
  43120. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43121. if (construct) {
  43122. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43123. this.remove(this.attached[n]);
  43124. this.add(input);
  43125. }
  43126. }
  43127. }
  43128. };
  43129. return CameraInputsManager;
  43130. }());
  43131. BABYLON.CameraInputsManager = CameraInputsManager;
  43132. })(BABYLON || (BABYLON = {}));
  43133. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43134. var BABYLON;
  43135. (function (BABYLON) {
  43136. var TargetCamera = /** @class */ (function (_super) {
  43137. __extends(TargetCamera, _super);
  43138. function TargetCamera(name, position, scene) {
  43139. var _this = _super.call(this, name, position, scene) || this;
  43140. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43141. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43142. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43143. _this.speed = 2.0;
  43144. _this.noRotationConstraint = false;
  43145. _this.lockedTarget = null;
  43146. _this._currentTarget = BABYLON.Vector3.Zero();
  43147. _this._viewMatrix = BABYLON.Matrix.Zero();
  43148. _this._camMatrix = BABYLON.Matrix.Zero();
  43149. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43150. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43151. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43152. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43153. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43154. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43155. _this._tempMatrix = BABYLON.Matrix.Zero();
  43156. return _this;
  43157. }
  43158. TargetCamera.prototype.getFrontPosition = function (distance) {
  43159. this.getWorldMatrix();
  43160. var direction = this.getTarget().subtract(this.position);
  43161. direction.normalize();
  43162. direction.scaleInPlace(distance);
  43163. return this.globalPosition.add(direction);
  43164. };
  43165. TargetCamera.prototype._getLockedTargetPosition = function () {
  43166. if (!this.lockedTarget) {
  43167. return null;
  43168. }
  43169. if (this.lockedTarget.absolutePosition) {
  43170. this.lockedTarget.computeWorldMatrix();
  43171. }
  43172. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43173. };
  43174. TargetCamera.prototype.storeState = function () {
  43175. this._storedPosition = this.position.clone();
  43176. this._storedRotation = this.rotation.clone();
  43177. if (this.rotationQuaternion) {
  43178. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43179. }
  43180. return _super.prototype.storeState.call(this);
  43181. };
  43182. /**
  43183. * Restored camera state. You must call storeState() first
  43184. */
  43185. TargetCamera.prototype._restoreStateValues = function () {
  43186. if (!_super.prototype._restoreStateValues.call(this)) {
  43187. return false;
  43188. }
  43189. this.position = this._storedPosition.clone();
  43190. this.rotation = this._storedRotation.clone();
  43191. if (this.rotationQuaternion) {
  43192. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43193. }
  43194. this.cameraDirection.copyFromFloats(0, 0, 0);
  43195. this.cameraRotation.copyFromFloats(0, 0);
  43196. return true;
  43197. };
  43198. // Cache
  43199. TargetCamera.prototype._initCache = function () {
  43200. _super.prototype._initCache.call(this);
  43201. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43202. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43203. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43204. };
  43205. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43206. if (!ignoreParentClass) {
  43207. _super.prototype._updateCache.call(this);
  43208. }
  43209. var lockedTargetPosition = this._getLockedTargetPosition();
  43210. if (!lockedTargetPosition) {
  43211. this._cache.lockedTarget = null;
  43212. }
  43213. else {
  43214. if (!this._cache.lockedTarget) {
  43215. this._cache.lockedTarget = lockedTargetPosition.clone();
  43216. }
  43217. else {
  43218. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43219. }
  43220. }
  43221. this._cache.rotation.copyFrom(this.rotation);
  43222. if (this.rotationQuaternion)
  43223. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43224. };
  43225. // Synchronized
  43226. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43227. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43228. return false;
  43229. }
  43230. var lockedTargetPosition = this._getLockedTargetPosition();
  43231. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43232. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43233. };
  43234. // Methods
  43235. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43236. var engine = this.getEngine();
  43237. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43238. };
  43239. // Target
  43240. TargetCamera.prototype.setTarget = function (target) {
  43241. this.upVector.normalize();
  43242. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43243. this._camMatrix.invert();
  43244. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43245. var vDir = target.subtract(this.position);
  43246. if (vDir.x >= 0.0) {
  43247. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43248. }
  43249. else {
  43250. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43251. }
  43252. this.rotation.z = 0;
  43253. if (isNaN(this.rotation.x)) {
  43254. this.rotation.x = 0;
  43255. }
  43256. if (isNaN(this.rotation.y)) {
  43257. this.rotation.y = 0;
  43258. }
  43259. if (isNaN(this.rotation.z)) {
  43260. this.rotation.z = 0;
  43261. }
  43262. if (this.rotationQuaternion) {
  43263. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43264. }
  43265. };
  43266. /**
  43267. * Return the current target position of the camera. This value is expressed in local space.
  43268. */
  43269. TargetCamera.prototype.getTarget = function () {
  43270. return this._currentTarget;
  43271. };
  43272. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43273. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43274. };
  43275. TargetCamera.prototype._updatePosition = function () {
  43276. if (this.parent) {
  43277. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43278. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43279. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43280. return;
  43281. }
  43282. this.position.addInPlace(this.cameraDirection);
  43283. };
  43284. TargetCamera.prototype._checkInputs = function () {
  43285. var needToMove = this._decideIfNeedsToMove();
  43286. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43287. // Move
  43288. if (needToMove) {
  43289. this._updatePosition();
  43290. }
  43291. // Rotate
  43292. if (needToRotate) {
  43293. this.rotation.x += this.cameraRotation.x;
  43294. this.rotation.y += this.cameraRotation.y;
  43295. //rotate, if quaternion is set and rotation was used
  43296. if (this.rotationQuaternion) {
  43297. var len = this.rotation.lengthSquared();
  43298. if (len) {
  43299. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43300. }
  43301. }
  43302. if (!this.noRotationConstraint) {
  43303. var limit = (Math.PI / 2) * 0.95;
  43304. if (this.rotation.x > limit)
  43305. this.rotation.x = limit;
  43306. if (this.rotation.x < -limit)
  43307. this.rotation.x = -limit;
  43308. }
  43309. }
  43310. // Inertia
  43311. if (needToMove) {
  43312. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43313. this.cameraDirection.x = 0;
  43314. }
  43315. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43316. this.cameraDirection.y = 0;
  43317. }
  43318. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43319. this.cameraDirection.z = 0;
  43320. }
  43321. this.cameraDirection.scaleInPlace(this.inertia);
  43322. }
  43323. if (needToRotate) {
  43324. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43325. this.cameraRotation.x = 0;
  43326. }
  43327. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43328. this.cameraRotation.y = 0;
  43329. }
  43330. this.cameraRotation.scaleInPlace(this.inertia);
  43331. }
  43332. _super.prototype._checkInputs.call(this);
  43333. };
  43334. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43335. if (this.rotationQuaternion) {
  43336. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43337. }
  43338. else {
  43339. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43340. }
  43341. //update the up vector!
  43342. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43343. };
  43344. TargetCamera.prototype._getViewMatrix = function () {
  43345. if (this.lockedTarget) {
  43346. this.setTarget(this._getLockedTargetPosition());
  43347. }
  43348. // Compute
  43349. this._updateCameraRotationMatrix();
  43350. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43351. // Computing target and final matrix
  43352. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43353. if (this.getScene().useRightHandedSystem) {
  43354. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43355. }
  43356. else {
  43357. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43358. }
  43359. return this._viewMatrix;
  43360. };
  43361. /**
  43362. * @override
  43363. * Override Camera.createRigCamera
  43364. */
  43365. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43366. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43367. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43368. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43369. if (!this.rotationQuaternion) {
  43370. this.rotationQuaternion = new BABYLON.Quaternion();
  43371. }
  43372. rigCamera._cameraRigParams = {};
  43373. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43374. }
  43375. return rigCamera;
  43376. }
  43377. return null;
  43378. };
  43379. /**
  43380. * @override
  43381. * Override Camera._updateRigCameras
  43382. */
  43383. TargetCamera.prototype._updateRigCameras = function () {
  43384. var camLeft = this._rigCameras[0];
  43385. var camRight = this._rigCameras[1];
  43386. switch (this.cameraRigMode) {
  43387. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43388. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43389. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43390. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43391. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43392. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43393. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43394. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43395. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43396. camLeft.setTarget(this.getTarget());
  43397. camRight.setTarget(this.getTarget());
  43398. break;
  43399. case BABYLON.Camera.RIG_MODE_VR:
  43400. if (camLeft.rotationQuaternion) {
  43401. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43402. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43403. }
  43404. else {
  43405. camLeft.rotation.copyFrom(this.rotation);
  43406. camRight.rotation.copyFrom(this.rotation);
  43407. }
  43408. camLeft.position.copyFrom(this.position);
  43409. camRight.position.copyFrom(this.position);
  43410. break;
  43411. }
  43412. _super.prototype._updateRigCameras.call(this);
  43413. };
  43414. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43415. if (!this._rigCamTransformMatrix) {
  43416. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43417. }
  43418. var target = this.getTarget();
  43419. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43420. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43421. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43422. };
  43423. TargetCamera.prototype.getClassName = function () {
  43424. return "TargetCamera";
  43425. };
  43426. __decorate([
  43427. BABYLON.serializeAsVector3()
  43428. ], TargetCamera.prototype, "rotation", void 0);
  43429. __decorate([
  43430. BABYLON.serialize()
  43431. ], TargetCamera.prototype, "speed", void 0);
  43432. __decorate([
  43433. BABYLON.serializeAsMeshReference("lockedTargetId")
  43434. ], TargetCamera.prototype, "lockedTarget", void 0);
  43435. return TargetCamera;
  43436. }(BABYLON.Camera));
  43437. BABYLON.TargetCamera = TargetCamera;
  43438. })(BABYLON || (BABYLON = {}));
  43439. //# sourceMappingURL=babylon.targetCamera.js.map
  43440. var BABYLON;
  43441. (function (BABYLON) {
  43442. var FreeCameraMouseInput = /** @class */ (function () {
  43443. function FreeCameraMouseInput(touchEnabled) {
  43444. if (touchEnabled === void 0) { touchEnabled = true; }
  43445. this.touchEnabled = touchEnabled;
  43446. this.buttons = [0, 1, 2];
  43447. this.angularSensibility = 2000.0;
  43448. this.previousPosition = null;
  43449. }
  43450. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43451. var _this = this;
  43452. var engine = this.camera.getEngine();
  43453. if (!this._pointerInput) {
  43454. this._pointerInput = function (p, s) {
  43455. var evt = p.event;
  43456. if (engine.isInVRExclusivePointerMode) {
  43457. return;
  43458. }
  43459. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43460. return;
  43461. }
  43462. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43463. return;
  43464. }
  43465. var srcElement = (evt.srcElement || evt.target);
  43466. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43467. try {
  43468. srcElement.setPointerCapture(evt.pointerId);
  43469. }
  43470. catch (e) {
  43471. //Nothing to do with the error. Execution will continue.
  43472. }
  43473. _this.previousPosition = {
  43474. x: evt.clientX,
  43475. y: evt.clientY
  43476. };
  43477. if (!noPreventDefault) {
  43478. evt.preventDefault();
  43479. element.focus();
  43480. }
  43481. }
  43482. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43483. try {
  43484. srcElement.releasePointerCapture(evt.pointerId);
  43485. }
  43486. catch (e) {
  43487. //Nothing to do with the error.
  43488. }
  43489. _this.previousPosition = null;
  43490. if (!noPreventDefault) {
  43491. evt.preventDefault();
  43492. }
  43493. }
  43494. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43495. if (!_this.previousPosition || engine.isPointerLock) {
  43496. return;
  43497. }
  43498. var offsetX = evt.clientX - _this.previousPosition.x;
  43499. var offsetY = evt.clientY - _this.previousPosition.y;
  43500. if (_this.camera.getScene().useRightHandedSystem) {
  43501. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43502. }
  43503. else {
  43504. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43505. }
  43506. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43507. _this.previousPosition = {
  43508. x: evt.clientX,
  43509. y: evt.clientY
  43510. };
  43511. if (!noPreventDefault) {
  43512. evt.preventDefault();
  43513. }
  43514. }
  43515. };
  43516. }
  43517. this._onMouseMove = function (evt) {
  43518. if (!engine.isPointerLock) {
  43519. return;
  43520. }
  43521. if (engine.isInVRExclusivePointerMode) {
  43522. return;
  43523. }
  43524. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43525. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43526. if (_this.camera.getScene().useRightHandedSystem) {
  43527. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43528. }
  43529. else {
  43530. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43531. }
  43532. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43533. _this.previousPosition = null;
  43534. if (!noPreventDefault) {
  43535. evt.preventDefault();
  43536. }
  43537. };
  43538. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43539. element.addEventListener("mousemove", this._onMouseMove, false);
  43540. };
  43541. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43542. if (this._observer && element) {
  43543. this.camera.getScene().onPointerObservable.remove(this._observer);
  43544. if (this._onMouseMove) {
  43545. element.removeEventListener("mousemove", this._onMouseMove);
  43546. }
  43547. this._observer = null;
  43548. this._onMouseMove = null;
  43549. this.previousPosition = null;
  43550. }
  43551. };
  43552. FreeCameraMouseInput.prototype.getClassName = function () {
  43553. return "FreeCameraMouseInput";
  43554. };
  43555. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43556. return "mouse";
  43557. };
  43558. __decorate([
  43559. BABYLON.serialize()
  43560. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43561. __decorate([
  43562. BABYLON.serialize()
  43563. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43564. return FreeCameraMouseInput;
  43565. }());
  43566. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43567. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43568. })(BABYLON || (BABYLON = {}));
  43569. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43570. var BABYLON;
  43571. (function (BABYLON) {
  43572. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43573. function FreeCameraKeyboardMoveInput() {
  43574. this._keys = new Array();
  43575. this.keysUp = [38];
  43576. this.keysDown = [40];
  43577. this.keysLeft = [37];
  43578. this.keysRight = [39];
  43579. }
  43580. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43581. var _this = this;
  43582. if (this._onCanvasBlurObserver) {
  43583. return;
  43584. }
  43585. this._scene = this.camera.getScene();
  43586. this._engine = this._scene.getEngine();
  43587. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43588. _this._keys = [];
  43589. });
  43590. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43591. var evt = info.event;
  43592. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43593. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43594. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43595. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43596. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43597. var index = _this._keys.indexOf(evt.keyCode);
  43598. if (index === -1) {
  43599. _this._keys.push(evt.keyCode);
  43600. }
  43601. if (!noPreventDefault) {
  43602. evt.preventDefault();
  43603. }
  43604. }
  43605. }
  43606. else {
  43607. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43608. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43609. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43610. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43611. var index = _this._keys.indexOf(evt.keyCode);
  43612. if (index >= 0) {
  43613. _this._keys.splice(index, 1);
  43614. }
  43615. if (!noPreventDefault) {
  43616. evt.preventDefault();
  43617. }
  43618. }
  43619. }
  43620. });
  43621. };
  43622. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43623. if (this._scene) {
  43624. if (this._onKeyboardObserver) {
  43625. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43626. }
  43627. if (this._onCanvasBlurObserver) {
  43628. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43629. }
  43630. this._onKeyboardObserver = null;
  43631. this._onCanvasBlurObserver = null;
  43632. }
  43633. this._keys = [];
  43634. };
  43635. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43636. if (this._onKeyboardObserver) {
  43637. var camera = this.camera;
  43638. // Keyboard
  43639. for (var index = 0; index < this._keys.length; index++) {
  43640. var keyCode = this._keys[index];
  43641. var speed = camera._computeLocalCameraSpeed();
  43642. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43643. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43644. }
  43645. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43646. camera._localDirection.copyFromFloats(0, 0, speed);
  43647. }
  43648. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43649. camera._localDirection.copyFromFloats(speed, 0, 0);
  43650. }
  43651. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43652. camera._localDirection.copyFromFloats(0, 0, -speed);
  43653. }
  43654. if (camera.getScene().useRightHandedSystem) {
  43655. camera._localDirection.z *= -1;
  43656. }
  43657. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43658. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43659. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43660. }
  43661. }
  43662. };
  43663. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43664. return "FreeCameraKeyboardMoveInput";
  43665. };
  43666. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43667. this._keys = [];
  43668. };
  43669. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43670. return "keyboard";
  43671. };
  43672. __decorate([
  43673. BABYLON.serialize()
  43674. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43675. __decorate([
  43676. BABYLON.serialize()
  43677. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43678. __decorate([
  43679. BABYLON.serialize()
  43680. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43681. __decorate([
  43682. BABYLON.serialize()
  43683. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43684. return FreeCameraKeyboardMoveInput;
  43685. }());
  43686. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43687. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43688. })(BABYLON || (BABYLON = {}));
  43689. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43690. var BABYLON;
  43691. (function (BABYLON) {
  43692. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43693. __extends(FreeCameraInputsManager, _super);
  43694. function FreeCameraInputsManager(camera) {
  43695. return _super.call(this, camera) || this;
  43696. }
  43697. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43698. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43699. return this;
  43700. };
  43701. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43702. if (touchEnabled === void 0) { touchEnabled = true; }
  43703. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43704. return this;
  43705. };
  43706. FreeCameraInputsManager.prototype.addGamepad = function () {
  43707. this.add(new BABYLON.FreeCameraGamepadInput());
  43708. return this;
  43709. };
  43710. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43711. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43712. return this;
  43713. };
  43714. FreeCameraInputsManager.prototype.addTouch = function () {
  43715. this.add(new BABYLON.FreeCameraTouchInput());
  43716. return this;
  43717. };
  43718. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43719. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43720. return this;
  43721. };
  43722. return FreeCameraInputsManager;
  43723. }(BABYLON.CameraInputsManager));
  43724. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43725. })(BABYLON || (BABYLON = {}));
  43726. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43727. var BABYLON;
  43728. (function (BABYLON) {
  43729. var FreeCamera = /** @class */ (function (_super) {
  43730. __extends(FreeCamera, _super);
  43731. function FreeCamera(name, position, scene) {
  43732. var _this = _super.call(this, name, position, scene) || this;
  43733. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43734. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43735. _this.checkCollisions = false;
  43736. _this.applyGravity = false;
  43737. _this._needMoveForGravity = false;
  43738. _this._oldPosition = BABYLON.Vector3.Zero();
  43739. _this._diffPosition = BABYLON.Vector3.Zero();
  43740. _this._newPosition = BABYLON.Vector3.Zero();
  43741. // Collisions
  43742. _this._collisionMask = -1;
  43743. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43744. if (collidedMesh === void 0) { collidedMesh = null; }
  43745. //TODO move this to the collision coordinator!
  43746. if (_this.getScene().workerCollisions)
  43747. newPosition.multiplyInPlace(_this._collider._radius);
  43748. var updatePosition = function (newPos) {
  43749. _this._newPosition.copyFrom(newPos);
  43750. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43751. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43752. _this.position.addInPlace(_this._diffPosition);
  43753. if (_this.onCollide && collidedMesh) {
  43754. _this.onCollide(collidedMesh);
  43755. }
  43756. }
  43757. };
  43758. updatePosition(newPosition);
  43759. };
  43760. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43761. _this.inputs.addKeyboard().addMouse();
  43762. return _this;
  43763. }
  43764. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43765. //-- begin properties for backward compatibility for inputs
  43766. /**
  43767. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43768. * Higher values reduce sensitivity.
  43769. */
  43770. get: function () {
  43771. var mouse = this.inputs.attached["mouse"];
  43772. if (mouse)
  43773. return mouse.angularSensibility;
  43774. return 0;
  43775. },
  43776. /**
  43777. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43778. * Higher values reduce sensitivity.
  43779. */
  43780. set: function (value) {
  43781. var mouse = this.inputs.attached["mouse"];
  43782. if (mouse)
  43783. mouse.angularSensibility = value;
  43784. },
  43785. enumerable: true,
  43786. configurable: true
  43787. });
  43788. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43789. get: function () {
  43790. var keyboard = this.inputs.attached["keyboard"];
  43791. if (keyboard)
  43792. return keyboard.keysUp;
  43793. return [];
  43794. },
  43795. set: function (value) {
  43796. var keyboard = this.inputs.attached["keyboard"];
  43797. if (keyboard)
  43798. keyboard.keysUp = value;
  43799. },
  43800. enumerable: true,
  43801. configurable: true
  43802. });
  43803. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43804. get: function () {
  43805. var keyboard = this.inputs.attached["keyboard"];
  43806. if (keyboard)
  43807. return keyboard.keysDown;
  43808. return [];
  43809. },
  43810. set: function (value) {
  43811. var keyboard = this.inputs.attached["keyboard"];
  43812. if (keyboard)
  43813. keyboard.keysDown = value;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43819. get: function () {
  43820. var keyboard = this.inputs.attached["keyboard"];
  43821. if (keyboard)
  43822. return keyboard.keysLeft;
  43823. return [];
  43824. },
  43825. set: function (value) {
  43826. var keyboard = this.inputs.attached["keyboard"];
  43827. if (keyboard)
  43828. keyboard.keysLeft = value;
  43829. },
  43830. enumerable: true,
  43831. configurable: true
  43832. });
  43833. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43834. get: function () {
  43835. var keyboard = this.inputs.attached["keyboard"];
  43836. if (keyboard)
  43837. return keyboard.keysRight;
  43838. return [];
  43839. },
  43840. set: function (value) {
  43841. var keyboard = this.inputs.attached["keyboard"];
  43842. if (keyboard)
  43843. keyboard.keysRight = value;
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. // Controls
  43849. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43850. this.inputs.attachElement(element, noPreventDefault);
  43851. };
  43852. FreeCamera.prototype.detachControl = function (element) {
  43853. this.inputs.detachElement(element);
  43854. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43855. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43856. };
  43857. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43858. get: function () {
  43859. return this._collisionMask;
  43860. },
  43861. set: function (mask) {
  43862. this._collisionMask = !isNaN(mask) ? mask : -1;
  43863. },
  43864. enumerable: true,
  43865. configurable: true
  43866. });
  43867. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43868. var globalPosition;
  43869. if (this.parent) {
  43870. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43871. }
  43872. else {
  43873. globalPosition = this.position;
  43874. }
  43875. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43876. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43877. if (!this._collider) {
  43878. this._collider = new BABYLON.Collider();
  43879. }
  43880. this._collider._radius = this.ellipsoid;
  43881. this._collider.collisionMask = this._collisionMask;
  43882. //no need for clone, as long as gravity is not on.
  43883. var actualDisplacement = displacement;
  43884. //add gravity to the direction to prevent the dual-collision checking
  43885. if (this.applyGravity) {
  43886. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43887. actualDisplacement = displacement.add(this.getScene().gravity);
  43888. }
  43889. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43890. };
  43891. FreeCamera.prototype._checkInputs = function () {
  43892. if (!this._localDirection) {
  43893. this._localDirection = BABYLON.Vector3.Zero();
  43894. this._transformedDirection = BABYLON.Vector3.Zero();
  43895. }
  43896. this.inputs.checkInputs();
  43897. _super.prototype._checkInputs.call(this);
  43898. };
  43899. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43900. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43901. };
  43902. FreeCamera.prototype._updatePosition = function () {
  43903. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43904. this._collideWithWorld(this.cameraDirection);
  43905. }
  43906. else {
  43907. _super.prototype._updatePosition.call(this);
  43908. }
  43909. };
  43910. FreeCamera.prototype.dispose = function () {
  43911. this.inputs.clear();
  43912. _super.prototype.dispose.call(this);
  43913. };
  43914. FreeCamera.prototype.getClassName = function () {
  43915. return "FreeCamera";
  43916. };
  43917. __decorate([
  43918. BABYLON.serializeAsVector3()
  43919. ], FreeCamera.prototype, "ellipsoid", void 0);
  43920. __decorate([
  43921. BABYLON.serializeAsVector3()
  43922. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43923. __decorate([
  43924. BABYLON.serialize()
  43925. ], FreeCamera.prototype, "checkCollisions", void 0);
  43926. __decorate([
  43927. BABYLON.serialize()
  43928. ], FreeCamera.prototype, "applyGravity", void 0);
  43929. return FreeCamera;
  43930. }(BABYLON.TargetCamera));
  43931. BABYLON.FreeCamera = FreeCamera;
  43932. })(BABYLON || (BABYLON = {}));
  43933. //# sourceMappingURL=babylon.freeCamera.js.map
  43934. var BABYLON;
  43935. (function (BABYLON) {
  43936. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43937. function ArcRotateCameraKeyboardMoveInput() {
  43938. this._keys = new Array();
  43939. this.keysUp = [38];
  43940. this.keysDown = [40];
  43941. this.keysLeft = [37];
  43942. this.keysRight = [39];
  43943. this.keysReset = [220];
  43944. this.panningSensibility = 50.0;
  43945. this.zoomingSensibility = 25.0;
  43946. this.useAltToZoom = true;
  43947. }
  43948. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43949. var _this = this;
  43950. if (this._onCanvasBlurObserver) {
  43951. return;
  43952. }
  43953. this._scene = this.camera.getScene();
  43954. this._engine = this._scene.getEngine();
  43955. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43956. _this._keys = [];
  43957. });
  43958. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43959. var evt = info.event;
  43960. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43961. _this._ctrlPressed = evt.ctrlKey;
  43962. _this._altPressed = evt.altKey;
  43963. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43964. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43965. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43966. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43967. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43968. var index = _this._keys.indexOf(evt.keyCode);
  43969. if (index === -1) {
  43970. _this._keys.push(evt.keyCode);
  43971. }
  43972. if (evt.preventDefault) {
  43973. if (!noPreventDefault) {
  43974. evt.preventDefault();
  43975. }
  43976. }
  43977. }
  43978. }
  43979. else {
  43980. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43981. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43982. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43983. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43984. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43985. var index = _this._keys.indexOf(evt.keyCode);
  43986. if (index >= 0) {
  43987. _this._keys.splice(index, 1);
  43988. }
  43989. if (evt.preventDefault) {
  43990. if (!noPreventDefault) {
  43991. evt.preventDefault();
  43992. }
  43993. }
  43994. }
  43995. }
  43996. });
  43997. };
  43998. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43999. if (this._scene) {
  44000. if (this._onKeyboardObserver) {
  44001. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44002. }
  44003. if (this._onCanvasBlurObserver) {
  44004. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44005. }
  44006. this._onKeyboardObserver = null;
  44007. this._onCanvasBlurObserver = null;
  44008. }
  44009. this._keys = [];
  44010. };
  44011. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44012. if (this._onKeyboardObserver) {
  44013. var camera = this.camera;
  44014. for (var index = 0; index < this._keys.length; index++) {
  44015. var keyCode = this._keys[index];
  44016. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44017. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44018. camera.inertialPanningX -= 1 / this.panningSensibility;
  44019. }
  44020. else {
  44021. camera.inertialAlphaOffset -= 0.01;
  44022. }
  44023. }
  44024. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44025. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44026. camera.inertialPanningY += 1 / this.panningSensibility;
  44027. }
  44028. else if (this._altPressed && this.useAltToZoom) {
  44029. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44030. }
  44031. else {
  44032. camera.inertialBetaOffset -= 0.01;
  44033. }
  44034. }
  44035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44036. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44037. camera.inertialPanningX += 1 / this.panningSensibility;
  44038. }
  44039. else {
  44040. camera.inertialAlphaOffset += 0.01;
  44041. }
  44042. }
  44043. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44044. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44045. camera.inertialPanningY -= 1 / this.panningSensibility;
  44046. }
  44047. else if (this._altPressed && this.useAltToZoom) {
  44048. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44049. }
  44050. else {
  44051. camera.inertialBetaOffset += 0.01;
  44052. }
  44053. }
  44054. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44055. camera.restoreState();
  44056. }
  44057. }
  44058. }
  44059. };
  44060. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44061. return "ArcRotateCameraKeyboardMoveInput";
  44062. };
  44063. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44064. return "keyboard";
  44065. };
  44066. __decorate([
  44067. BABYLON.serialize()
  44068. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44069. __decorate([
  44070. BABYLON.serialize()
  44071. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44072. __decorate([
  44073. BABYLON.serialize()
  44074. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44078. __decorate([
  44079. BABYLON.serialize()
  44080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44081. __decorate([
  44082. BABYLON.serialize()
  44083. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44084. __decorate([
  44085. BABYLON.serialize()
  44086. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44087. __decorate([
  44088. BABYLON.serialize()
  44089. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44090. return ArcRotateCameraKeyboardMoveInput;
  44091. }());
  44092. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44093. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44094. })(BABYLON || (BABYLON = {}));
  44095. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44096. var BABYLON;
  44097. (function (BABYLON) {
  44098. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44099. function ArcRotateCameraMouseWheelInput() {
  44100. this.wheelPrecision = 3.0;
  44101. /**
  44102. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44103. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44104. */
  44105. this.wheelDeltaPercentage = 0;
  44106. }
  44107. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44108. var _this = this;
  44109. this._wheel = function (p, s) {
  44110. //sanity check - this should be a PointerWheel event.
  44111. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44112. return;
  44113. var event = p.event;
  44114. var delta = 0;
  44115. if (event.wheelDelta) {
  44116. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44117. }
  44118. else if (event.detail) {
  44119. delta = -event.detail / _this.wheelPrecision;
  44120. }
  44121. if (delta)
  44122. _this.camera.inertialRadiusOffset += delta;
  44123. if (event.preventDefault) {
  44124. if (!noPreventDefault) {
  44125. event.preventDefault();
  44126. }
  44127. }
  44128. };
  44129. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44130. };
  44131. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44132. if (this._observer && element) {
  44133. this.camera.getScene().onPointerObservable.remove(this._observer);
  44134. this._observer = null;
  44135. this._wheel = null;
  44136. }
  44137. };
  44138. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44139. return "ArcRotateCameraMouseWheelInput";
  44140. };
  44141. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44142. return "mousewheel";
  44143. };
  44144. __decorate([
  44145. BABYLON.serialize()
  44146. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44147. __decorate([
  44148. BABYLON.serialize()
  44149. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44150. return ArcRotateCameraMouseWheelInput;
  44151. }());
  44152. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44153. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44154. })(BABYLON || (BABYLON = {}));
  44155. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44156. var BABYLON;
  44157. (function (BABYLON) {
  44158. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44159. function ArcRotateCameraPointersInput() {
  44160. this.buttons = [0, 1, 2];
  44161. this.angularSensibilityX = 1000.0;
  44162. this.angularSensibilityY = 1000.0;
  44163. this.pinchPrecision = 12.0;
  44164. /**
  44165. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44166. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44167. */
  44168. this.pinchDeltaPercentage = 0;
  44169. this.panningSensibility = 1000.0;
  44170. this.multiTouchPanning = true;
  44171. this.multiTouchPanAndZoom = true;
  44172. this._isPanClick = false;
  44173. this.pinchInwards = true;
  44174. }
  44175. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44176. var _this = this;
  44177. var engine = this.camera.getEngine();
  44178. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44179. var pointA = null;
  44180. var pointB = null;
  44181. var previousPinchSquaredDistance = 0;
  44182. var initialDistance = 0;
  44183. var twoFingerActivityCount = 0;
  44184. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44185. this._pointerInput = function (p, s) {
  44186. var evt = p.event;
  44187. var isTouch = p.event.pointerType === "touch";
  44188. if (engine.isInVRExclusivePointerMode) {
  44189. return;
  44190. }
  44191. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44192. return;
  44193. }
  44194. var srcElement = (evt.srcElement || evt.target);
  44195. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44196. try {
  44197. srcElement.setPointerCapture(evt.pointerId);
  44198. }
  44199. catch (e) {
  44200. //Nothing to do with the error. Execution will continue.
  44201. }
  44202. // Manage panning with pan button click
  44203. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44204. // manage pointers
  44205. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44206. if (pointA === null) {
  44207. pointA = cacheSoloPointer;
  44208. }
  44209. else if (pointB === null) {
  44210. pointB = cacheSoloPointer;
  44211. }
  44212. if (!noPreventDefault) {
  44213. evt.preventDefault();
  44214. element.focus();
  44215. }
  44216. }
  44217. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44218. _this.camera.restoreState();
  44219. }
  44220. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44221. try {
  44222. srcElement.releasePointerCapture(evt.pointerId);
  44223. }
  44224. catch (e) {
  44225. //Nothing to do with the error.
  44226. }
  44227. cacheSoloPointer = null;
  44228. previousPinchSquaredDistance = 0;
  44229. previousMultiTouchPanPosition.isPaning = false;
  44230. previousMultiTouchPanPosition.isPinching = false;
  44231. twoFingerActivityCount = 0;
  44232. initialDistance = 0;
  44233. if (!isTouch) {
  44234. pointB = null; // Mouse and pen are mono pointer
  44235. }
  44236. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44237. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44238. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44239. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44240. if (engine.badOS) {
  44241. pointA = pointB = null;
  44242. }
  44243. else {
  44244. //only remove the impacted pointer in case of multitouch allowing on most
  44245. //platforms switching from rotate to zoom and pan seamlessly.
  44246. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44247. pointA = pointB;
  44248. pointB = null;
  44249. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44250. }
  44251. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44252. pointB = null;
  44253. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44254. }
  44255. else {
  44256. pointA = pointB = null;
  44257. }
  44258. }
  44259. if (!noPreventDefault) {
  44260. evt.preventDefault();
  44261. }
  44262. }
  44263. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44264. if (!noPreventDefault) {
  44265. evt.preventDefault();
  44266. }
  44267. // One button down
  44268. if (pointA && pointB === null && cacheSoloPointer) {
  44269. if (_this.panningSensibility !== 0 &&
  44270. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44271. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44272. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44273. }
  44274. else {
  44275. var offsetX = evt.clientX - cacheSoloPointer.x;
  44276. var offsetY = evt.clientY - cacheSoloPointer.y;
  44277. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44278. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44279. }
  44280. cacheSoloPointer.x = evt.clientX;
  44281. cacheSoloPointer.y = evt.clientY;
  44282. }
  44283. else if (pointA && pointB) {
  44284. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44285. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44286. ed.x = evt.clientX;
  44287. ed.y = evt.clientY;
  44288. var direction = _this.pinchInwards ? 1 : -1;
  44289. var distX = pointA.x - pointB.x;
  44290. var distY = pointA.y - pointB.y;
  44291. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44292. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44293. if (previousPinchSquaredDistance === 0) {
  44294. initialDistance = pinchDistance;
  44295. previousPinchSquaredDistance = pinchSquaredDistance;
  44296. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44297. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44298. return;
  44299. }
  44300. if (_this.multiTouchPanAndZoom) {
  44301. if (_this.pinchDeltaPercentage) {
  44302. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44303. }
  44304. else {
  44305. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44306. (_this.pinchPrecision *
  44307. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44308. direction);
  44309. }
  44310. if (_this.panningSensibility !== 0) {
  44311. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44312. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44313. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44314. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44315. previousMultiTouchPanPosition.x = pointersCenterX;
  44316. previousMultiTouchPanPosition.y = pointersCenterY;
  44317. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44318. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44319. }
  44320. }
  44321. else {
  44322. twoFingerActivityCount++;
  44323. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44324. if (_this.pinchDeltaPercentage) {
  44325. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44326. }
  44327. else {
  44328. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44329. (_this.pinchPrecision *
  44330. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44331. direction);
  44332. }
  44333. previousMultiTouchPanPosition.isPaning = false;
  44334. previousMultiTouchPanPosition.isPinching = true;
  44335. }
  44336. else {
  44337. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44338. if (!previousMultiTouchPanPosition.isPaning) {
  44339. previousMultiTouchPanPosition.isPaning = true;
  44340. previousMultiTouchPanPosition.isPinching = false;
  44341. previousMultiTouchPanPosition.x = ed.x;
  44342. previousMultiTouchPanPosition.y = ed.y;
  44343. return;
  44344. }
  44345. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44346. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44347. }
  44348. }
  44349. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44350. previousMultiTouchPanPosition.x = ed.x;
  44351. previousMultiTouchPanPosition.y = ed.y;
  44352. }
  44353. }
  44354. previousPinchSquaredDistance = pinchSquaredDistance;
  44355. }
  44356. }
  44357. };
  44358. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44359. this._onContextMenu = function (evt) {
  44360. evt.preventDefault();
  44361. };
  44362. if (!this.camera._useCtrlForPanning) {
  44363. element.addEventListener("contextmenu", this._onContextMenu, false);
  44364. }
  44365. this._onLostFocus = function () {
  44366. //this._keys = [];
  44367. pointA = pointB = null;
  44368. previousPinchSquaredDistance = 0;
  44369. previousMultiTouchPanPosition.isPaning = false;
  44370. previousMultiTouchPanPosition.isPinching = false;
  44371. twoFingerActivityCount = 0;
  44372. cacheSoloPointer = null;
  44373. initialDistance = 0;
  44374. };
  44375. this._onMouseMove = function (evt) {
  44376. if (!engine.isPointerLock) {
  44377. return;
  44378. }
  44379. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44380. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44381. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44382. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44383. if (!noPreventDefault) {
  44384. evt.preventDefault();
  44385. }
  44386. };
  44387. this._onGestureStart = function (e) {
  44388. if (window.MSGesture === undefined) {
  44389. return;
  44390. }
  44391. if (!_this._MSGestureHandler) {
  44392. _this._MSGestureHandler = new MSGesture();
  44393. _this._MSGestureHandler.target = element;
  44394. }
  44395. _this._MSGestureHandler.addPointer(e.pointerId);
  44396. };
  44397. this._onGesture = function (e) {
  44398. _this.camera.radius *= e.scale;
  44399. if (e.preventDefault) {
  44400. if (!noPreventDefault) {
  44401. e.stopPropagation();
  44402. e.preventDefault();
  44403. }
  44404. }
  44405. };
  44406. element.addEventListener("mousemove", this._onMouseMove, false);
  44407. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44408. element.addEventListener("MSGestureChange", this._onGesture, false);
  44409. BABYLON.Tools.RegisterTopRootEvents([
  44410. { name: "blur", handler: this._onLostFocus }
  44411. ]);
  44412. };
  44413. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44414. if (this._onLostFocus) {
  44415. BABYLON.Tools.UnregisterTopRootEvents([
  44416. { name: "blur", handler: this._onLostFocus }
  44417. ]);
  44418. }
  44419. if (element && this._observer) {
  44420. this.camera.getScene().onPointerObservable.remove(this._observer);
  44421. this._observer = null;
  44422. if (this._onContextMenu) {
  44423. element.removeEventListener("contextmenu", this._onContextMenu);
  44424. }
  44425. if (this._onMouseMove) {
  44426. element.removeEventListener("mousemove", this._onMouseMove);
  44427. }
  44428. if (this._onGestureStart) {
  44429. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44430. }
  44431. if (this._onGesture) {
  44432. element.removeEventListener("MSGestureChange", this._onGesture);
  44433. }
  44434. this._isPanClick = false;
  44435. this.pinchInwards = true;
  44436. this._onMouseMove = null;
  44437. this._onGestureStart = null;
  44438. this._onGesture = null;
  44439. this._MSGestureHandler = null;
  44440. this._onLostFocus = null;
  44441. this._onContextMenu = null;
  44442. }
  44443. };
  44444. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44445. return "ArcRotateCameraPointersInput";
  44446. };
  44447. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44448. return "pointers";
  44449. };
  44450. __decorate([
  44451. BABYLON.serialize()
  44452. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44453. __decorate([
  44454. BABYLON.serialize()
  44455. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44456. __decorate([
  44457. BABYLON.serialize()
  44458. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44459. __decorate([
  44460. BABYLON.serialize()
  44461. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44462. __decorate([
  44463. BABYLON.serialize()
  44464. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44465. __decorate([
  44466. BABYLON.serialize()
  44467. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44468. __decorate([
  44469. BABYLON.serialize()
  44470. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44471. __decorate([
  44472. BABYLON.serialize()
  44473. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44474. return ArcRotateCameraPointersInput;
  44475. }());
  44476. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44477. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44478. })(BABYLON || (BABYLON = {}));
  44479. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44480. var BABYLON;
  44481. (function (BABYLON) {
  44482. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44483. __extends(ArcRotateCameraInputsManager, _super);
  44484. function ArcRotateCameraInputsManager(camera) {
  44485. return _super.call(this, camera) || this;
  44486. }
  44487. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44488. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44489. return this;
  44490. };
  44491. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44492. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44493. return this;
  44494. };
  44495. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44496. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44497. return this;
  44498. };
  44499. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44500. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44501. return this;
  44502. };
  44503. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44504. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44505. return this;
  44506. };
  44507. return ArcRotateCameraInputsManager;
  44508. }(BABYLON.CameraInputsManager));
  44509. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44510. })(BABYLON || (BABYLON = {}));
  44511. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44512. var BABYLON;
  44513. (function (BABYLON) {
  44514. var ArcRotateCamera = /** @class */ (function (_super) {
  44515. __extends(ArcRotateCamera, _super);
  44516. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44517. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44518. _this.inertialAlphaOffset = 0;
  44519. _this.inertialBetaOffset = 0;
  44520. _this.inertialRadiusOffset = 0;
  44521. _this.lowerAlphaLimit = null;
  44522. _this.upperAlphaLimit = null;
  44523. _this.lowerBetaLimit = 0.01;
  44524. _this.upperBetaLimit = Math.PI;
  44525. _this.lowerRadiusLimit = null;
  44526. _this.upperRadiusLimit = null;
  44527. _this.inertialPanningX = 0;
  44528. _this.inertialPanningY = 0;
  44529. _this.pinchToPanMaxDistance = 20;
  44530. _this.panningDistanceLimit = null;
  44531. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44532. _this.panningInertia = 0.9;
  44533. //-- end properties for backward compatibility for inputs
  44534. _this.zoomOnFactor = 1;
  44535. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44536. _this.allowUpsideDown = true;
  44537. _this._viewMatrix = new BABYLON.Matrix();
  44538. // Panning
  44539. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44540. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44541. _this.checkCollisions = false;
  44542. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44543. _this._previousPosition = BABYLON.Vector3.Zero();
  44544. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44545. _this._newPosition = BABYLON.Vector3.Zero();
  44546. _this._computationVector = BABYLON.Vector3.Zero();
  44547. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44548. if (collidedMesh === void 0) { collidedMesh = null; }
  44549. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44550. newPosition.multiplyInPlace(_this._collider._radius);
  44551. }
  44552. if (!collidedMesh) {
  44553. _this._previousPosition.copyFrom(_this.position);
  44554. }
  44555. else {
  44556. _this.setPosition(newPosition);
  44557. if (_this.onCollide) {
  44558. _this.onCollide(collidedMesh);
  44559. }
  44560. }
  44561. // Recompute because of constraints
  44562. var cosa = Math.cos(_this.alpha);
  44563. var sina = Math.sin(_this.alpha);
  44564. var cosb = Math.cos(_this.beta);
  44565. var sinb = Math.sin(_this.beta);
  44566. if (sinb === 0) {
  44567. sinb = 0.0001;
  44568. }
  44569. var target = _this._getTargetPosition();
  44570. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44571. target.addToRef(_this._computationVector, _this._newPosition);
  44572. _this.position.copyFrom(_this._newPosition);
  44573. var up = _this.upVector;
  44574. if (_this.allowUpsideDown && _this.beta < 0) {
  44575. up = up.clone();
  44576. up = up.negate();
  44577. }
  44578. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44579. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44580. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44581. _this._collisionTriggered = false;
  44582. };
  44583. _this._target = BABYLON.Vector3.Zero();
  44584. if (target) {
  44585. _this.setTarget(target);
  44586. }
  44587. _this.alpha = alpha;
  44588. _this.beta = beta;
  44589. _this.radius = radius;
  44590. _this.getViewMatrix();
  44591. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44592. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44593. return _this;
  44594. }
  44595. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44596. get: function () {
  44597. return this._target;
  44598. },
  44599. set: function (value) {
  44600. this.setTarget(value);
  44601. },
  44602. enumerable: true,
  44603. configurable: true
  44604. });
  44605. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44606. //-- begin properties for backward compatibility for inputs
  44607. get: function () {
  44608. var pointers = this.inputs.attached["pointers"];
  44609. if (pointers)
  44610. return pointers.angularSensibilityX;
  44611. return 0;
  44612. },
  44613. set: function (value) {
  44614. var pointers = this.inputs.attached["pointers"];
  44615. if (pointers) {
  44616. pointers.angularSensibilityX = value;
  44617. }
  44618. },
  44619. enumerable: true,
  44620. configurable: true
  44621. });
  44622. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44623. get: function () {
  44624. var pointers = this.inputs.attached["pointers"];
  44625. if (pointers)
  44626. return pointers.angularSensibilityY;
  44627. return 0;
  44628. },
  44629. set: function (value) {
  44630. var pointers = this.inputs.attached["pointers"];
  44631. if (pointers) {
  44632. pointers.angularSensibilityY = value;
  44633. }
  44634. },
  44635. enumerable: true,
  44636. configurable: true
  44637. });
  44638. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44639. get: function () {
  44640. var pointers = this.inputs.attached["pointers"];
  44641. if (pointers)
  44642. return pointers.pinchPrecision;
  44643. return 0;
  44644. },
  44645. set: function (value) {
  44646. var pointers = this.inputs.attached["pointers"];
  44647. if (pointers) {
  44648. pointers.pinchPrecision = value;
  44649. }
  44650. },
  44651. enumerable: true,
  44652. configurable: true
  44653. });
  44654. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44655. get: function () {
  44656. var pointers = this.inputs.attached["pointers"];
  44657. if (pointers)
  44658. return pointers.pinchDeltaPercentage;
  44659. return 0;
  44660. },
  44661. set: function (value) {
  44662. var pointers = this.inputs.attached["pointers"];
  44663. if (pointers) {
  44664. pointers.pinchDeltaPercentage = value;
  44665. }
  44666. },
  44667. enumerable: true,
  44668. configurable: true
  44669. });
  44670. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44671. get: function () {
  44672. var pointers = this.inputs.attached["pointers"];
  44673. if (pointers)
  44674. return pointers.panningSensibility;
  44675. return 0;
  44676. },
  44677. set: function (value) {
  44678. var pointers = this.inputs.attached["pointers"];
  44679. if (pointers) {
  44680. pointers.panningSensibility = value;
  44681. }
  44682. },
  44683. enumerable: true,
  44684. configurable: true
  44685. });
  44686. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44687. get: function () {
  44688. var keyboard = this.inputs.attached["keyboard"];
  44689. if (keyboard)
  44690. return keyboard.keysUp;
  44691. return [];
  44692. },
  44693. set: function (value) {
  44694. var keyboard = this.inputs.attached["keyboard"];
  44695. if (keyboard)
  44696. keyboard.keysUp = value;
  44697. },
  44698. enumerable: true,
  44699. configurable: true
  44700. });
  44701. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44702. get: function () {
  44703. var keyboard = this.inputs.attached["keyboard"];
  44704. if (keyboard)
  44705. return keyboard.keysDown;
  44706. return [];
  44707. },
  44708. set: function (value) {
  44709. var keyboard = this.inputs.attached["keyboard"];
  44710. if (keyboard)
  44711. keyboard.keysDown = value;
  44712. },
  44713. enumerable: true,
  44714. configurable: true
  44715. });
  44716. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44717. get: function () {
  44718. var keyboard = this.inputs.attached["keyboard"];
  44719. if (keyboard)
  44720. return keyboard.keysLeft;
  44721. return [];
  44722. },
  44723. set: function (value) {
  44724. var keyboard = this.inputs.attached["keyboard"];
  44725. if (keyboard)
  44726. keyboard.keysLeft = value;
  44727. },
  44728. enumerable: true,
  44729. configurable: true
  44730. });
  44731. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44732. get: function () {
  44733. var keyboard = this.inputs.attached["keyboard"];
  44734. if (keyboard)
  44735. return keyboard.keysRight;
  44736. return [];
  44737. },
  44738. set: function (value) {
  44739. var keyboard = this.inputs.attached["keyboard"];
  44740. if (keyboard)
  44741. keyboard.keysRight = value;
  44742. },
  44743. enumerable: true,
  44744. configurable: true
  44745. });
  44746. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44747. get: function () {
  44748. var mousewheel = this.inputs.attached["mousewheel"];
  44749. if (mousewheel)
  44750. return mousewheel.wheelPrecision;
  44751. return 0;
  44752. },
  44753. set: function (value) {
  44754. var mousewheel = this.inputs.attached["mousewheel"];
  44755. if (mousewheel)
  44756. mousewheel.wheelPrecision = value;
  44757. },
  44758. enumerable: true,
  44759. configurable: true
  44760. });
  44761. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44762. get: function () {
  44763. var mousewheel = this.inputs.attached["mousewheel"];
  44764. if (mousewheel)
  44765. return mousewheel.wheelDeltaPercentage;
  44766. return 0;
  44767. },
  44768. set: function (value) {
  44769. var mousewheel = this.inputs.attached["mousewheel"];
  44770. if (mousewheel)
  44771. mousewheel.wheelDeltaPercentage = value;
  44772. },
  44773. enumerable: true,
  44774. configurable: true
  44775. });
  44776. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44777. get: function () {
  44778. return this._bouncingBehavior;
  44779. },
  44780. enumerable: true,
  44781. configurable: true
  44782. });
  44783. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44784. get: function () {
  44785. return this._bouncingBehavior != null;
  44786. },
  44787. set: function (value) {
  44788. if (value === this.useBouncingBehavior) {
  44789. return;
  44790. }
  44791. if (value) {
  44792. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44793. this.addBehavior(this._bouncingBehavior);
  44794. }
  44795. else if (this._bouncingBehavior) {
  44796. this.removeBehavior(this._bouncingBehavior);
  44797. this._bouncingBehavior = null;
  44798. }
  44799. },
  44800. enumerable: true,
  44801. configurable: true
  44802. });
  44803. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44804. get: function () {
  44805. return this._framingBehavior;
  44806. },
  44807. enumerable: true,
  44808. configurable: true
  44809. });
  44810. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44811. get: function () {
  44812. return this._framingBehavior != null;
  44813. },
  44814. set: function (value) {
  44815. if (value === this.useFramingBehavior) {
  44816. return;
  44817. }
  44818. if (value) {
  44819. this._framingBehavior = new BABYLON.FramingBehavior();
  44820. this.addBehavior(this._framingBehavior);
  44821. }
  44822. else if (this._framingBehavior) {
  44823. this.removeBehavior(this._framingBehavior);
  44824. this._framingBehavior = null;
  44825. }
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44831. get: function () {
  44832. return this._autoRotationBehavior;
  44833. },
  44834. enumerable: true,
  44835. configurable: true
  44836. });
  44837. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44838. get: function () {
  44839. return this._autoRotationBehavior != null;
  44840. },
  44841. set: function (value) {
  44842. if (value === this.useAutoRotationBehavior) {
  44843. return;
  44844. }
  44845. if (value) {
  44846. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44847. this.addBehavior(this._autoRotationBehavior);
  44848. }
  44849. else if (this._autoRotationBehavior) {
  44850. this.removeBehavior(this._autoRotationBehavior);
  44851. this._autoRotationBehavior = null;
  44852. }
  44853. },
  44854. enumerable: true,
  44855. configurable: true
  44856. });
  44857. // Cache
  44858. ArcRotateCamera.prototype._initCache = function () {
  44859. _super.prototype._initCache.call(this);
  44860. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44861. this._cache.alpha = undefined;
  44862. this._cache.beta = undefined;
  44863. this._cache.radius = undefined;
  44864. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44865. };
  44866. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44867. if (!ignoreParentClass) {
  44868. _super.prototype._updateCache.call(this);
  44869. }
  44870. this._cache._target.copyFrom(this._getTargetPosition());
  44871. this._cache.alpha = this.alpha;
  44872. this._cache.beta = this.beta;
  44873. this._cache.radius = this.radius;
  44874. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44875. };
  44876. ArcRotateCamera.prototype._getTargetPosition = function () {
  44877. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44878. var pos = this._targetHost.getAbsolutePosition();
  44879. if (this._targetBoundingCenter) {
  44880. pos.addToRef(this._targetBoundingCenter, this._target);
  44881. }
  44882. else {
  44883. this._target.copyFrom(pos);
  44884. }
  44885. }
  44886. var lockedTargetPosition = this._getLockedTargetPosition();
  44887. if (lockedTargetPosition) {
  44888. return lockedTargetPosition;
  44889. }
  44890. return this._target;
  44891. };
  44892. ArcRotateCamera.prototype.storeState = function () {
  44893. this._storedAlpha = this.alpha;
  44894. this._storedBeta = this.beta;
  44895. this._storedRadius = this.radius;
  44896. this._storedTarget = this._getTargetPosition().clone();
  44897. return _super.prototype.storeState.call(this);
  44898. };
  44899. /**
  44900. * Restored camera state. You must call storeState() first
  44901. */
  44902. ArcRotateCamera.prototype._restoreStateValues = function () {
  44903. if (!_super.prototype._restoreStateValues.call(this)) {
  44904. return false;
  44905. }
  44906. this.alpha = this._storedAlpha;
  44907. this.beta = this._storedBeta;
  44908. this.radius = this._storedRadius;
  44909. this.setTarget(this._storedTarget.clone());
  44910. this.inertialAlphaOffset = 0;
  44911. this.inertialBetaOffset = 0;
  44912. this.inertialRadiusOffset = 0;
  44913. this.inertialPanningX = 0;
  44914. this.inertialPanningY = 0;
  44915. return true;
  44916. };
  44917. // Synchronized
  44918. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44919. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44920. return false;
  44921. return this._cache._target.equals(this._getTargetPosition())
  44922. && this._cache.alpha === this.alpha
  44923. && this._cache.beta === this.beta
  44924. && this._cache.radius === this.radius
  44925. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44926. };
  44927. // Methods
  44928. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44929. var _this = this;
  44930. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44931. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44932. this._useCtrlForPanning = useCtrlForPanning;
  44933. this._panningMouseButton = panningMouseButton;
  44934. this.inputs.attachElement(element, noPreventDefault);
  44935. this._reset = function () {
  44936. _this.inertialAlphaOffset = 0;
  44937. _this.inertialBetaOffset = 0;
  44938. _this.inertialRadiusOffset = 0;
  44939. _this.inertialPanningX = 0;
  44940. _this.inertialPanningY = 0;
  44941. };
  44942. };
  44943. ArcRotateCamera.prototype.detachControl = function (element) {
  44944. this.inputs.detachElement(element);
  44945. if (this._reset) {
  44946. this._reset();
  44947. }
  44948. };
  44949. ArcRotateCamera.prototype._checkInputs = function () {
  44950. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44951. if (this._collisionTriggered) {
  44952. return;
  44953. }
  44954. this.inputs.checkInputs();
  44955. // Inertia
  44956. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44957. if (this.getScene().useRightHandedSystem) {
  44958. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44959. }
  44960. else {
  44961. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44962. }
  44963. this.beta += this.inertialBetaOffset;
  44964. this.radius -= this.inertialRadiusOffset;
  44965. this.inertialAlphaOffset *= this.inertia;
  44966. this.inertialBetaOffset *= this.inertia;
  44967. this.inertialRadiusOffset *= this.inertia;
  44968. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44969. this.inertialAlphaOffset = 0;
  44970. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44971. this.inertialBetaOffset = 0;
  44972. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44973. this.inertialRadiusOffset = 0;
  44974. }
  44975. // Panning inertia
  44976. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44977. if (!this._localDirection) {
  44978. this._localDirection = BABYLON.Vector3.Zero();
  44979. this._transformedDirection = BABYLON.Vector3.Zero();
  44980. }
  44981. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44982. this._localDirection.multiplyInPlace(this.panningAxis);
  44983. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44984. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44985. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44986. if (!this.panningAxis.y) {
  44987. this._transformedDirection.y = 0;
  44988. }
  44989. if (!this._targetHost) {
  44990. if (this.panningDistanceLimit) {
  44991. this._transformedDirection.addInPlace(this._target);
  44992. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44993. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44994. this._target.copyFrom(this._transformedDirection);
  44995. }
  44996. }
  44997. else {
  44998. this._target.addInPlace(this._transformedDirection);
  44999. }
  45000. }
  45001. this.inertialPanningX *= this.panningInertia;
  45002. this.inertialPanningY *= this.panningInertia;
  45003. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45004. this.inertialPanningX = 0;
  45005. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45006. this.inertialPanningY = 0;
  45007. }
  45008. // Limits
  45009. this._checkLimits();
  45010. _super.prototype._checkInputs.call(this);
  45011. };
  45012. ArcRotateCamera.prototype._checkLimits = function () {
  45013. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45014. if (this.allowUpsideDown && this.beta > Math.PI) {
  45015. this.beta = this.beta - (2 * Math.PI);
  45016. }
  45017. }
  45018. else {
  45019. if (this.beta < this.lowerBetaLimit) {
  45020. this.beta = this.lowerBetaLimit;
  45021. }
  45022. }
  45023. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45024. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45025. this.beta = this.beta + (2 * Math.PI);
  45026. }
  45027. }
  45028. else {
  45029. if (this.beta > this.upperBetaLimit) {
  45030. this.beta = this.upperBetaLimit;
  45031. }
  45032. }
  45033. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45034. this.alpha = this.lowerAlphaLimit;
  45035. }
  45036. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45037. this.alpha = this.upperAlphaLimit;
  45038. }
  45039. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45040. this.radius = this.lowerRadiusLimit;
  45041. }
  45042. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45043. this.radius = this.upperRadiusLimit;
  45044. }
  45045. };
  45046. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45047. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45048. this.radius = this._computationVector.length();
  45049. if (this.radius === 0) {
  45050. this.radius = 0.0001; // Just to avoid division by zero
  45051. }
  45052. // Alpha
  45053. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45054. if (this._computationVector.z < 0) {
  45055. this.alpha = 2 * Math.PI - this.alpha;
  45056. }
  45057. // Beta
  45058. this.beta = Math.acos(this._computationVector.y / this.radius);
  45059. this._checkLimits();
  45060. };
  45061. ArcRotateCamera.prototype.setPosition = function (position) {
  45062. if (this.position.equals(position)) {
  45063. return;
  45064. }
  45065. this.position.copyFrom(position);
  45066. this.rebuildAnglesAndRadius();
  45067. };
  45068. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45069. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45070. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45071. if (target.getBoundingInfo) {
  45072. if (toBoundingCenter) {
  45073. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45074. }
  45075. else {
  45076. this._targetBoundingCenter = null;
  45077. }
  45078. this._targetHost = target;
  45079. this._target = this._getTargetPosition();
  45080. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45081. }
  45082. else {
  45083. var newTarget = target;
  45084. var currentTarget = this._getTargetPosition();
  45085. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45086. return;
  45087. }
  45088. this._targetHost = null;
  45089. this._target = newTarget;
  45090. this._targetBoundingCenter = null;
  45091. this.onMeshTargetChangedObservable.notifyObservers(null);
  45092. }
  45093. this.rebuildAnglesAndRadius();
  45094. };
  45095. ArcRotateCamera.prototype._getViewMatrix = function () {
  45096. // Compute
  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. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45108. if (!this._collider) {
  45109. this._collider = new BABYLON.Collider();
  45110. }
  45111. this._collider._radius = this.collisionRadius;
  45112. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45113. this._collisionTriggered = true;
  45114. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45115. }
  45116. else {
  45117. this.position.copyFrom(this._newPosition);
  45118. var up = this.upVector;
  45119. if (this.allowUpsideDown && sinb < 0) {
  45120. up = up.clone();
  45121. up = up.negate();
  45122. }
  45123. if (this.getScene().useRightHandedSystem) {
  45124. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45125. }
  45126. else {
  45127. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45128. }
  45129. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45130. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45131. }
  45132. this._currentTarget = target;
  45133. return this._viewMatrix;
  45134. };
  45135. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45136. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45137. meshes = meshes || this.getScene().meshes;
  45138. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45139. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45140. this.radius = distance * this.zoomOnFactor;
  45141. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45142. };
  45143. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45144. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45145. var meshesOrMinMaxVector;
  45146. var distance;
  45147. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45148. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45149. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45150. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45151. }
  45152. else {
  45153. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45154. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45155. distance = minMaxVectorAndDistance.distance;
  45156. }
  45157. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45158. if (!doNotUpdateMaxZ) {
  45159. this.maxZ = distance * 2;
  45160. }
  45161. };
  45162. /**
  45163. * @override
  45164. * Override Camera.createRigCamera
  45165. */
  45166. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45167. var alphaShift = 0;
  45168. switch (this.cameraRigMode) {
  45169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45172. case BABYLON.Camera.RIG_MODE_VR:
  45173. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45174. break;
  45175. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45176. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45177. break;
  45178. }
  45179. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45180. rigCam._cameraRigParams = {};
  45181. return rigCam;
  45182. };
  45183. /**
  45184. * @override
  45185. * Override Camera._updateRigCameras
  45186. */
  45187. ArcRotateCamera.prototype._updateRigCameras = function () {
  45188. var camLeft = this._rigCameras[0];
  45189. var camRight = this._rigCameras[1];
  45190. camLeft.beta = camRight.beta = this.beta;
  45191. camLeft.radius = camRight.radius = this.radius;
  45192. switch (this.cameraRigMode) {
  45193. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45196. case BABYLON.Camera.RIG_MODE_VR:
  45197. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45198. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45199. break;
  45200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45201. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45202. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45203. break;
  45204. }
  45205. _super.prototype._updateRigCameras.call(this);
  45206. };
  45207. ArcRotateCamera.prototype.dispose = function () {
  45208. this.inputs.clear();
  45209. _super.prototype.dispose.call(this);
  45210. };
  45211. ArcRotateCamera.prototype.getClassName = function () {
  45212. return "ArcRotateCamera";
  45213. };
  45214. __decorate([
  45215. BABYLON.serialize()
  45216. ], ArcRotateCamera.prototype, "alpha", void 0);
  45217. __decorate([
  45218. BABYLON.serialize()
  45219. ], ArcRotateCamera.prototype, "beta", void 0);
  45220. __decorate([
  45221. BABYLON.serialize()
  45222. ], ArcRotateCamera.prototype, "radius", void 0);
  45223. __decorate([
  45224. BABYLON.serializeAsVector3("target")
  45225. ], ArcRotateCamera.prototype, "_target", void 0);
  45226. __decorate([
  45227. BABYLON.serialize()
  45228. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45229. __decorate([
  45230. BABYLON.serialize()
  45231. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45232. __decorate([
  45233. BABYLON.serialize()
  45234. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45235. __decorate([
  45236. BABYLON.serialize()
  45237. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45238. __decorate([
  45239. BABYLON.serialize()
  45240. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45241. __decorate([
  45242. BABYLON.serialize()
  45243. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45244. __decorate([
  45245. BABYLON.serialize()
  45246. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45247. __decorate([
  45248. BABYLON.serialize()
  45249. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45250. __decorate([
  45251. BABYLON.serialize()
  45252. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45253. __decorate([
  45254. BABYLON.serialize()
  45255. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45256. __decorate([
  45257. BABYLON.serialize()
  45258. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45259. __decorate([
  45260. BABYLON.serialize()
  45261. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45262. __decorate([
  45263. BABYLON.serialize()
  45264. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45265. __decorate([
  45266. BABYLON.serializeAsVector3()
  45267. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45268. __decorate([
  45269. BABYLON.serialize()
  45270. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45271. __decorate([
  45272. BABYLON.serialize()
  45273. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45274. __decorate([
  45275. BABYLON.serialize()
  45276. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45277. return ArcRotateCamera;
  45278. }(BABYLON.TargetCamera));
  45279. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45280. })(BABYLON || (BABYLON = {}));
  45281. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45282. var BABYLON;
  45283. (function (BABYLON) {
  45284. /**
  45285. * The HemisphericLight simulates the ambient environment light,
  45286. * so the passed direction is the light reflection direction, not the incoming direction.
  45287. */
  45288. var HemisphericLight = /** @class */ (function (_super) {
  45289. __extends(HemisphericLight, _super);
  45290. /**
  45291. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45292. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45293. * The HemisphericLight can't cast shadows.
  45294. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45295. * @param name The friendly name of the light
  45296. * @param direction The direction of the light reflection
  45297. * @param scene The scene the light belongs to
  45298. */
  45299. function HemisphericLight(name, direction, scene) {
  45300. var _this = _super.call(this, name, scene) || this;
  45301. /**
  45302. * The groundColor is the light in the opposite direction to the one specified during creation.
  45303. * 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.
  45304. */
  45305. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45306. _this.direction = direction || BABYLON.Vector3.Up();
  45307. return _this;
  45308. }
  45309. HemisphericLight.prototype._buildUniformLayout = function () {
  45310. this._uniformBuffer.addUniform("vLightData", 4);
  45311. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45312. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45313. this._uniformBuffer.addUniform("vLightGround", 3);
  45314. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45315. this._uniformBuffer.addUniform("depthValues", 2);
  45316. this._uniformBuffer.create();
  45317. };
  45318. /**
  45319. * Returns the string "HemisphericLight".
  45320. * @return The class name
  45321. */
  45322. HemisphericLight.prototype.getClassName = function () {
  45323. return "HemisphericLight";
  45324. };
  45325. /**
  45326. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45327. * Returns the updated direction.
  45328. * @param target The target the direction should point to
  45329. * @return The computed direction
  45330. */
  45331. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45332. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45333. return this.direction;
  45334. };
  45335. /**
  45336. * Returns the shadow generator associated to the light.
  45337. * @returns Always null for hemispheric lights because it does not support shadows.
  45338. */
  45339. HemisphericLight.prototype.getShadowGenerator = function () {
  45340. return null;
  45341. };
  45342. /**
  45343. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45344. * @param effect The effect to update
  45345. * @param lightIndex The index of the light in the effect to update
  45346. * @returns The hemispheric light
  45347. */
  45348. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45349. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45350. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45351. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45352. return this;
  45353. };
  45354. /**
  45355. * @ignore internal use only.
  45356. */
  45357. HemisphericLight.prototype._getWorldMatrix = function () {
  45358. if (!this._worldMatrix) {
  45359. this._worldMatrix = BABYLON.Matrix.Identity();
  45360. }
  45361. return this._worldMatrix;
  45362. };
  45363. /**
  45364. * Returns the integer 3.
  45365. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45366. */
  45367. HemisphericLight.prototype.getTypeID = function () {
  45368. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45369. };
  45370. __decorate([
  45371. BABYLON.serializeAsColor3()
  45372. ], HemisphericLight.prototype, "groundColor", void 0);
  45373. __decorate([
  45374. BABYLON.serializeAsVector3()
  45375. ], HemisphericLight.prototype, "direction", void 0);
  45376. return HemisphericLight;
  45377. }(BABYLON.Light));
  45378. BABYLON.HemisphericLight = HemisphericLight;
  45379. })(BABYLON || (BABYLON = {}));
  45380. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45381. var BABYLON;
  45382. (function (BABYLON) {
  45383. /**
  45384. * Base implementation of @see IShadowLight
  45385. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45386. */
  45387. var ShadowLight = /** @class */ (function (_super) {
  45388. __extends(ShadowLight, _super);
  45389. function ShadowLight() {
  45390. var _this = _super !== null && _super.apply(this, arguments) || this;
  45391. _this._needProjectionMatrixCompute = true;
  45392. return _this;
  45393. }
  45394. ShadowLight.prototype._setPosition = function (value) {
  45395. this._position = value;
  45396. };
  45397. Object.defineProperty(ShadowLight.prototype, "position", {
  45398. /**
  45399. * Sets the position the shadow will be casted from. Also use as the light position for both
  45400. * point and spot lights.
  45401. */
  45402. get: function () {
  45403. return this._position;
  45404. },
  45405. /**
  45406. * Sets the position the shadow will be casted from. Also use as the light position for both
  45407. * point and spot lights.
  45408. */
  45409. set: function (value) {
  45410. this._setPosition(value);
  45411. },
  45412. enumerable: true,
  45413. configurable: true
  45414. });
  45415. ShadowLight.prototype._setDirection = function (value) {
  45416. this._direction = value;
  45417. };
  45418. Object.defineProperty(ShadowLight.prototype, "direction", {
  45419. /**
  45420. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45421. * Also use as the light direction on spot and directional lights.
  45422. */
  45423. get: function () {
  45424. return this._direction;
  45425. },
  45426. /**
  45427. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45428. * Also use as the light direction on spot and directional lights.
  45429. */
  45430. set: function (value) {
  45431. this._setDirection(value);
  45432. },
  45433. enumerable: true,
  45434. configurable: true
  45435. });
  45436. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45437. /**
  45438. * Gets the shadow projection clipping minimum z value.
  45439. */
  45440. get: function () {
  45441. return this._shadowMinZ;
  45442. },
  45443. /**
  45444. * Sets the shadow projection clipping minimum z value.
  45445. */
  45446. set: function (value) {
  45447. this._shadowMinZ = value;
  45448. this.forceProjectionMatrixCompute();
  45449. },
  45450. enumerable: true,
  45451. configurable: true
  45452. });
  45453. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45454. /**
  45455. * Sets the shadow projection clipping maximum z value.
  45456. */
  45457. get: function () {
  45458. return this._shadowMaxZ;
  45459. },
  45460. /**
  45461. * Gets the shadow projection clipping maximum z value.
  45462. */
  45463. set: function (value) {
  45464. this._shadowMaxZ = value;
  45465. this.forceProjectionMatrixCompute();
  45466. },
  45467. enumerable: true,
  45468. configurable: true
  45469. });
  45470. /**
  45471. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45472. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45473. */
  45474. ShadowLight.prototype.computeTransformedInformation = function () {
  45475. if (this.parent && this.parent.getWorldMatrix) {
  45476. if (!this.transformedPosition) {
  45477. this.transformedPosition = BABYLON.Vector3.Zero();
  45478. }
  45479. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45480. // In case the direction is present.
  45481. if (this.direction) {
  45482. if (!this.transformedDirection) {
  45483. this.transformedDirection = BABYLON.Vector3.Zero();
  45484. }
  45485. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45486. }
  45487. return true;
  45488. }
  45489. return false;
  45490. };
  45491. /**
  45492. * Return the depth scale used for the shadow map.
  45493. * @returns the depth scale.
  45494. */
  45495. ShadowLight.prototype.getDepthScale = function () {
  45496. return 50.0;
  45497. };
  45498. /**
  45499. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45500. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45501. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45502. */
  45503. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45504. return this.transformedDirection ? this.transformedDirection : this.direction;
  45505. };
  45506. /**
  45507. * Returns the ShadowLight absolute position in the World.
  45508. * @returns the position vector in world space
  45509. */
  45510. ShadowLight.prototype.getAbsolutePosition = function () {
  45511. return this.transformedPosition ? this.transformedPosition : this.position;
  45512. };
  45513. /**
  45514. * Sets the ShadowLight direction toward the passed target.
  45515. * @param target The point tot target in local space
  45516. * @returns the updated ShadowLight direction
  45517. */
  45518. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45519. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45520. return this.direction;
  45521. };
  45522. /**
  45523. * Returns the light rotation in euler definition.
  45524. * @returns the x y z rotation in local space.
  45525. */
  45526. ShadowLight.prototype.getRotation = function () {
  45527. this.direction.normalize();
  45528. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45529. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45530. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45531. };
  45532. /**
  45533. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45534. * @returns true if a cube texture needs to be use
  45535. */
  45536. ShadowLight.prototype.needCube = function () {
  45537. return false;
  45538. };
  45539. /**
  45540. * Detects if the projection matrix requires to be recomputed this frame.
  45541. * @returns true if it requires to be recomputed otherwise, false.
  45542. */
  45543. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45544. return this._needProjectionMatrixCompute;
  45545. };
  45546. /**
  45547. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45548. */
  45549. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45550. this._needProjectionMatrixCompute = true;
  45551. };
  45552. /**
  45553. * Get the world matrix of the sahdow lights.
  45554. * @ignore Internal Use Only
  45555. */
  45556. ShadowLight.prototype._getWorldMatrix = function () {
  45557. if (!this._worldMatrix) {
  45558. this._worldMatrix = BABYLON.Matrix.Identity();
  45559. }
  45560. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45561. return this._worldMatrix;
  45562. };
  45563. /**
  45564. * Gets the minZ used for shadow according to both the scene and the light.
  45565. * @param activeCamera The camera we are returning the min for
  45566. * @returns the depth min z
  45567. */
  45568. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45569. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45570. };
  45571. /**
  45572. * Gets the maxZ used for shadow according to both the scene and the light.
  45573. * @param activeCamera The camera we are returning the max for
  45574. * @returns the depth max z
  45575. */
  45576. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45577. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45578. };
  45579. /**
  45580. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45581. * @param matrix The materix to updated with the projection information
  45582. * @param viewMatrix The transform matrix of the light
  45583. * @param renderList The list of mesh to render in the map
  45584. * @returns The current light
  45585. */
  45586. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45587. if (this.customProjectionMatrixBuilder) {
  45588. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45589. }
  45590. else {
  45591. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45592. }
  45593. return this;
  45594. };
  45595. __decorate([
  45596. BABYLON.serializeAsVector3()
  45597. ], ShadowLight.prototype, "position", null);
  45598. __decorate([
  45599. BABYLON.serializeAsVector3()
  45600. ], ShadowLight.prototype, "direction", null);
  45601. __decorate([
  45602. BABYLON.serialize()
  45603. ], ShadowLight.prototype, "shadowMinZ", null);
  45604. __decorate([
  45605. BABYLON.serialize()
  45606. ], ShadowLight.prototype, "shadowMaxZ", null);
  45607. return ShadowLight;
  45608. }(BABYLON.Light));
  45609. BABYLON.ShadowLight = ShadowLight;
  45610. })(BABYLON || (BABYLON = {}));
  45611. //# sourceMappingURL=babylon.shadowLight.js.map
  45612. var BABYLON;
  45613. (function (BABYLON) {
  45614. /**
  45615. * A point light is a light defined by an unique point in world space.
  45616. * The light is emitted in every direction from this point.
  45617. * A good example of a point light is a standard light bulb.
  45618. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45619. */
  45620. var PointLight = /** @class */ (function (_super) {
  45621. __extends(PointLight, _super);
  45622. /**
  45623. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45624. * A PointLight emits the light in every direction.
  45625. * It can cast shadows.
  45626. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45627. * ```javascript
  45628. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45629. * ```
  45630. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45631. * @param name The light friendly name
  45632. * @param position The position of the point light in the scene
  45633. * @param scene The scene the lights belongs to
  45634. */
  45635. function PointLight(name, position, scene) {
  45636. var _this = _super.call(this, name, scene) || this;
  45637. _this._shadowAngle = Math.PI / 2;
  45638. _this.position = position;
  45639. return _this;
  45640. }
  45641. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45642. /**
  45643. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45644. * This specifies what angle the shadow will use to be created.
  45645. *
  45646. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45647. */
  45648. get: function () {
  45649. return this._shadowAngle;
  45650. },
  45651. /**
  45652. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45653. * This specifies what angle the shadow will use to be created.
  45654. *
  45655. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45656. */
  45657. set: function (value) {
  45658. this._shadowAngle = value;
  45659. this.forceProjectionMatrixCompute();
  45660. },
  45661. enumerable: true,
  45662. configurable: true
  45663. });
  45664. Object.defineProperty(PointLight.prototype, "direction", {
  45665. /**
  45666. * Gets the direction if it has been set.
  45667. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45668. */
  45669. get: function () {
  45670. return this._direction;
  45671. },
  45672. /**
  45673. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45674. */
  45675. set: function (value) {
  45676. var previousNeedCube = this.needCube();
  45677. this._direction = value;
  45678. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45679. this._shadowGenerator.recreateShadowMap();
  45680. }
  45681. },
  45682. enumerable: true,
  45683. configurable: true
  45684. });
  45685. /**
  45686. * Returns the string "PointLight"
  45687. * @returns the class name
  45688. */
  45689. PointLight.prototype.getClassName = function () {
  45690. return "PointLight";
  45691. };
  45692. /**
  45693. * Returns the integer 0.
  45694. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45695. */
  45696. PointLight.prototype.getTypeID = function () {
  45697. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45698. };
  45699. /**
  45700. * Specifies wether or not the shadowmap should be a cube texture.
  45701. * @returns true if the shadowmap needs to be a cube texture.
  45702. */
  45703. PointLight.prototype.needCube = function () {
  45704. return !this.direction;
  45705. };
  45706. /**
  45707. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45708. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45709. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45710. */
  45711. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45712. if (this.direction) {
  45713. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45714. }
  45715. else {
  45716. switch (faceIndex) {
  45717. case 0:
  45718. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45719. case 1:
  45720. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45721. case 2:
  45722. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45723. case 3:
  45724. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45725. case 4:
  45726. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45727. case 5:
  45728. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45729. }
  45730. }
  45731. return BABYLON.Vector3.Zero();
  45732. };
  45733. /**
  45734. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45735. * - fov = PI / 2
  45736. * - aspect ratio : 1.0
  45737. * - z-near and far equal to the active camera minZ and maxZ.
  45738. * Returns the PointLight.
  45739. */
  45740. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45741. var activeCamera = this.getScene().activeCamera;
  45742. if (!activeCamera) {
  45743. return;
  45744. }
  45745. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45746. };
  45747. PointLight.prototype._buildUniformLayout = function () {
  45748. this._uniformBuffer.addUniform("vLightData", 4);
  45749. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45750. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45751. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45752. this._uniformBuffer.addUniform("depthValues", 2);
  45753. this._uniformBuffer.create();
  45754. };
  45755. /**
  45756. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45757. * @param effect The effect to update
  45758. * @param lightIndex The index of the light in the effect to update
  45759. * @returns The point light
  45760. */
  45761. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45762. if (this.computeTransformedInformation()) {
  45763. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45764. return this;
  45765. }
  45766. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45767. return this;
  45768. };
  45769. __decorate([
  45770. BABYLON.serialize()
  45771. ], PointLight.prototype, "shadowAngle", null);
  45772. return PointLight;
  45773. }(BABYLON.ShadowLight));
  45774. BABYLON.PointLight = PointLight;
  45775. })(BABYLON || (BABYLON = {}));
  45776. //# sourceMappingURL=babylon.pointLight.js.map
  45777. var BABYLON;
  45778. (function (BABYLON) {
  45779. /**
  45780. * A directional light is defined by a direction (what a surprise!).
  45781. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45782. * 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.
  45783. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45784. */
  45785. var DirectionalLight = /** @class */ (function (_super) {
  45786. __extends(DirectionalLight, _super);
  45787. /**
  45788. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45789. * The directional light is emitted from everywhere in the given direction.
  45790. * It can cast shawdows.
  45791. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45792. * @param name The friendly name of the light
  45793. * @param direction The direction of the light
  45794. * @param scene The scene the light belongs to
  45795. */
  45796. function DirectionalLight(name, direction, scene) {
  45797. var _this = _super.call(this, name, scene) || this;
  45798. _this._shadowFrustumSize = 0;
  45799. _this._shadowOrthoScale = 0.5;
  45800. /**
  45801. * Automatically compute the projection matrix to best fit (including all the casters)
  45802. * on each frame.
  45803. */
  45804. _this.autoUpdateExtends = true;
  45805. // Cache
  45806. _this._orthoLeft = Number.MAX_VALUE;
  45807. _this._orthoRight = Number.MIN_VALUE;
  45808. _this._orthoTop = Number.MIN_VALUE;
  45809. _this._orthoBottom = Number.MAX_VALUE;
  45810. _this.position = direction.scale(-1.0);
  45811. _this.direction = direction;
  45812. return _this;
  45813. }
  45814. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45815. /**
  45816. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45817. */
  45818. get: function () {
  45819. return this._shadowFrustumSize;
  45820. },
  45821. /**
  45822. * Specifies a fix frustum size for the shadow generation.
  45823. */
  45824. set: function (value) {
  45825. this._shadowFrustumSize = value;
  45826. this.forceProjectionMatrixCompute();
  45827. },
  45828. enumerable: true,
  45829. configurable: true
  45830. });
  45831. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45832. /**
  45833. * Gets the shadow projection scale against the optimal computed one.
  45834. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45835. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45836. */
  45837. get: function () {
  45838. return this._shadowOrthoScale;
  45839. },
  45840. /**
  45841. * Sets the shadow projection scale against the optimal computed one.
  45842. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45843. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45844. */
  45845. set: function (value) {
  45846. this._shadowOrthoScale = value;
  45847. this.forceProjectionMatrixCompute();
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. /**
  45853. * Returns the string "DirectionalLight".
  45854. * @return The class name
  45855. */
  45856. DirectionalLight.prototype.getClassName = function () {
  45857. return "DirectionalLight";
  45858. };
  45859. /**
  45860. * Returns the integer 1.
  45861. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45862. */
  45863. DirectionalLight.prototype.getTypeID = function () {
  45864. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45865. };
  45866. /**
  45867. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45868. * Returns the DirectionalLight Shadow projection matrix.
  45869. */
  45870. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45871. if (this.shadowFrustumSize > 0) {
  45872. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45873. }
  45874. else {
  45875. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45876. }
  45877. };
  45878. /**
  45879. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45880. * Returns the DirectionalLight Shadow projection matrix.
  45881. */
  45882. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45883. var activeCamera = this.getScene().activeCamera;
  45884. if (!activeCamera) {
  45885. return;
  45886. }
  45887. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45888. };
  45889. /**
  45890. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45891. * Returns the DirectionalLight Shadow projection matrix.
  45892. */
  45893. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45894. var activeCamera = this.getScene().activeCamera;
  45895. if (!activeCamera) {
  45896. return;
  45897. }
  45898. // Check extends
  45899. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45900. var tempVector3 = BABYLON.Vector3.Zero();
  45901. this._orthoLeft = Number.MAX_VALUE;
  45902. this._orthoRight = Number.MIN_VALUE;
  45903. this._orthoTop = Number.MIN_VALUE;
  45904. this._orthoBottom = Number.MAX_VALUE;
  45905. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45906. var mesh = renderList[meshIndex];
  45907. if (!mesh) {
  45908. continue;
  45909. }
  45910. var boundingInfo = mesh.getBoundingInfo();
  45911. var boundingBox = boundingInfo.boundingBox;
  45912. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45913. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45914. if (tempVector3.x < this._orthoLeft)
  45915. this._orthoLeft = tempVector3.x;
  45916. if (tempVector3.y < this._orthoBottom)
  45917. this._orthoBottom = tempVector3.y;
  45918. if (tempVector3.x > this._orthoRight)
  45919. this._orthoRight = tempVector3.x;
  45920. if (tempVector3.y > this._orthoTop)
  45921. this._orthoTop = tempVector3.y;
  45922. }
  45923. }
  45924. }
  45925. var xOffset = this._orthoRight - this._orthoLeft;
  45926. var yOffset = this._orthoTop - this._orthoBottom;
  45927. 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);
  45928. };
  45929. DirectionalLight.prototype._buildUniformLayout = function () {
  45930. this._uniformBuffer.addUniform("vLightData", 4);
  45931. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45932. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45933. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45934. this._uniformBuffer.addUniform("depthValues", 2);
  45935. this._uniformBuffer.create();
  45936. };
  45937. /**
  45938. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45939. * @param effect The effect to update
  45940. * @param lightIndex The index of the light in the effect to update
  45941. * @returns The directional light
  45942. */
  45943. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45944. if (this.computeTransformedInformation()) {
  45945. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45946. return this;
  45947. }
  45948. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45949. return this;
  45950. };
  45951. /**
  45952. * Gets the minZ used for shadow according to both the scene and the light.
  45953. *
  45954. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45955. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45956. * @param activeCamera The camera we are returning the min for
  45957. * @returns the depth min z
  45958. */
  45959. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45960. return 1;
  45961. };
  45962. /**
  45963. * Gets the maxZ used for shadow according to both the scene and the light.
  45964. *
  45965. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45966. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45967. * @param activeCamera The camera we are returning the max for
  45968. * @returns the depth max z
  45969. */
  45970. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45971. return 1;
  45972. };
  45973. __decorate([
  45974. BABYLON.serialize()
  45975. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45976. __decorate([
  45977. BABYLON.serialize()
  45978. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45979. __decorate([
  45980. BABYLON.serialize()
  45981. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45982. return DirectionalLight;
  45983. }(BABYLON.ShadowLight));
  45984. BABYLON.DirectionalLight = DirectionalLight;
  45985. })(BABYLON || (BABYLON = {}));
  45986. //# sourceMappingURL=babylon.directionalLight.js.map
  45987. var BABYLON;
  45988. (function (BABYLON) {
  45989. /**
  45990. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45991. * These values define a cone of light starting from the position, emitting toward the direction.
  45992. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45993. * and the exponent defines the speed of the decay of the light with distance (reach).
  45994. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45995. */
  45996. var SpotLight = /** @class */ (function (_super) {
  45997. __extends(SpotLight, _super);
  45998. /**
  45999. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46000. * It can cast shadows.
  46001. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46002. * @param name The light friendly name
  46003. * @param position The position of the spot light in the scene
  46004. * @param direction The direction of the light in the scene
  46005. * @param angle The cone angle of the light in Radians
  46006. * @param exponent The light decay speed with the distance from the emission spot
  46007. * @param scene The scene the lights belongs to
  46008. */
  46009. function SpotLight(name, position, direction, angle, exponent, scene) {
  46010. var _this = _super.call(this, name, scene) || this;
  46011. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46012. _this._projectionTextureLightNear = 1e-6;
  46013. _this._projectionTextureLightFar = 1000.0;
  46014. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46015. _this._projectionTextureViewLightDirty = true;
  46016. _this._projectionTextureProjectionLightDirty = true;
  46017. _this._projectionTextureDirty = true;
  46018. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46019. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46020. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46021. _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);
  46022. _this.position = position;
  46023. _this.direction = direction;
  46024. _this.angle = angle;
  46025. _this.exponent = exponent;
  46026. return _this;
  46027. }
  46028. Object.defineProperty(SpotLight.prototype, "angle", {
  46029. /**
  46030. * Gets the cone angle of the spot light in Radians.
  46031. */
  46032. get: function () {
  46033. return this._angle;
  46034. },
  46035. /**
  46036. * Sets the cone angle of the spot light in Radians.
  46037. */
  46038. set: function (value) {
  46039. this._angle = value;
  46040. this._projectionTextureProjectionLightDirty = true;
  46041. this.forceProjectionMatrixCompute();
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46047. /**
  46048. * Allows scaling the angle of the light for shadow generation only.
  46049. */
  46050. get: function () {
  46051. return this._shadowAngleScale;
  46052. },
  46053. /**
  46054. * Allows scaling the angle of the light for shadow generation only.
  46055. */
  46056. set: function (value) {
  46057. this._shadowAngleScale = value;
  46058. this.forceProjectionMatrixCompute();
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46064. /**
  46065. * Allows reading the projecton texture
  46066. */
  46067. get: function () {
  46068. return this._projectionTextureMatrix;
  46069. },
  46070. enumerable: true,
  46071. configurable: true
  46072. });
  46073. ;
  46074. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46075. /**
  46076. * Gets the near clip of the Spotlight for texture projection.
  46077. */
  46078. get: function () {
  46079. return this._projectionTextureLightNear;
  46080. },
  46081. /**
  46082. * Sets the near clip of the Spotlight for texture projection.
  46083. */
  46084. set: function (value) {
  46085. this._projectionTextureLightNear = value;
  46086. this._projectionTextureProjectionLightDirty = true;
  46087. },
  46088. enumerable: true,
  46089. configurable: true
  46090. });
  46091. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46092. /**
  46093. * Gets the far clip of the Spotlight for texture projection.
  46094. */
  46095. get: function () {
  46096. return this._projectionTextureLightFar;
  46097. },
  46098. /**
  46099. * Sets the far clip of the Spotlight for texture projection.
  46100. */
  46101. set: function (value) {
  46102. this._projectionTextureLightFar = value;
  46103. this._projectionTextureProjectionLightDirty = true;
  46104. },
  46105. enumerable: true,
  46106. configurable: true
  46107. });
  46108. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46109. /**
  46110. * Gets the Up vector of the Spotlight for texture projection.
  46111. */
  46112. get: function () {
  46113. return this._projectionTextureUpDirection;
  46114. },
  46115. /**
  46116. * Sets the Up vector of the Spotlight for texture projection.
  46117. */
  46118. set: function (value) {
  46119. this._projectionTextureUpDirection = value;
  46120. this._projectionTextureProjectionLightDirty = true;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. ;
  46126. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46127. /**
  46128. * Gets the projection texture of the light.
  46129. */
  46130. get: function () {
  46131. return this._projectionTexture;
  46132. },
  46133. /**
  46134. * Sets the projection texture of the light.
  46135. */
  46136. set: function (value) {
  46137. this._projectionTexture = value;
  46138. this._projectionTextureDirty = true;
  46139. },
  46140. enumerable: true,
  46141. configurable: true
  46142. });
  46143. /**
  46144. * Returns the string "SpotLight".
  46145. * @returns the class name
  46146. */
  46147. SpotLight.prototype.getClassName = function () {
  46148. return "SpotLight";
  46149. };
  46150. /**
  46151. * Returns the integer 2.
  46152. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46153. */
  46154. SpotLight.prototype.getTypeID = function () {
  46155. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46156. };
  46157. /**
  46158. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46159. */
  46160. SpotLight.prototype._setDirection = function (value) {
  46161. _super.prototype._setDirection.call(this, value);
  46162. this._projectionTextureViewLightDirty = true;
  46163. };
  46164. /**
  46165. * Overrides the position setter to recompute the projection texture view light Matrix.
  46166. */
  46167. SpotLight.prototype._setPosition = function (value) {
  46168. _super.prototype._setPosition.call(this, value);
  46169. this._projectionTextureViewLightDirty = true;
  46170. };
  46171. /**
  46172. * 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.
  46173. * Returns the SpotLight.
  46174. */
  46175. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46176. var activeCamera = this.getScene().activeCamera;
  46177. if (!activeCamera) {
  46178. return;
  46179. }
  46180. this._shadowAngleScale = this._shadowAngleScale || 1;
  46181. var angle = this._shadowAngleScale * this._angle;
  46182. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46183. };
  46184. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46185. this._projectionTextureViewLightDirty = false;
  46186. this._projectionTextureDirty = true;
  46187. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46188. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46189. };
  46190. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46191. this._projectionTextureProjectionLightDirty = false;
  46192. this._projectionTextureDirty = true;
  46193. var light_far = this.projectionTextureLightFar;
  46194. var light_near = this.projectionTextureLightNear;
  46195. var P = light_far / (light_far - light_near);
  46196. var Q = -P * light_near;
  46197. var S = 1.0 / Math.tan(this._angle / 2.0);
  46198. var A = 1.0;
  46199. 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);
  46200. };
  46201. /**
  46202. * Main function for light texture projection matrix computing.
  46203. */
  46204. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46205. this._projectionTextureDirty = false;
  46206. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46207. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46208. };
  46209. SpotLight.prototype._buildUniformLayout = function () {
  46210. this._uniformBuffer.addUniform("vLightData", 4);
  46211. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46212. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46213. this._uniformBuffer.addUniform("vLightDirection", 3);
  46214. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46215. this._uniformBuffer.addUniform("depthValues", 2);
  46216. this._uniformBuffer.create();
  46217. };
  46218. /**
  46219. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46220. * @param effect The effect to update
  46221. * @param lightIndex The index of the light in the effect to update
  46222. * @returns The spot light
  46223. */
  46224. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46225. var normalizeDirection;
  46226. if (this.computeTransformedInformation()) {
  46227. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46228. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46229. }
  46230. else {
  46231. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46232. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46233. }
  46234. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46235. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46236. if (this._projectionTextureViewLightDirty) {
  46237. this._computeProjectionTextureViewLightMatrix();
  46238. }
  46239. if (this._projectionTextureProjectionLightDirty) {
  46240. this._computeProjectionTextureProjectionLightMatrix();
  46241. }
  46242. if (this._projectionTextureDirty) {
  46243. this._computeProjectionTextureMatrix();
  46244. }
  46245. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46246. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46247. }
  46248. return this;
  46249. };
  46250. /**
  46251. * Disposes the light and the associated resources.
  46252. */
  46253. SpotLight.prototype.dispose = function () {
  46254. _super.prototype.dispose.call(this);
  46255. if (this._projectionTexture) {
  46256. this._projectionTexture.dispose();
  46257. }
  46258. };
  46259. __decorate([
  46260. BABYLON.serialize()
  46261. ], SpotLight.prototype, "angle", null);
  46262. __decorate([
  46263. BABYLON.serialize()
  46264. ], SpotLight.prototype, "shadowAngleScale", null);
  46265. __decorate([
  46266. BABYLON.serialize()
  46267. ], SpotLight.prototype, "exponent", void 0);
  46268. __decorate([
  46269. BABYLON.serialize()
  46270. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46271. __decorate([
  46272. BABYLON.serialize()
  46273. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46274. __decorate([
  46275. BABYLON.serialize()
  46276. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46277. __decorate([
  46278. BABYLON.serializeAsTexture("projectedLightTexture")
  46279. ], SpotLight.prototype, "_projectionTexture", void 0);
  46280. return SpotLight;
  46281. }(BABYLON.ShadowLight));
  46282. BABYLON.SpotLight = SpotLight;
  46283. })(BABYLON || (BABYLON = {}));
  46284. //# sourceMappingURL=babylon.spotLight.js.map
  46285. var BABYLON;
  46286. (function (BABYLON) {
  46287. /**
  46288. * Class used to override all child animations of a given target
  46289. */
  46290. var AnimationPropertiesOverride = /** @class */ (function () {
  46291. function AnimationPropertiesOverride() {
  46292. /**
  46293. * Gets or sets a value indicating if animation blending must be used
  46294. */
  46295. this.enableBlending = false;
  46296. /**
  46297. * Gets or sets the blending speed to use when enableBlending is true
  46298. */
  46299. this.blendingSpeed = 0.01;
  46300. /**
  46301. * Gets or sets the default loop mode to use
  46302. */
  46303. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46304. }
  46305. return AnimationPropertiesOverride;
  46306. }());
  46307. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46308. })(BABYLON || (BABYLON = {}));
  46309. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46310. var BABYLON;
  46311. (function (BABYLON) {
  46312. var AnimationRange = /** @class */ (function () {
  46313. function AnimationRange(name, from, to) {
  46314. this.name = name;
  46315. this.from = from;
  46316. this.to = to;
  46317. }
  46318. AnimationRange.prototype.clone = function () {
  46319. return new AnimationRange(this.name, this.from, this.to);
  46320. };
  46321. return AnimationRange;
  46322. }());
  46323. BABYLON.AnimationRange = AnimationRange;
  46324. /**
  46325. * Composed of a frame, and an action function
  46326. */
  46327. var AnimationEvent = /** @class */ (function () {
  46328. function AnimationEvent(frame, action, onlyOnce) {
  46329. this.frame = frame;
  46330. this.action = action;
  46331. this.onlyOnce = onlyOnce;
  46332. this.isDone = false;
  46333. }
  46334. return AnimationEvent;
  46335. }());
  46336. BABYLON.AnimationEvent = AnimationEvent;
  46337. var PathCursor = /** @class */ (function () {
  46338. function PathCursor(path) {
  46339. this.path = path;
  46340. this._onchange = new Array();
  46341. this.value = 0;
  46342. this.animations = new Array();
  46343. }
  46344. PathCursor.prototype.getPoint = function () {
  46345. var point = this.path.getPointAtLengthPosition(this.value);
  46346. return new BABYLON.Vector3(point.x, 0, point.y);
  46347. };
  46348. PathCursor.prototype.moveAhead = function (step) {
  46349. if (step === void 0) { step = 0.002; }
  46350. this.move(step);
  46351. return this;
  46352. };
  46353. PathCursor.prototype.moveBack = function (step) {
  46354. if (step === void 0) { step = 0.002; }
  46355. this.move(-step);
  46356. return this;
  46357. };
  46358. PathCursor.prototype.move = function (step) {
  46359. if (Math.abs(step) > 1) {
  46360. throw "step size should be less than 1.";
  46361. }
  46362. this.value += step;
  46363. this.ensureLimits();
  46364. this.raiseOnChange();
  46365. return this;
  46366. };
  46367. PathCursor.prototype.ensureLimits = function () {
  46368. while (this.value > 1) {
  46369. this.value -= 1;
  46370. }
  46371. while (this.value < 0) {
  46372. this.value += 1;
  46373. }
  46374. return this;
  46375. };
  46376. // used by animation engine
  46377. PathCursor.prototype.raiseOnChange = function () {
  46378. var _this = this;
  46379. this._onchange.forEach(function (f) { return f(_this); });
  46380. return this;
  46381. };
  46382. PathCursor.prototype.onchange = function (f) {
  46383. this._onchange.push(f);
  46384. return this;
  46385. };
  46386. return PathCursor;
  46387. }());
  46388. BABYLON.PathCursor = PathCursor;
  46389. var AnimationKeyInterpolation;
  46390. (function (AnimationKeyInterpolation) {
  46391. /**
  46392. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46393. */
  46394. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46395. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46396. var Animation = /** @class */ (function () {
  46397. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46398. this.name = name;
  46399. this.targetProperty = targetProperty;
  46400. this.framePerSecond = framePerSecond;
  46401. this.dataType = dataType;
  46402. this.loopMode = loopMode;
  46403. this.enableBlending = enableBlending;
  46404. this._runtimeAnimations = new Array();
  46405. // The set of event that will be linked to this animation
  46406. this._events = new Array();
  46407. this.blendingSpeed = 0.01;
  46408. this._ranges = {};
  46409. this.targetPropertyPath = targetProperty.split(".");
  46410. this.dataType = dataType;
  46411. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46412. }
  46413. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46414. var dataType = undefined;
  46415. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46416. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46417. }
  46418. else if (from instanceof BABYLON.Quaternion) {
  46419. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46420. }
  46421. else if (from instanceof BABYLON.Vector3) {
  46422. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46423. }
  46424. else if (from instanceof BABYLON.Vector2) {
  46425. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46426. }
  46427. else if (from instanceof BABYLON.Color3) {
  46428. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46429. }
  46430. else if (from instanceof BABYLON.Size) {
  46431. dataType = Animation.ANIMATIONTYPE_SIZE;
  46432. }
  46433. if (dataType == undefined) {
  46434. return null;
  46435. }
  46436. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46437. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46438. animation.setKeys(keys);
  46439. if (easingFunction !== undefined) {
  46440. animation.setEasingFunction(easingFunction);
  46441. }
  46442. return animation;
  46443. };
  46444. /**
  46445. * Sets up an animation.
  46446. * @param property the property to animate
  46447. * @param animationType the animation type to apply
  46448. * @param easingFunction the easing function used in the animation
  46449. * @returns The created animation
  46450. */
  46451. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46452. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46453. animation.setEasingFunction(easingFunction);
  46454. return animation;
  46455. };
  46456. /**
  46457. * Create and start an animation on a node
  46458. * @param {string} name defines the name of the global animation that will be run on all nodes
  46459. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46460. * @param {string} targetProperty defines property to animate
  46461. * @param {number} framePerSecond defines the number of frame per second yo use
  46462. * @param {number} totalFrame defines the number of frames in total
  46463. * @param {any} from defines the initial value
  46464. * @param {any} to defines the final value
  46465. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46466. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46467. * @param onAnimationEnd defines the callback to call when animation end
  46468. * @returns the animatable created for this animation
  46469. */
  46470. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46471. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46472. if (!animation) {
  46473. return null;
  46474. }
  46475. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46476. };
  46477. /**
  46478. * Create and start an animation on a node and its descendants
  46479. * @param {string} name defines the name of the global animation that will be run on all nodes
  46480. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46481. * @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.
  46482. * @param {string} targetProperty defines property to animate
  46483. * @param {number} framePerSecond defines the number of frame per second yo use
  46484. * @param {number} totalFrame defines the number of frames in total
  46485. * @param {any} from defines the initial value
  46486. * @param {any} to defines the final value
  46487. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46488. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46489. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46490. * @returns the list of animatables created for all nodes
  46491. * @example https://www.babylonjs-playground.com/#MH0VLI
  46492. */
  46493. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46494. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46495. if (!animation) {
  46496. return null;
  46497. }
  46498. var scene = node.getScene();
  46499. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46500. };
  46501. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46502. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46503. if (!animation) {
  46504. return null;
  46505. }
  46506. node.animations.push(animation);
  46507. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46508. };
  46509. /**
  46510. * Transition property of the Camera to the target Value.
  46511. * @param property The property to transition
  46512. * @param targetValue The target Value of the property
  46513. * @param host The object where the property to animate belongs
  46514. * @param scene Scene used to run the animation
  46515. * @param frameRate Framerate (in frame/s) to use
  46516. * @param transition The transition type we want to use
  46517. * @param duration The duration of the animation, in milliseconds
  46518. * @param onAnimationEnd Call back trigger at the end of the animation.
  46519. */
  46520. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46521. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46522. if (duration <= 0) {
  46523. host[property] = targetValue;
  46524. if (onAnimationEnd) {
  46525. onAnimationEnd();
  46526. }
  46527. return null;
  46528. }
  46529. var endFrame = frameRate * (duration / 1000);
  46530. transition.setKeys([{
  46531. frame: 0,
  46532. value: host[property].clone ? host[property].clone() : host[property]
  46533. },
  46534. {
  46535. frame: endFrame,
  46536. value: targetValue
  46537. }]);
  46538. if (!host.animations) {
  46539. host.animations = [];
  46540. }
  46541. host.animations.push(transition);
  46542. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46543. animation.onAnimationEnd = onAnimationEnd;
  46544. return animation;
  46545. };
  46546. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46547. /**
  46548. * Return the array of runtime animations currently using this animation
  46549. */
  46550. get: function () {
  46551. return this._runtimeAnimations;
  46552. },
  46553. enumerable: true,
  46554. configurable: true
  46555. });
  46556. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46557. get: function () {
  46558. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46559. var runtimeAnimation = _a[_i];
  46560. if (!runtimeAnimation.isStopped) {
  46561. return true;
  46562. }
  46563. }
  46564. return false;
  46565. },
  46566. enumerable: true,
  46567. configurable: true
  46568. });
  46569. // Methods
  46570. /**
  46571. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46572. */
  46573. Animation.prototype.toString = function (fullDetails) {
  46574. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46575. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46576. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46577. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46578. if (fullDetails) {
  46579. ret += ", Ranges: {";
  46580. var first = true;
  46581. for (var name in this._ranges) {
  46582. if (first) {
  46583. ret += ", ";
  46584. first = false;
  46585. }
  46586. ret += name;
  46587. }
  46588. ret += "}";
  46589. }
  46590. return ret;
  46591. };
  46592. /**
  46593. * Add an event to this animation.
  46594. */
  46595. Animation.prototype.addEvent = function (event) {
  46596. this._events.push(event);
  46597. };
  46598. /**
  46599. * Remove all events found at the given frame
  46600. * @param frame
  46601. */
  46602. Animation.prototype.removeEvents = function (frame) {
  46603. for (var index = 0; index < this._events.length; index++) {
  46604. if (this._events[index].frame === frame) {
  46605. this._events.splice(index, 1);
  46606. index--;
  46607. }
  46608. }
  46609. };
  46610. Animation.prototype.getEvents = function () {
  46611. return this._events;
  46612. };
  46613. Animation.prototype.createRange = function (name, from, to) {
  46614. // check name not already in use; could happen for bones after serialized
  46615. if (!this._ranges[name]) {
  46616. this._ranges[name] = new AnimationRange(name, from, to);
  46617. }
  46618. };
  46619. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46620. if (deleteFrames === void 0) { deleteFrames = true; }
  46621. var range = this._ranges[name];
  46622. if (!range) {
  46623. return;
  46624. }
  46625. if (deleteFrames) {
  46626. var from = range.from;
  46627. var to = range.to;
  46628. // this loop MUST go high to low for multiple splices to work
  46629. for (var key = this._keys.length - 1; key >= 0; key--) {
  46630. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46631. this._keys.splice(key, 1);
  46632. }
  46633. }
  46634. }
  46635. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46636. };
  46637. Animation.prototype.getRange = function (name) {
  46638. return this._ranges[name];
  46639. };
  46640. Animation.prototype.getKeys = function () {
  46641. return this._keys;
  46642. };
  46643. Animation.prototype.getHighestFrame = function () {
  46644. var ret = 0;
  46645. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46646. if (ret < this._keys[key].frame) {
  46647. ret = this._keys[key].frame;
  46648. }
  46649. }
  46650. return ret;
  46651. };
  46652. Animation.prototype.getEasingFunction = function () {
  46653. return this._easingFunction;
  46654. };
  46655. Animation.prototype.setEasingFunction = function (easingFunction) {
  46656. this._easingFunction = easingFunction;
  46657. };
  46658. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46659. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46660. };
  46661. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46662. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46663. };
  46664. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46665. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46666. };
  46667. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46668. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46669. };
  46670. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46671. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46672. };
  46673. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46674. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46675. };
  46676. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46677. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46678. };
  46679. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46680. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46681. };
  46682. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46683. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46684. };
  46685. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46686. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46687. };
  46688. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46689. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46690. };
  46691. Animation.prototype.clone = function () {
  46692. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46693. clone.enableBlending = this.enableBlending;
  46694. clone.blendingSpeed = this.blendingSpeed;
  46695. if (this._keys) {
  46696. clone.setKeys(this._keys);
  46697. }
  46698. if (this._ranges) {
  46699. clone._ranges = {};
  46700. for (var name in this._ranges) {
  46701. var range = this._ranges[name];
  46702. if (!range) {
  46703. continue;
  46704. }
  46705. clone._ranges[name] = range.clone();
  46706. }
  46707. }
  46708. return clone;
  46709. };
  46710. Animation.prototype.setKeys = function (values) {
  46711. this._keys = values.slice(0);
  46712. };
  46713. Animation.prototype.serialize = function () {
  46714. var serializationObject = {};
  46715. serializationObject.name = this.name;
  46716. serializationObject.property = this.targetProperty;
  46717. serializationObject.framePerSecond = this.framePerSecond;
  46718. serializationObject.dataType = this.dataType;
  46719. serializationObject.loopBehavior = this.loopMode;
  46720. serializationObject.enableBlending = this.enableBlending;
  46721. serializationObject.blendingSpeed = this.blendingSpeed;
  46722. var dataType = this.dataType;
  46723. serializationObject.keys = [];
  46724. var keys = this.getKeys();
  46725. for (var index = 0; index < keys.length; index++) {
  46726. var animationKey = keys[index];
  46727. var key = {};
  46728. key.frame = animationKey.frame;
  46729. switch (dataType) {
  46730. case Animation.ANIMATIONTYPE_FLOAT:
  46731. key.values = [animationKey.value];
  46732. break;
  46733. case Animation.ANIMATIONTYPE_QUATERNION:
  46734. case Animation.ANIMATIONTYPE_MATRIX:
  46735. case Animation.ANIMATIONTYPE_VECTOR3:
  46736. case Animation.ANIMATIONTYPE_COLOR3:
  46737. key.values = animationKey.value.asArray();
  46738. break;
  46739. }
  46740. serializationObject.keys.push(key);
  46741. }
  46742. serializationObject.ranges = [];
  46743. for (var name in this._ranges) {
  46744. var source = this._ranges[name];
  46745. if (!source) {
  46746. continue;
  46747. }
  46748. var range = {};
  46749. range.name = name;
  46750. range.from = source.from;
  46751. range.to = source.to;
  46752. serializationObject.ranges.push(range);
  46753. }
  46754. return serializationObject;
  46755. };
  46756. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46757. get: function () {
  46758. return Animation._ANIMATIONTYPE_FLOAT;
  46759. },
  46760. enumerable: true,
  46761. configurable: true
  46762. });
  46763. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46764. get: function () {
  46765. return Animation._ANIMATIONTYPE_VECTOR3;
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46771. get: function () {
  46772. return Animation._ANIMATIONTYPE_VECTOR2;
  46773. },
  46774. enumerable: true,
  46775. configurable: true
  46776. });
  46777. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46778. get: function () {
  46779. return Animation._ANIMATIONTYPE_SIZE;
  46780. },
  46781. enumerable: true,
  46782. configurable: true
  46783. });
  46784. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46785. get: function () {
  46786. return Animation._ANIMATIONTYPE_QUATERNION;
  46787. },
  46788. enumerable: true,
  46789. configurable: true
  46790. });
  46791. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46792. get: function () {
  46793. return Animation._ANIMATIONTYPE_MATRIX;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46799. get: function () {
  46800. return Animation._ANIMATIONTYPE_COLOR3;
  46801. },
  46802. enumerable: true,
  46803. configurable: true
  46804. });
  46805. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46806. get: function () {
  46807. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46808. },
  46809. enumerable: true,
  46810. configurable: true
  46811. });
  46812. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46813. get: function () {
  46814. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46815. },
  46816. enumerable: true,
  46817. configurable: true
  46818. });
  46819. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46820. get: function () {
  46821. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46822. },
  46823. enumerable: true,
  46824. configurable: true
  46825. });
  46826. Animation.Parse = function (parsedAnimation) {
  46827. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46828. var dataType = parsedAnimation.dataType;
  46829. var keys = [];
  46830. var data;
  46831. var index;
  46832. if (parsedAnimation.enableBlending) {
  46833. animation.enableBlending = parsedAnimation.enableBlending;
  46834. }
  46835. if (parsedAnimation.blendingSpeed) {
  46836. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46837. }
  46838. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46839. var key = parsedAnimation.keys[index];
  46840. var inTangent;
  46841. var outTangent;
  46842. switch (dataType) {
  46843. case Animation.ANIMATIONTYPE_FLOAT:
  46844. data = key.values[0];
  46845. if (key.values.length >= 1) {
  46846. inTangent = key.values[1];
  46847. }
  46848. if (key.values.length >= 2) {
  46849. outTangent = key.values[2];
  46850. }
  46851. break;
  46852. case Animation.ANIMATIONTYPE_QUATERNION:
  46853. data = BABYLON.Quaternion.FromArray(key.values);
  46854. if (key.values.length >= 8) {
  46855. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46856. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46857. inTangent = _inTangent;
  46858. }
  46859. }
  46860. if (key.values.length >= 12) {
  46861. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46862. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46863. outTangent = _outTangent;
  46864. }
  46865. }
  46866. break;
  46867. case Animation.ANIMATIONTYPE_MATRIX:
  46868. data = BABYLON.Matrix.FromArray(key.values);
  46869. break;
  46870. case Animation.ANIMATIONTYPE_COLOR3:
  46871. data = BABYLON.Color3.FromArray(key.values);
  46872. break;
  46873. case Animation.ANIMATIONTYPE_VECTOR3:
  46874. default:
  46875. data = BABYLON.Vector3.FromArray(key.values);
  46876. break;
  46877. }
  46878. var keyData = {};
  46879. keyData.frame = key.frame;
  46880. keyData.value = data;
  46881. if (inTangent != undefined) {
  46882. keyData.inTangent = inTangent;
  46883. }
  46884. if (outTangent != undefined) {
  46885. keyData.outTangent = outTangent;
  46886. }
  46887. keys.push(keyData);
  46888. }
  46889. animation.setKeys(keys);
  46890. if (parsedAnimation.ranges) {
  46891. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46892. data = parsedAnimation.ranges[index];
  46893. animation.createRange(data.name, data.from, data.to);
  46894. }
  46895. }
  46896. return animation;
  46897. };
  46898. Animation.AppendSerializedAnimations = function (source, destination) {
  46899. if (source.animations) {
  46900. destination.animations = [];
  46901. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46902. var animation = source.animations[animationIndex];
  46903. destination.animations.push(animation.serialize());
  46904. }
  46905. }
  46906. };
  46907. Animation.AllowMatricesInterpolation = false;
  46908. // Statics
  46909. Animation._ANIMATIONTYPE_FLOAT = 0;
  46910. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46911. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46912. Animation._ANIMATIONTYPE_MATRIX = 3;
  46913. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46914. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46915. Animation._ANIMATIONTYPE_SIZE = 6;
  46916. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46917. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46918. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46919. return Animation;
  46920. }());
  46921. BABYLON.Animation = Animation;
  46922. })(BABYLON || (BABYLON = {}));
  46923. //# sourceMappingURL=babylon.animation.js.map
  46924. var BABYLON;
  46925. (function (BABYLON) {
  46926. /**
  46927. * This class defines the direct association between an animation and a target
  46928. */
  46929. var TargetedAnimation = /** @class */ (function () {
  46930. function TargetedAnimation() {
  46931. }
  46932. return TargetedAnimation;
  46933. }());
  46934. BABYLON.TargetedAnimation = TargetedAnimation;
  46935. /**
  46936. * Use this class to create coordinated animations on multiple targets
  46937. */
  46938. var AnimationGroup = /** @class */ (function () {
  46939. function AnimationGroup(name, scene) {
  46940. if (scene === void 0) { scene = null; }
  46941. this.name = name;
  46942. this._targetedAnimations = new Array();
  46943. this._animatables = new Array();
  46944. this._from = Number.MAX_VALUE;
  46945. this._to = -Number.MAX_VALUE;
  46946. this._speedRatio = 1;
  46947. this.onAnimationEndObservable = new BABYLON.Observable();
  46948. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46949. this._scene.animationGroups.push(this);
  46950. }
  46951. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46952. /**
  46953. * Define if the animations are started
  46954. */
  46955. get: function () {
  46956. return this._isStarted;
  46957. },
  46958. enumerable: true,
  46959. configurable: true
  46960. });
  46961. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46962. /**
  46963. * Gets or sets the speed ratio to use for all animations
  46964. */
  46965. get: function () {
  46966. return this._speedRatio;
  46967. },
  46968. /**
  46969. * Gets or sets the speed ratio to use for all animations
  46970. */
  46971. set: function (value) {
  46972. if (this._speedRatio === value) {
  46973. return;
  46974. }
  46975. this._speedRatio = value;
  46976. for (var index = 0; index < this._animatables.length; index++) {
  46977. var animatable = this._animatables[index];
  46978. animatable.speedRatio = this._speedRatio;
  46979. }
  46980. },
  46981. enumerable: true,
  46982. configurable: true
  46983. });
  46984. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46985. /**
  46986. * Gets the targeted animations for this animation group
  46987. */
  46988. get: function () {
  46989. return this._targetedAnimations;
  46990. },
  46991. enumerable: true,
  46992. configurable: true
  46993. });
  46994. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46995. /**
  46996. * returning the list of animatables controlled by this animation group.
  46997. */
  46998. get: function () {
  46999. return this._animatables;
  47000. },
  47001. enumerable: true,
  47002. configurable: true
  47003. });
  47004. /**
  47005. * Add an animation (with its target) in the group
  47006. * @param animation defines the animation we want to add
  47007. * @param target defines the target of the animation
  47008. * @returns the {BABYLON.TargetedAnimation} object
  47009. */
  47010. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47011. var targetedAnimation = {
  47012. animation: animation,
  47013. target: target
  47014. };
  47015. var keys = animation.getKeys();
  47016. if (this._from > keys[0].frame) {
  47017. this._from = keys[0].frame;
  47018. }
  47019. if (this._to < keys[keys.length - 1].frame) {
  47020. this._to = keys[keys.length - 1].frame;
  47021. }
  47022. this._targetedAnimations.push(targetedAnimation);
  47023. return targetedAnimation;
  47024. };
  47025. /**
  47026. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47027. * It can add constant keys at begin or end
  47028. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47029. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47030. */
  47031. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47032. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47033. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47034. beginFrame = Math.max(beginFrame, this._from);
  47035. endFrame = Math.min(endFrame, this._to);
  47036. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47037. var targetedAnimation = this._targetedAnimations[index];
  47038. var keys = targetedAnimation.animation.getKeys();
  47039. var startKey = keys[0];
  47040. var endKey = keys[keys.length - 1];
  47041. if (startKey.frame > beginFrame) {
  47042. var newKey = {
  47043. frame: beginFrame,
  47044. value: startKey.value,
  47045. inTangent: startKey.inTangent,
  47046. outTangent: startKey.outTangent,
  47047. interpolation: startKey.interpolation
  47048. };
  47049. keys.splice(0, 0, newKey);
  47050. }
  47051. if (endKey.frame < endFrame) {
  47052. var newKey = {
  47053. frame: endFrame,
  47054. value: endKey.value,
  47055. inTangent: endKey.outTangent,
  47056. outTangent: endKey.outTangent,
  47057. interpolation: endKey.interpolation
  47058. };
  47059. keys.push(newKey);
  47060. }
  47061. }
  47062. return this;
  47063. };
  47064. /**
  47065. * Start all animations on given targets
  47066. * @param loop defines if animations must loop
  47067. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47068. */
  47069. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47070. var _this = this;
  47071. if (loop === void 0) { loop = false; }
  47072. if (speedRatio === void 0) { speedRatio = 1; }
  47073. if (this._isStarted || this._targetedAnimations.length === 0) {
  47074. return this;
  47075. }
  47076. var _loop_1 = function () {
  47077. var targetedAnimation = this_1._targetedAnimations[index];
  47078. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47079. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47080. }));
  47081. };
  47082. var this_1 = this;
  47083. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47084. _loop_1();
  47085. }
  47086. this._speedRatio = speedRatio;
  47087. this._isStarted = true;
  47088. return this;
  47089. };
  47090. /**
  47091. * Pause all animations
  47092. */
  47093. AnimationGroup.prototype.pause = function () {
  47094. if (!this._isStarted) {
  47095. return this;
  47096. }
  47097. for (var index = 0; index < this._animatables.length; index++) {
  47098. var animatable = this._animatables[index];
  47099. animatable.pause();
  47100. }
  47101. return this;
  47102. };
  47103. /**
  47104. * Play all animations to initial state
  47105. * This function will start() the animations if they were not started or will restart() them if they were paused
  47106. * @param loop defines if animations must loop
  47107. */
  47108. AnimationGroup.prototype.play = function (loop) {
  47109. if (this.isStarted) {
  47110. if (loop !== undefined) {
  47111. for (var index = 0; index < this._animatables.length; index++) {
  47112. var animatable = this._animatables[index];
  47113. animatable.loopAnimation = loop;
  47114. }
  47115. }
  47116. this.restart();
  47117. }
  47118. else {
  47119. this.start(loop, this._speedRatio);
  47120. }
  47121. return this;
  47122. };
  47123. /**
  47124. * Reset all animations to initial state
  47125. */
  47126. AnimationGroup.prototype.reset = function () {
  47127. if (!this._isStarted) {
  47128. return this;
  47129. }
  47130. for (var index = 0; index < this._animatables.length; index++) {
  47131. var animatable = this._animatables[index];
  47132. animatable.reset();
  47133. }
  47134. return this;
  47135. };
  47136. /**
  47137. * Restart animations from key 0
  47138. */
  47139. AnimationGroup.prototype.restart = function () {
  47140. if (!this._isStarted) {
  47141. return this;
  47142. }
  47143. for (var index = 0; index < this._animatables.length; index++) {
  47144. var animatable = this._animatables[index];
  47145. animatable.restart();
  47146. }
  47147. return this;
  47148. };
  47149. /**
  47150. * Stop all animations
  47151. */
  47152. AnimationGroup.prototype.stop = function () {
  47153. if (!this._isStarted) {
  47154. return this;
  47155. }
  47156. for (var index = 0; index < this._animatables.length; index++) {
  47157. var animatable = this._animatables[index];
  47158. animatable.stop();
  47159. }
  47160. this._isStarted = false;
  47161. return this;
  47162. };
  47163. /**
  47164. * Goes to a specific frame in this animation group
  47165. *
  47166. * @param frame the frame number to go to
  47167. * @return the animationGroup
  47168. */
  47169. AnimationGroup.prototype.goToFrame = function (frame) {
  47170. if (!this._isStarted) {
  47171. return this;
  47172. }
  47173. for (var index = 0; index < this._animatables.length; index++) {
  47174. var animatable = this._animatables[index];
  47175. animatable.goToFrame(frame);
  47176. }
  47177. return this;
  47178. };
  47179. /**
  47180. * Dispose all associated resources
  47181. */
  47182. AnimationGroup.prototype.dispose = function () {
  47183. this._targetedAnimations = [];
  47184. this._animatables = [];
  47185. var index = this._scene.animationGroups.indexOf(this);
  47186. if (index > -1) {
  47187. this._scene.animationGroups.splice(index, 1);
  47188. }
  47189. };
  47190. return AnimationGroup;
  47191. }());
  47192. BABYLON.AnimationGroup = AnimationGroup;
  47193. })(BABYLON || (BABYLON = {}));
  47194. //# sourceMappingURL=babylon.animationGroup.js.map
  47195. var BABYLON;
  47196. (function (BABYLON) {
  47197. var RuntimeAnimation = /** @class */ (function () {
  47198. function RuntimeAnimation(target, animation) {
  47199. this._offsetsCache = {};
  47200. this._highLimitsCache = {};
  47201. this._stopped = false;
  47202. this._blendingFactor = 0;
  47203. this._ratioOffset = 0;
  47204. this._animation = animation;
  47205. this._target = target;
  47206. animation._runtimeAnimations.push(this);
  47207. }
  47208. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47209. get: function () {
  47210. return this._animation;
  47211. },
  47212. enumerable: true,
  47213. configurable: true
  47214. });
  47215. RuntimeAnimation.prototype.reset = function () {
  47216. this._offsetsCache = {};
  47217. this._highLimitsCache = {};
  47218. this.currentFrame = 0;
  47219. this._blendingFactor = 0;
  47220. this._originalBlendValue = null;
  47221. };
  47222. RuntimeAnimation.prototype.isStopped = function () {
  47223. return this._stopped;
  47224. };
  47225. RuntimeAnimation.prototype.dispose = function () {
  47226. var index = this._animation.runtimeAnimations.indexOf(this);
  47227. if (index > -1) {
  47228. this._animation.runtimeAnimations.splice(index, 1);
  47229. }
  47230. };
  47231. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47232. if (typeof value === "function") {
  47233. return value();
  47234. }
  47235. return value;
  47236. };
  47237. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47238. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47239. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47240. }
  47241. this.currentFrame = currentFrame;
  47242. var keys = this._animation.getKeys();
  47243. // Try to get a hash to find the right key
  47244. 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));
  47245. if (keys[startKeyIndex].frame >= currentFrame) {
  47246. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47247. startKeyIndex--;
  47248. }
  47249. }
  47250. for (var key = startKeyIndex; key < keys.length; key++) {
  47251. var endKey = keys[key + 1];
  47252. if (endKey.frame >= currentFrame) {
  47253. var startKey = keys[key];
  47254. var startValue = this._getKeyValue(startKey.value);
  47255. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47256. return startValue;
  47257. }
  47258. var endValue = this._getKeyValue(endKey.value);
  47259. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47260. var frameDelta = endKey.frame - startKey.frame;
  47261. // gradient : percent of currentFrame between the frame inf and the frame sup
  47262. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47263. // check for easingFunction and correction of gradient
  47264. var easingFunction = this._animation.getEasingFunction();
  47265. if (easingFunction != null) {
  47266. gradient = easingFunction.ease(gradient);
  47267. }
  47268. switch (this._animation.dataType) {
  47269. // Float
  47270. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47271. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47272. switch (loopMode) {
  47273. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47274. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47275. return floatValue;
  47276. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47277. return offsetValue * repeatCount + floatValue;
  47278. }
  47279. break;
  47280. // Quaternion
  47281. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47282. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47283. switch (loopMode) {
  47284. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47285. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47286. return quatValue;
  47287. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47288. return quatValue.add(offsetValue.scale(repeatCount));
  47289. }
  47290. return quatValue;
  47291. // Vector3
  47292. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47293. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47294. switch (loopMode) {
  47295. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47296. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47297. return vec3Value;
  47298. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47299. return vec3Value.add(offsetValue.scale(repeatCount));
  47300. }
  47301. // Vector2
  47302. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47303. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47304. switch (loopMode) {
  47305. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47306. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47307. return vec2Value;
  47308. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47309. return vec2Value.add(offsetValue.scale(repeatCount));
  47310. }
  47311. // Size
  47312. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47313. switch (loopMode) {
  47314. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47315. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47316. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47317. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47318. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47319. }
  47320. // Color3
  47321. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47322. switch (loopMode) {
  47323. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47324. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47325. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47326. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47327. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47328. }
  47329. // Matrix
  47330. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47331. switch (loopMode) {
  47332. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47333. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47334. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47335. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47336. }
  47337. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47338. return startValue;
  47339. }
  47340. default:
  47341. break;
  47342. }
  47343. break;
  47344. }
  47345. }
  47346. return this._getKeyValue(keys[keys.length - 1].value);
  47347. };
  47348. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47349. if (blend === void 0) { blend = false; }
  47350. // Set value
  47351. var path;
  47352. var destination;
  47353. var targetPropertyPath = this._animation.targetPropertyPath;
  47354. if (targetPropertyPath.length > 1) {
  47355. var property = this._target[targetPropertyPath[0]];
  47356. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47357. property = property[targetPropertyPath[index]];
  47358. }
  47359. path = targetPropertyPath[targetPropertyPath.length - 1];
  47360. destination = property;
  47361. }
  47362. else {
  47363. path = targetPropertyPath[0];
  47364. destination = this._target;
  47365. }
  47366. // Blending
  47367. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47368. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47369. if (enableBlending && this._blendingFactor <= 1.0) {
  47370. if (!this._originalBlendValue) {
  47371. if (destination[path].clone) {
  47372. this._originalBlendValue = destination[path].clone();
  47373. }
  47374. else {
  47375. this._originalBlendValue = destination[path];
  47376. }
  47377. }
  47378. if (this._originalBlendValue.prototype) {
  47379. if (this._originalBlendValue.prototype.Lerp) {
  47380. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47381. }
  47382. else {
  47383. destination[path] = currentValue;
  47384. }
  47385. }
  47386. else if (this._originalBlendValue.m) {
  47387. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47388. }
  47389. else {
  47390. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47391. }
  47392. this._blendingFactor += blendingSpeed;
  47393. }
  47394. else {
  47395. destination[path] = currentValue;
  47396. }
  47397. if (this._target.markAsDirty) {
  47398. this._target.markAsDirty(this._animation.targetProperty);
  47399. }
  47400. };
  47401. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47402. if (this._target && this._target.animationPropertiesOverride) {
  47403. return this._target.animationPropertiesOverride.loopMode;
  47404. }
  47405. return this._animation.loopMode;
  47406. };
  47407. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47408. var keys = this._animation.getKeys();
  47409. if (frame < keys[0].frame) {
  47410. frame = keys[0].frame;
  47411. }
  47412. else if (frame > keys[keys.length - 1].frame) {
  47413. frame = keys[keys.length - 1].frame;
  47414. }
  47415. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47416. this.setValue(currentValue);
  47417. };
  47418. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47419. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47420. this._ratioOffset = this._previousRatio - newRatio;
  47421. };
  47422. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47423. if (blend === void 0) { blend = false; }
  47424. var targetPropertyPath = this._animation.targetPropertyPath;
  47425. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47426. this._stopped = true;
  47427. return false;
  47428. }
  47429. var returnValue = true;
  47430. var keys = this._animation.getKeys();
  47431. // Adding a start key at frame 0 if missing
  47432. if (keys[0].frame !== 0) {
  47433. var newKey = { frame: 0, value: keys[0].value };
  47434. keys.splice(0, 0, newKey);
  47435. }
  47436. // Check limits
  47437. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47438. from = keys[0].frame;
  47439. }
  47440. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47441. to = keys[keys.length - 1].frame;
  47442. }
  47443. //to and from cannot be the same key
  47444. if (from === to) {
  47445. if (from > keys[0].frame) {
  47446. from--;
  47447. }
  47448. else if (to < keys[keys.length - 1].frame) {
  47449. to++;
  47450. }
  47451. }
  47452. // Compute ratio
  47453. var range = to - from;
  47454. var offsetValue;
  47455. // ratio represents the frame delta between from and to
  47456. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47457. var highLimitValue = 0;
  47458. this._previousDelay = delay;
  47459. this._previousRatio = ratio;
  47460. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47461. returnValue = false;
  47462. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47463. }
  47464. else {
  47465. // Get max value if required
  47466. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47467. var keyOffset = to.toString() + from.toString();
  47468. if (!this._offsetsCache[keyOffset]) {
  47469. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47470. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47471. switch (this._animation.dataType) {
  47472. // Float
  47473. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47474. this._offsetsCache[keyOffset] = toValue - fromValue;
  47475. break;
  47476. // Quaternion
  47477. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47478. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47479. break;
  47480. // Vector3
  47481. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47482. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47483. // Vector2
  47484. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47485. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47486. // Size
  47487. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47488. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47489. // Color3
  47490. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47491. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47492. default:
  47493. break;
  47494. }
  47495. this._highLimitsCache[keyOffset] = toValue;
  47496. }
  47497. highLimitValue = this._highLimitsCache[keyOffset];
  47498. offsetValue = this._offsetsCache[keyOffset];
  47499. }
  47500. }
  47501. if (offsetValue === undefined) {
  47502. switch (this._animation.dataType) {
  47503. // Float
  47504. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47505. offsetValue = 0;
  47506. break;
  47507. // Quaternion
  47508. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47509. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47510. break;
  47511. // Vector3
  47512. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47513. offsetValue = BABYLON.Vector3.Zero();
  47514. break;
  47515. // Vector2
  47516. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47517. offsetValue = BABYLON.Vector2.Zero();
  47518. break;
  47519. // Size
  47520. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47521. offsetValue = BABYLON.Size.Zero();
  47522. break;
  47523. // Color3
  47524. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47525. offsetValue = BABYLON.Color3.Black();
  47526. }
  47527. }
  47528. // Compute value
  47529. var repeatCount = (ratio / range) >> 0;
  47530. var currentFrame = returnValue ? from + ratio % range : to;
  47531. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47532. // Set value
  47533. this.setValue(currentValue);
  47534. // Check events
  47535. var events = this._animation.getEvents();
  47536. for (var index = 0; index < events.length; index++) {
  47537. // Make sure current frame has passed event frame and that event frame is within the current range
  47538. // Also, handle both forward and reverse animations
  47539. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47540. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47541. var event = events[index];
  47542. if (!event.isDone) {
  47543. // If event should be done only once, remove it.
  47544. if (event.onlyOnce) {
  47545. events.splice(index, 1);
  47546. index--;
  47547. }
  47548. event.isDone = true;
  47549. event.action();
  47550. } // Don't do anything if the event has already be done.
  47551. }
  47552. else if (events[index].isDone && !events[index].onlyOnce) {
  47553. // reset event, the animation is looping
  47554. events[index].isDone = false;
  47555. }
  47556. }
  47557. if (!returnValue) {
  47558. this._stopped = true;
  47559. }
  47560. return returnValue;
  47561. };
  47562. return RuntimeAnimation;
  47563. }());
  47564. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47565. })(BABYLON || (BABYLON = {}));
  47566. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47567. var BABYLON;
  47568. (function (BABYLON) {
  47569. var Animatable = /** @class */ (function () {
  47570. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47571. if (fromFrame === void 0) { fromFrame = 0; }
  47572. if (toFrame === void 0) { toFrame = 100; }
  47573. if (loopAnimation === void 0) { loopAnimation = false; }
  47574. if (speedRatio === void 0) { speedRatio = 1.0; }
  47575. this.target = target;
  47576. this.fromFrame = fromFrame;
  47577. this.toFrame = toFrame;
  47578. this.loopAnimation = loopAnimation;
  47579. this.onAnimationEnd = onAnimationEnd;
  47580. this._localDelayOffset = null;
  47581. this._pausedDelay = null;
  47582. this._runtimeAnimations = new Array();
  47583. this._paused = false;
  47584. this._speedRatio = 1;
  47585. this.animationStarted = false;
  47586. if (animations) {
  47587. this.appendAnimations(target, animations);
  47588. }
  47589. this._speedRatio = speedRatio;
  47590. this._scene = scene;
  47591. scene._activeAnimatables.push(this);
  47592. }
  47593. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47594. get: function () {
  47595. return this._speedRatio;
  47596. },
  47597. set: function (value) {
  47598. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47599. var animation = this._runtimeAnimations[index];
  47600. animation._prepareForSpeedRatioChange(value);
  47601. }
  47602. this._speedRatio = value;
  47603. },
  47604. enumerable: true,
  47605. configurable: true
  47606. });
  47607. // Methods
  47608. Animatable.prototype.getAnimations = function () {
  47609. return this._runtimeAnimations;
  47610. };
  47611. Animatable.prototype.appendAnimations = function (target, animations) {
  47612. for (var index = 0; index < animations.length; index++) {
  47613. var animation = animations[index];
  47614. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47615. }
  47616. };
  47617. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47618. var runtimeAnimations = this._runtimeAnimations;
  47619. for (var index = 0; index < runtimeAnimations.length; index++) {
  47620. if (runtimeAnimations[index].animation.targetProperty === property) {
  47621. return runtimeAnimations[index].animation;
  47622. }
  47623. }
  47624. return null;
  47625. };
  47626. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47627. var runtimeAnimations = this._runtimeAnimations;
  47628. for (var index = 0; index < runtimeAnimations.length; index++) {
  47629. if (runtimeAnimations[index].animation.targetProperty === property) {
  47630. return runtimeAnimations[index];
  47631. }
  47632. }
  47633. return null;
  47634. };
  47635. Animatable.prototype.reset = function () {
  47636. var runtimeAnimations = this._runtimeAnimations;
  47637. for (var index = 0; index < runtimeAnimations.length; index++) {
  47638. runtimeAnimations[index].reset();
  47639. }
  47640. // Reset to original value
  47641. for (index = 0; index < runtimeAnimations.length; index++) {
  47642. var animation = runtimeAnimations[index];
  47643. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47644. }
  47645. this._localDelayOffset = null;
  47646. this._pausedDelay = null;
  47647. };
  47648. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47649. var runtimeAnimations = this._runtimeAnimations;
  47650. for (var index = 0; index < runtimeAnimations.length; index++) {
  47651. runtimeAnimations[index].animation.enableBlending = true;
  47652. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47653. }
  47654. };
  47655. Animatable.prototype.disableBlending = function () {
  47656. var runtimeAnimations = this._runtimeAnimations;
  47657. for (var index = 0; index < runtimeAnimations.length; index++) {
  47658. runtimeAnimations[index].animation.enableBlending = false;
  47659. }
  47660. };
  47661. Animatable.prototype.goToFrame = function (frame) {
  47662. var runtimeAnimations = this._runtimeAnimations;
  47663. if (runtimeAnimations[0]) {
  47664. var fps = runtimeAnimations[0].animation.framePerSecond;
  47665. var currentFrame = runtimeAnimations[0].currentFrame;
  47666. var adjustTime = frame - currentFrame;
  47667. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47668. if (this._localDelayOffset === null) {
  47669. this._localDelayOffset = 0;
  47670. }
  47671. this._localDelayOffset -= delay;
  47672. }
  47673. for (var index = 0; index < runtimeAnimations.length; index++) {
  47674. runtimeAnimations[index].goToFrame(frame);
  47675. }
  47676. };
  47677. Animatable.prototype.pause = function () {
  47678. if (this._paused) {
  47679. return;
  47680. }
  47681. this._paused = true;
  47682. };
  47683. Animatable.prototype.restart = function () {
  47684. this._paused = false;
  47685. };
  47686. Animatable.prototype.stop = function (animationName) {
  47687. if (animationName) {
  47688. var idx = this._scene._activeAnimatables.indexOf(this);
  47689. if (idx > -1) {
  47690. var runtimeAnimations = this._runtimeAnimations;
  47691. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47692. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47693. continue;
  47694. }
  47695. runtimeAnimations[index].dispose();
  47696. runtimeAnimations.splice(index, 1);
  47697. }
  47698. if (runtimeAnimations.length == 0) {
  47699. this._scene._activeAnimatables.splice(idx, 1);
  47700. if (this.onAnimationEnd) {
  47701. this.onAnimationEnd();
  47702. }
  47703. }
  47704. }
  47705. }
  47706. else {
  47707. var index = this._scene._activeAnimatables.indexOf(this);
  47708. if (index > -1) {
  47709. this._scene._activeAnimatables.splice(index, 1);
  47710. var runtimeAnimations = this._runtimeAnimations;
  47711. for (var index = 0; index < runtimeAnimations.length; index++) {
  47712. runtimeAnimations[index].dispose();
  47713. }
  47714. if (this.onAnimationEnd) {
  47715. this.onAnimationEnd();
  47716. }
  47717. }
  47718. }
  47719. };
  47720. Animatable.prototype._animate = function (delay) {
  47721. if (this._paused) {
  47722. this.animationStarted = false;
  47723. if (this._pausedDelay === null) {
  47724. this._pausedDelay = delay;
  47725. }
  47726. return true;
  47727. }
  47728. if (this._localDelayOffset === null) {
  47729. this._localDelayOffset = delay;
  47730. this._pausedDelay = null;
  47731. }
  47732. else if (this._pausedDelay !== null) {
  47733. this._localDelayOffset += delay - this._pausedDelay;
  47734. this._pausedDelay = null;
  47735. }
  47736. // Animating
  47737. var running = false;
  47738. var runtimeAnimations = this._runtimeAnimations;
  47739. var index;
  47740. for (index = 0; index < runtimeAnimations.length; index++) {
  47741. var animation = runtimeAnimations[index];
  47742. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47743. running = running || isRunning;
  47744. }
  47745. this.animationStarted = running;
  47746. if (!running) {
  47747. // Remove from active animatables
  47748. index = this._scene._activeAnimatables.indexOf(this);
  47749. this._scene._activeAnimatables.splice(index, 1);
  47750. // Dispose all runtime animations
  47751. for (index = 0; index < runtimeAnimations.length; index++) {
  47752. runtimeAnimations[index].dispose();
  47753. }
  47754. }
  47755. if (!running && this.onAnimationEnd) {
  47756. this.onAnimationEnd();
  47757. this.onAnimationEnd = null;
  47758. }
  47759. return running;
  47760. };
  47761. return Animatable;
  47762. }());
  47763. BABYLON.Animatable = Animatable;
  47764. })(BABYLON || (BABYLON = {}));
  47765. //# sourceMappingURL=babylon.animatable.js.map
  47766. var BABYLON;
  47767. (function (BABYLON) {
  47768. var EasingFunction = /** @class */ (function () {
  47769. function EasingFunction() {
  47770. // Properties
  47771. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47772. }
  47773. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47774. get: function () {
  47775. return EasingFunction._EASINGMODE_EASEIN;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47781. get: function () {
  47782. return EasingFunction._EASINGMODE_EASEOUT;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47788. get: function () {
  47789. return EasingFunction._EASINGMODE_EASEINOUT;
  47790. },
  47791. enumerable: true,
  47792. configurable: true
  47793. });
  47794. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47795. var n = Math.min(Math.max(easingMode, 0), 2);
  47796. this._easingMode = n;
  47797. };
  47798. EasingFunction.prototype.getEasingMode = function () {
  47799. return this._easingMode;
  47800. };
  47801. EasingFunction.prototype.easeInCore = function (gradient) {
  47802. throw new Error('You must implement this method');
  47803. };
  47804. EasingFunction.prototype.ease = function (gradient) {
  47805. switch (this._easingMode) {
  47806. case EasingFunction.EASINGMODE_EASEIN:
  47807. return this.easeInCore(gradient);
  47808. case EasingFunction.EASINGMODE_EASEOUT:
  47809. return (1 - this.easeInCore(1 - gradient));
  47810. }
  47811. if (gradient >= 0.5) {
  47812. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47813. }
  47814. return (this.easeInCore(gradient * 2) * 0.5);
  47815. };
  47816. //Statics
  47817. EasingFunction._EASINGMODE_EASEIN = 0;
  47818. EasingFunction._EASINGMODE_EASEOUT = 1;
  47819. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47820. return EasingFunction;
  47821. }());
  47822. BABYLON.EasingFunction = EasingFunction;
  47823. var CircleEase = /** @class */ (function (_super) {
  47824. __extends(CircleEase, _super);
  47825. function CircleEase() {
  47826. return _super !== null && _super.apply(this, arguments) || this;
  47827. }
  47828. CircleEase.prototype.easeInCore = function (gradient) {
  47829. gradient = Math.max(0, Math.min(1, gradient));
  47830. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47831. };
  47832. return CircleEase;
  47833. }(EasingFunction));
  47834. BABYLON.CircleEase = CircleEase;
  47835. var BackEase = /** @class */ (function (_super) {
  47836. __extends(BackEase, _super);
  47837. function BackEase(amplitude) {
  47838. if (amplitude === void 0) { amplitude = 1; }
  47839. var _this = _super.call(this) || this;
  47840. _this.amplitude = amplitude;
  47841. return _this;
  47842. }
  47843. BackEase.prototype.easeInCore = function (gradient) {
  47844. var num = Math.max(0, this.amplitude);
  47845. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47846. };
  47847. return BackEase;
  47848. }(EasingFunction));
  47849. BABYLON.BackEase = BackEase;
  47850. var BounceEase = /** @class */ (function (_super) {
  47851. __extends(BounceEase, _super);
  47852. function BounceEase(bounces, bounciness) {
  47853. if (bounces === void 0) { bounces = 3; }
  47854. if (bounciness === void 0) { bounciness = 2; }
  47855. var _this = _super.call(this) || this;
  47856. _this.bounces = bounces;
  47857. _this.bounciness = bounciness;
  47858. return _this;
  47859. }
  47860. BounceEase.prototype.easeInCore = function (gradient) {
  47861. var y = Math.max(0.0, this.bounces);
  47862. var bounciness = this.bounciness;
  47863. if (bounciness <= 1.0) {
  47864. bounciness = 1.001;
  47865. }
  47866. var num9 = Math.pow(bounciness, y);
  47867. var num5 = 1.0 - bounciness;
  47868. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47869. var num15 = gradient * num4;
  47870. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47871. var num3 = Math.floor(num65);
  47872. var num13 = num3 + 1.0;
  47873. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47874. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47875. var num7 = (num8 + num12) * 0.5;
  47876. var num6 = gradient - num7;
  47877. var num2 = num7 - num8;
  47878. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47879. };
  47880. return BounceEase;
  47881. }(EasingFunction));
  47882. BABYLON.BounceEase = BounceEase;
  47883. var CubicEase = /** @class */ (function (_super) {
  47884. __extends(CubicEase, _super);
  47885. function CubicEase() {
  47886. return _super !== null && _super.apply(this, arguments) || this;
  47887. }
  47888. CubicEase.prototype.easeInCore = function (gradient) {
  47889. return (gradient * gradient * gradient);
  47890. };
  47891. return CubicEase;
  47892. }(EasingFunction));
  47893. BABYLON.CubicEase = CubicEase;
  47894. var ElasticEase = /** @class */ (function (_super) {
  47895. __extends(ElasticEase, _super);
  47896. function ElasticEase(oscillations, springiness) {
  47897. if (oscillations === void 0) { oscillations = 3; }
  47898. if (springiness === void 0) { springiness = 3; }
  47899. var _this = _super.call(this) || this;
  47900. _this.oscillations = oscillations;
  47901. _this.springiness = springiness;
  47902. return _this;
  47903. }
  47904. ElasticEase.prototype.easeInCore = function (gradient) {
  47905. var num2;
  47906. var num3 = Math.max(0.0, this.oscillations);
  47907. var num = Math.max(0.0, this.springiness);
  47908. if (num == 0) {
  47909. num2 = gradient;
  47910. }
  47911. else {
  47912. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47913. }
  47914. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47915. };
  47916. return ElasticEase;
  47917. }(EasingFunction));
  47918. BABYLON.ElasticEase = ElasticEase;
  47919. var ExponentialEase = /** @class */ (function (_super) {
  47920. __extends(ExponentialEase, _super);
  47921. function ExponentialEase(exponent) {
  47922. if (exponent === void 0) { exponent = 2; }
  47923. var _this = _super.call(this) || this;
  47924. _this.exponent = exponent;
  47925. return _this;
  47926. }
  47927. ExponentialEase.prototype.easeInCore = function (gradient) {
  47928. if (this.exponent <= 0) {
  47929. return gradient;
  47930. }
  47931. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47932. };
  47933. return ExponentialEase;
  47934. }(EasingFunction));
  47935. BABYLON.ExponentialEase = ExponentialEase;
  47936. var PowerEase = /** @class */ (function (_super) {
  47937. __extends(PowerEase, _super);
  47938. function PowerEase(power) {
  47939. if (power === void 0) { power = 2; }
  47940. var _this = _super.call(this) || this;
  47941. _this.power = power;
  47942. return _this;
  47943. }
  47944. PowerEase.prototype.easeInCore = function (gradient) {
  47945. var y = Math.max(0.0, this.power);
  47946. return Math.pow(gradient, y);
  47947. };
  47948. return PowerEase;
  47949. }(EasingFunction));
  47950. BABYLON.PowerEase = PowerEase;
  47951. var QuadraticEase = /** @class */ (function (_super) {
  47952. __extends(QuadraticEase, _super);
  47953. function QuadraticEase() {
  47954. return _super !== null && _super.apply(this, arguments) || this;
  47955. }
  47956. QuadraticEase.prototype.easeInCore = function (gradient) {
  47957. return (gradient * gradient);
  47958. };
  47959. return QuadraticEase;
  47960. }(EasingFunction));
  47961. BABYLON.QuadraticEase = QuadraticEase;
  47962. var QuarticEase = /** @class */ (function (_super) {
  47963. __extends(QuarticEase, _super);
  47964. function QuarticEase() {
  47965. return _super !== null && _super.apply(this, arguments) || this;
  47966. }
  47967. QuarticEase.prototype.easeInCore = function (gradient) {
  47968. return (gradient * gradient * gradient * gradient);
  47969. };
  47970. return QuarticEase;
  47971. }(EasingFunction));
  47972. BABYLON.QuarticEase = QuarticEase;
  47973. var QuinticEase = /** @class */ (function (_super) {
  47974. __extends(QuinticEase, _super);
  47975. function QuinticEase() {
  47976. return _super !== null && _super.apply(this, arguments) || this;
  47977. }
  47978. QuinticEase.prototype.easeInCore = function (gradient) {
  47979. return (gradient * gradient * gradient * gradient * gradient);
  47980. };
  47981. return QuinticEase;
  47982. }(EasingFunction));
  47983. BABYLON.QuinticEase = QuinticEase;
  47984. var SineEase = /** @class */ (function (_super) {
  47985. __extends(SineEase, _super);
  47986. function SineEase() {
  47987. return _super !== null && _super.apply(this, arguments) || this;
  47988. }
  47989. SineEase.prototype.easeInCore = function (gradient) {
  47990. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47991. };
  47992. return SineEase;
  47993. }(EasingFunction));
  47994. BABYLON.SineEase = SineEase;
  47995. var BezierCurveEase = /** @class */ (function (_super) {
  47996. __extends(BezierCurveEase, _super);
  47997. function BezierCurveEase(x1, y1, x2, y2) {
  47998. if (x1 === void 0) { x1 = 0; }
  47999. if (y1 === void 0) { y1 = 0; }
  48000. if (x2 === void 0) { x2 = 1; }
  48001. if (y2 === void 0) { y2 = 1; }
  48002. var _this = _super.call(this) || this;
  48003. _this.x1 = x1;
  48004. _this.y1 = y1;
  48005. _this.x2 = x2;
  48006. _this.y2 = y2;
  48007. return _this;
  48008. }
  48009. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48010. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48011. };
  48012. return BezierCurveEase;
  48013. }(EasingFunction));
  48014. BABYLON.BezierCurveEase = BezierCurveEase;
  48015. })(BABYLON || (BABYLON = {}));
  48016. //# sourceMappingURL=babylon.easing.js.map
  48017. var BABYLON;
  48018. (function (BABYLON) {
  48019. var Condition = /** @class */ (function () {
  48020. function Condition(actionManager) {
  48021. this._actionManager = actionManager;
  48022. }
  48023. Condition.prototype.isValid = function () {
  48024. return true;
  48025. };
  48026. Condition.prototype._getProperty = function (propertyPath) {
  48027. return this._actionManager._getProperty(propertyPath);
  48028. };
  48029. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48030. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48031. };
  48032. Condition.prototype.serialize = function () {
  48033. };
  48034. Condition.prototype._serialize = function (serializedCondition) {
  48035. return {
  48036. type: 2,
  48037. children: [],
  48038. name: serializedCondition.name,
  48039. properties: serializedCondition.properties
  48040. };
  48041. };
  48042. return Condition;
  48043. }());
  48044. BABYLON.Condition = Condition;
  48045. var ValueCondition = /** @class */ (function (_super) {
  48046. __extends(ValueCondition, _super);
  48047. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48048. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48049. var _this = _super.call(this, actionManager) || this;
  48050. _this.propertyPath = propertyPath;
  48051. _this.value = value;
  48052. _this.operator = operator;
  48053. _this._target = target;
  48054. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48055. _this._property = _this._getProperty(_this.propertyPath);
  48056. return _this;
  48057. }
  48058. Object.defineProperty(ValueCondition, "IsEqual", {
  48059. get: function () {
  48060. return ValueCondition._IsEqual;
  48061. },
  48062. enumerable: true,
  48063. configurable: true
  48064. });
  48065. Object.defineProperty(ValueCondition, "IsDifferent", {
  48066. get: function () {
  48067. return ValueCondition._IsDifferent;
  48068. },
  48069. enumerable: true,
  48070. configurable: true
  48071. });
  48072. Object.defineProperty(ValueCondition, "IsGreater", {
  48073. get: function () {
  48074. return ValueCondition._IsGreater;
  48075. },
  48076. enumerable: true,
  48077. configurable: true
  48078. });
  48079. Object.defineProperty(ValueCondition, "IsLesser", {
  48080. get: function () {
  48081. return ValueCondition._IsLesser;
  48082. },
  48083. enumerable: true,
  48084. configurable: true
  48085. });
  48086. // Methods
  48087. ValueCondition.prototype.isValid = function () {
  48088. switch (this.operator) {
  48089. case ValueCondition.IsGreater:
  48090. return this._effectiveTarget[this._property] > this.value;
  48091. case ValueCondition.IsLesser:
  48092. return this._effectiveTarget[this._property] < this.value;
  48093. case ValueCondition.IsEqual:
  48094. case ValueCondition.IsDifferent:
  48095. var check;
  48096. if (this.value.equals) {
  48097. check = this.value.equals(this._effectiveTarget[this._property]);
  48098. }
  48099. else {
  48100. check = this.value === this._effectiveTarget[this._property];
  48101. }
  48102. return this.operator === ValueCondition.IsEqual ? check : !check;
  48103. }
  48104. return false;
  48105. };
  48106. ValueCondition.prototype.serialize = function () {
  48107. return this._serialize({
  48108. name: "ValueCondition",
  48109. properties: [
  48110. BABYLON.Action._GetTargetProperty(this._target),
  48111. { name: "propertyPath", value: this.propertyPath },
  48112. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48113. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48114. ]
  48115. });
  48116. };
  48117. ValueCondition.GetOperatorName = function (operator) {
  48118. switch (operator) {
  48119. case ValueCondition._IsEqual: return "IsEqual";
  48120. case ValueCondition._IsDifferent: return "IsDifferent";
  48121. case ValueCondition._IsGreater: return "IsGreater";
  48122. case ValueCondition._IsLesser: return "IsLesser";
  48123. default: return "";
  48124. }
  48125. };
  48126. // Statics
  48127. ValueCondition._IsEqual = 0;
  48128. ValueCondition._IsDifferent = 1;
  48129. ValueCondition._IsGreater = 2;
  48130. ValueCondition._IsLesser = 3;
  48131. return ValueCondition;
  48132. }(Condition));
  48133. BABYLON.ValueCondition = ValueCondition;
  48134. var PredicateCondition = /** @class */ (function (_super) {
  48135. __extends(PredicateCondition, _super);
  48136. function PredicateCondition(actionManager, predicate) {
  48137. var _this = _super.call(this, actionManager) || this;
  48138. _this.predicate = predicate;
  48139. return _this;
  48140. }
  48141. PredicateCondition.prototype.isValid = function () {
  48142. return this.predicate();
  48143. };
  48144. return PredicateCondition;
  48145. }(Condition));
  48146. BABYLON.PredicateCondition = PredicateCondition;
  48147. var StateCondition = /** @class */ (function (_super) {
  48148. __extends(StateCondition, _super);
  48149. function StateCondition(actionManager, target, value) {
  48150. var _this = _super.call(this, actionManager) || this;
  48151. _this.value = value;
  48152. _this._target = target;
  48153. return _this;
  48154. }
  48155. // Methods
  48156. StateCondition.prototype.isValid = function () {
  48157. return this._target.state === this.value;
  48158. };
  48159. StateCondition.prototype.serialize = function () {
  48160. return this._serialize({
  48161. name: "StateCondition",
  48162. properties: [
  48163. BABYLON.Action._GetTargetProperty(this._target),
  48164. { name: "value", value: this.value }
  48165. ]
  48166. });
  48167. };
  48168. return StateCondition;
  48169. }(Condition));
  48170. BABYLON.StateCondition = StateCondition;
  48171. })(BABYLON || (BABYLON = {}));
  48172. //# sourceMappingURL=babylon.condition.js.map
  48173. var BABYLON;
  48174. (function (BABYLON) {
  48175. var Action = /** @class */ (function () {
  48176. function Action(triggerOptions, condition) {
  48177. this.triggerOptions = triggerOptions;
  48178. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48179. if (triggerOptions.parameter) {
  48180. this.trigger = triggerOptions.trigger;
  48181. this._triggerParameter = triggerOptions.parameter;
  48182. }
  48183. else {
  48184. this.trigger = triggerOptions;
  48185. }
  48186. this._nextActiveAction = this;
  48187. this._condition = condition;
  48188. }
  48189. // Methods
  48190. Action.prototype._prepare = function () {
  48191. };
  48192. Action.prototype.getTriggerParameter = function () {
  48193. return this._triggerParameter;
  48194. };
  48195. Action.prototype._executeCurrent = function (evt) {
  48196. if (this._nextActiveAction._condition) {
  48197. var condition = this._nextActiveAction._condition;
  48198. var currentRenderId = this._actionManager.getScene().getRenderId();
  48199. // We cache the current evaluation for the current frame
  48200. if (condition._evaluationId === currentRenderId) {
  48201. if (!condition._currentResult) {
  48202. return;
  48203. }
  48204. }
  48205. else {
  48206. condition._evaluationId = currentRenderId;
  48207. if (!condition.isValid()) {
  48208. condition._currentResult = false;
  48209. return;
  48210. }
  48211. condition._currentResult = true;
  48212. }
  48213. }
  48214. this.onBeforeExecuteObservable.notifyObservers(this);
  48215. this._nextActiveAction.execute(evt);
  48216. this.skipToNextActiveAction();
  48217. };
  48218. Action.prototype.execute = function (evt) {
  48219. };
  48220. Action.prototype.skipToNextActiveAction = function () {
  48221. if (this._nextActiveAction._child) {
  48222. if (!this._nextActiveAction._child._actionManager) {
  48223. this._nextActiveAction._child._actionManager = this._actionManager;
  48224. }
  48225. this._nextActiveAction = this._nextActiveAction._child;
  48226. }
  48227. else {
  48228. this._nextActiveAction = this;
  48229. }
  48230. };
  48231. Action.prototype.then = function (action) {
  48232. this._child = action;
  48233. action._actionManager = this._actionManager;
  48234. action._prepare();
  48235. return action;
  48236. };
  48237. Action.prototype._getProperty = function (propertyPath) {
  48238. return this._actionManager._getProperty(propertyPath);
  48239. };
  48240. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48241. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48242. };
  48243. Action.prototype.serialize = function (parent) {
  48244. };
  48245. // Called by BABYLON.Action objects in serialize(...). Internal use
  48246. Action.prototype._serialize = function (serializedAction, parent) {
  48247. var serializationObject = {
  48248. type: 1,
  48249. children: [],
  48250. name: serializedAction.name,
  48251. properties: serializedAction.properties || []
  48252. };
  48253. // Serialize child
  48254. if (this._child) {
  48255. this._child.serialize(serializationObject);
  48256. }
  48257. // Check if "this" has a condition
  48258. if (this._condition) {
  48259. var serializedCondition = this._condition.serialize();
  48260. serializedCondition.children.push(serializationObject);
  48261. if (parent) {
  48262. parent.children.push(serializedCondition);
  48263. }
  48264. return serializedCondition;
  48265. }
  48266. if (parent) {
  48267. parent.children.push(serializationObject);
  48268. }
  48269. return serializationObject;
  48270. };
  48271. Action._SerializeValueAsString = function (value) {
  48272. if (typeof value === "number") {
  48273. return value.toString();
  48274. }
  48275. if (typeof value === "boolean") {
  48276. return value ? "true" : "false";
  48277. }
  48278. if (value instanceof BABYLON.Vector2) {
  48279. return value.x + ", " + value.y;
  48280. }
  48281. if (value instanceof BABYLON.Vector3) {
  48282. return value.x + ", " + value.y + ", " + value.z;
  48283. }
  48284. if (value instanceof BABYLON.Color3) {
  48285. return value.r + ", " + value.g + ", " + value.b;
  48286. }
  48287. if (value instanceof BABYLON.Color4) {
  48288. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48289. }
  48290. return value; // string
  48291. };
  48292. Action._GetTargetProperty = function (target) {
  48293. return {
  48294. name: "target",
  48295. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48296. : target instanceof BABYLON.Light ? "LightProperties"
  48297. : target instanceof BABYLON.Camera ? "CameraProperties"
  48298. : "SceneProperties",
  48299. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48300. };
  48301. };
  48302. return Action;
  48303. }());
  48304. BABYLON.Action = Action;
  48305. })(BABYLON || (BABYLON = {}));
  48306. //# sourceMappingURL=babylon.action.js.map
  48307. var BABYLON;
  48308. (function (BABYLON) {
  48309. /**
  48310. * ActionEvent is the event beint sent when an action is triggered.
  48311. */
  48312. var ActionEvent = /** @class */ (function () {
  48313. /**
  48314. * @param source The mesh or sprite that triggered the action.
  48315. * @param pointerX The X mouse cursor position at the time of the event
  48316. * @param pointerY The Y mouse cursor position at the time of the event
  48317. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48318. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48319. */
  48320. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48321. this.source = source;
  48322. this.pointerX = pointerX;
  48323. this.pointerY = pointerY;
  48324. this.meshUnderPointer = meshUnderPointer;
  48325. this.sourceEvent = sourceEvent;
  48326. this.additionalData = additionalData;
  48327. }
  48328. /**
  48329. * Helper function to auto-create an ActionEvent from a source mesh.
  48330. * @param source The source mesh that triggered the event
  48331. * @param evt {Event} The original (browser) event
  48332. */
  48333. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48334. var scene = source.getScene();
  48335. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48336. };
  48337. /**
  48338. * Helper function to auto-create an ActionEvent from a source mesh.
  48339. * @param source The source sprite that triggered the event
  48340. * @param scene Scene associated with the sprite
  48341. * @param evt {Event} The original (browser) event
  48342. */
  48343. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48344. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48345. };
  48346. /**
  48347. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48348. * @param scene the scene where the event occurred
  48349. * @param evt {Event} The original (browser) event
  48350. */
  48351. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48352. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48353. };
  48354. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48355. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48356. };
  48357. return ActionEvent;
  48358. }());
  48359. BABYLON.ActionEvent = ActionEvent;
  48360. /**
  48361. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48362. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48363. */
  48364. var ActionManager = /** @class */ (function () {
  48365. function ActionManager(scene) {
  48366. // Members
  48367. this.actions = new Array();
  48368. this.hoverCursor = '';
  48369. this._scene = scene;
  48370. scene._actionManagers.push(this);
  48371. }
  48372. Object.defineProperty(ActionManager, "NothingTrigger", {
  48373. get: function () {
  48374. return ActionManager._NothingTrigger;
  48375. },
  48376. enumerable: true,
  48377. configurable: true
  48378. });
  48379. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48380. get: function () {
  48381. return ActionManager._OnPickTrigger;
  48382. },
  48383. enumerable: true,
  48384. configurable: true
  48385. });
  48386. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48387. get: function () {
  48388. return ActionManager._OnLeftPickTrigger;
  48389. },
  48390. enumerable: true,
  48391. configurable: true
  48392. });
  48393. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48394. get: function () {
  48395. return ActionManager._OnRightPickTrigger;
  48396. },
  48397. enumerable: true,
  48398. configurable: true
  48399. });
  48400. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48401. get: function () {
  48402. return ActionManager._OnCenterPickTrigger;
  48403. },
  48404. enumerable: true,
  48405. configurable: true
  48406. });
  48407. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48408. get: function () {
  48409. return ActionManager._OnPickDownTrigger;
  48410. },
  48411. enumerable: true,
  48412. configurable: true
  48413. });
  48414. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48415. get: function () {
  48416. return ActionManager._OnDoublePickTrigger;
  48417. },
  48418. enumerable: true,
  48419. configurable: true
  48420. });
  48421. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48422. get: function () {
  48423. return ActionManager._OnPickUpTrigger;
  48424. },
  48425. enumerable: true,
  48426. configurable: true
  48427. });
  48428. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48429. /// This trigger will only be raised if you also declared a OnPickDown
  48430. get: function () {
  48431. return ActionManager._OnPickOutTrigger;
  48432. },
  48433. enumerable: true,
  48434. configurable: true
  48435. });
  48436. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48437. get: function () {
  48438. return ActionManager._OnLongPressTrigger;
  48439. },
  48440. enumerable: true,
  48441. configurable: true
  48442. });
  48443. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48444. get: function () {
  48445. return ActionManager._OnPointerOverTrigger;
  48446. },
  48447. enumerable: true,
  48448. configurable: true
  48449. });
  48450. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48451. get: function () {
  48452. return ActionManager._OnPointerOutTrigger;
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48458. get: function () {
  48459. return ActionManager._OnEveryFrameTrigger;
  48460. },
  48461. enumerable: true,
  48462. configurable: true
  48463. });
  48464. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48465. get: function () {
  48466. return ActionManager._OnIntersectionEnterTrigger;
  48467. },
  48468. enumerable: true,
  48469. configurable: true
  48470. });
  48471. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48472. get: function () {
  48473. return ActionManager._OnIntersectionExitTrigger;
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48479. get: function () {
  48480. return ActionManager._OnKeyDownTrigger;
  48481. },
  48482. enumerable: true,
  48483. configurable: true
  48484. });
  48485. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48486. get: function () {
  48487. return ActionManager._OnKeyUpTrigger;
  48488. },
  48489. enumerable: true,
  48490. configurable: true
  48491. });
  48492. // Methods
  48493. ActionManager.prototype.dispose = function () {
  48494. var index = this._scene._actionManagers.indexOf(this);
  48495. for (var i = 0; i < this.actions.length; i++) {
  48496. var action = this.actions[i];
  48497. ActionManager.Triggers[action.trigger]--;
  48498. if (ActionManager.Triggers[action.trigger] === 0) {
  48499. delete ActionManager.Triggers[action.trigger];
  48500. }
  48501. }
  48502. if (index > -1) {
  48503. this._scene._actionManagers.splice(index, 1);
  48504. }
  48505. };
  48506. ActionManager.prototype.getScene = function () {
  48507. return this._scene;
  48508. };
  48509. /**
  48510. * Does this action manager handles actions of any of the given triggers
  48511. * @param {number[]} triggers - the triggers to be tested
  48512. * @return {boolean} whether one (or more) of the triggers is handeled
  48513. */
  48514. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48515. for (var index = 0; index < this.actions.length; index++) {
  48516. var action = this.actions[index];
  48517. if (triggers.indexOf(action.trigger) > -1) {
  48518. return true;
  48519. }
  48520. }
  48521. return false;
  48522. };
  48523. /**
  48524. * Does this action manager handles actions of a given trigger
  48525. * @param {number} trigger - the trigger to be tested
  48526. * @return {boolean} whether the trigger is handeled
  48527. */
  48528. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48529. for (var index = 0; index < this.actions.length; index++) {
  48530. var action = this.actions[index];
  48531. if (action.trigger === trigger) {
  48532. return true;
  48533. }
  48534. }
  48535. return false;
  48536. };
  48537. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48538. /**
  48539. * Does this action manager has pointer triggers
  48540. * @return {boolean} whether or not it has pointer triggers
  48541. */
  48542. get: function () {
  48543. for (var index = 0; index < this.actions.length; index++) {
  48544. var action = this.actions[index];
  48545. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48546. return true;
  48547. }
  48548. }
  48549. return false;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48555. /**
  48556. * Does this action manager has pick triggers
  48557. * @return {boolean} whether or not it has pick triggers
  48558. */
  48559. get: function () {
  48560. for (var index = 0; index < this.actions.length; index++) {
  48561. var action = this.actions[index];
  48562. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48563. return true;
  48564. }
  48565. }
  48566. return false;
  48567. },
  48568. enumerable: true,
  48569. configurable: true
  48570. });
  48571. Object.defineProperty(ActionManager, "HasTriggers", {
  48572. /**
  48573. * Does exist one action manager with at least one trigger
  48574. * @return {boolean} whether or not it exists one action manager with one trigger
  48575. **/
  48576. get: function () {
  48577. for (var t in ActionManager.Triggers) {
  48578. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48579. return true;
  48580. }
  48581. }
  48582. return false;
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48588. /**
  48589. * Does exist one action manager with at least one pick trigger
  48590. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48591. **/
  48592. get: function () {
  48593. for (var t in ActionManager.Triggers) {
  48594. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48595. var t_int = parseInt(t);
  48596. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48597. return true;
  48598. }
  48599. }
  48600. }
  48601. return false;
  48602. },
  48603. enumerable: true,
  48604. configurable: true
  48605. });
  48606. /**
  48607. * Does exist one action manager that handles actions of a given trigger
  48608. * @param {number} trigger - the trigger to be tested
  48609. * @return {boolean} whether the trigger is handeled by at least one action manager
  48610. **/
  48611. ActionManager.HasSpecificTrigger = function (trigger) {
  48612. for (var t in ActionManager.Triggers) {
  48613. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48614. var t_int = parseInt(t);
  48615. if (t_int === trigger) {
  48616. return true;
  48617. }
  48618. }
  48619. }
  48620. return false;
  48621. };
  48622. /**
  48623. * Registers an action to this action manager
  48624. * @param {BABYLON.Action} action - the action to be registered
  48625. * @return {BABYLON.Action} the action amended (prepared) after registration
  48626. */
  48627. ActionManager.prototype.registerAction = function (action) {
  48628. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48629. if (this.getScene().actionManager !== this) {
  48630. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48631. return null;
  48632. }
  48633. }
  48634. this.actions.push(action);
  48635. if (ActionManager.Triggers[action.trigger]) {
  48636. ActionManager.Triggers[action.trigger]++;
  48637. }
  48638. else {
  48639. ActionManager.Triggers[action.trigger] = 1;
  48640. }
  48641. action._actionManager = this;
  48642. action._prepare();
  48643. return action;
  48644. };
  48645. /**
  48646. * Unregisters an action to this action manager
  48647. * @param action The action to be unregistered
  48648. * @return whether the action has been unregistered
  48649. */
  48650. ActionManager.prototype.unregisterAction = function (action) {
  48651. var index = this.actions.indexOf(action);
  48652. if (index !== -1) {
  48653. this.actions.splice(index, 1);
  48654. ActionManager.Triggers[action.trigger] -= 1;
  48655. if (ActionManager.Triggers[action.trigger] === 0) {
  48656. delete ActionManager.Triggers[action.trigger];
  48657. }
  48658. delete action._actionManager;
  48659. return true;
  48660. }
  48661. return false;
  48662. };
  48663. /**
  48664. * Process a specific trigger
  48665. * @param {number} trigger - the trigger to process
  48666. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48667. */
  48668. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48669. for (var index = 0; index < this.actions.length; index++) {
  48670. var action = this.actions[index];
  48671. if (action.trigger === trigger) {
  48672. if (evt) {
  48673. if (trigger === ActionManager.OnKeyUpTrigger
  48674. || trigger === ActionManager.OnKeyDownTrigger) {
  48675. var parameter = action.getTriggerParameter();
  48676. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48677. if (!parameter.toLowerCase) {
  48678. continue;
  48679. }
  48680. var lowerCase = parameter.toLowerCase();
  48681. if (lowerCase !== evt.sourceEvent.key) {
  48682. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48683. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48684. if (actualkey !== lowerCase) {
  48685. continue;
  48686. }
  48687. }
  48688. }
  48689. }
  48690. }
  48691. action._executeCurrent(evt);
  48692. }
  48693. }
  48694. };
  48695. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48696. var properties = propertyPath.split(".");
  48697. for (var index = 0; index < properties.length - 1; index++) {
  48698. target = target[properties[index]];
  48699. }
  48700. return target;
  48701. };
  48702. ActionManager.prototype._getProperty = function (propertyPath) {
  48703. var properties = propertyPath.split(".");
  48704. return properties[properties.length - 1];
  48705. };
  48706. ActionManager.prototype.serialize = function (name) {
  48707. var root = {
  48708. children: new Array(),
  48709. name: name,
  48710. type: 3,
  48711. properties: new Array() // Empty for root but required
  48712. };
  48713. for (var i = 0; i < this.actions.length; i++) {
  48714. var triggerObject = {
  48715. type: 0,
  48716. children: new Array(),
  48717. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48718. properties: new Array()
  48719. };
  48720. var triggerOptions = this.actions[i].triggerOptions;
  48721. if (triggerOptions && typeof triggerOptions !== "number") {
  48722. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48723. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48724. }
  48725. else {
  48726. var parameter = {};
  48727. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48728. if (triggerOptions.parameter.mesh) {
  48729. parameter._meshId = triggerOptions.parameter.mesh.id;
  48730. }
  48731. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48732. }
  48733. }
  48734. // Serialize child action, recursively
  48735. this.actions[i].serialize(triggerObject);
  48736. // Add serialized trigger
  48737. root.children.push(triggerObject);
  48738. }
  48739. return root;
  48740. };
  48741. ActionManager.Parse = function (parsedActions, object, scene) {
  48742. var actionManager = new ActionManager(scene);
  48743. if (object === null)
  48744. scene.actionManager = actionManager;
  48745. else
  48746. object.actionManager = actionManager;
  48747. // instanciate a new object
  48748. var instanciate = function (name, params) {
  48749. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48750. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48751. newInstance.constructor.apply(newInstance, params);
  48752. return newInstance;
  48753. };
  48754. var parseParameter = function (name, value, target, propertyPath) {
  48755. if (propertyPath === null) {
  48756. // String, boolean or float
  48757. var floatValue = parseFloat(value);
  48758. if (value === "true" || value === "false")
  48759. return value === "true";
  48760. else
  48761. return isNaN(floatValue) ? value : floatValue;
  48762. }
  48763. var effectiveTarget = propertyPath.split(".");
  48764. var values = value.split(",");
  48765. // Get effective Target
  48766. for (var i = 0; i < effectiveTarget.length; i++) {
  48767. target = target[effectiveTarget[i]];
  48768. }
  48769. // Return appropriate value with its type
  48770. if (typeof (target) === "boolean")
  48771. return values[0] === "true";
  48772. if (typeof (target) === "string")
  48773. return values[0];
  48774. // Parameters with multiple values such as Vector3 etc.
  48775. var split = new Array();
  48776. for (var i = 0; i < values.length; i++)
  48777. split.push(parseFloat(values[i]));
  48778. if (target instanceof BABYLON.Vector3)
  48779. return BABYLON.Vector3.FromArray(split);
  48780. if (target instanceof BABYLON.Vector4)
  48781. return BABYLON.Vector4.FromArray(split);
  48782. if (target instanceof BABYLON.Color3)
  48783. return BABYLON.Color3.FromArray(split);
  48784. if (target instanceof BABYLON.Color4)
  48785. return BABYLON.Color4.FromArray(split);
  48786. return parseFloat(values[0]);
  48787. };
  48788. // traverse graph per trigger
  48789. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48790. if (combineArray === void 0) { combineArray = null; }
  48791. if (parsedAction.detached)
  48792. return;
  48793. var parameters = new Array();
  48794. var target = null;
  48795. var propertyPath = null;
  48796. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48797. // Parameters
  48798. if (parsedAction.type === 2)
  48799. parameters.push(actionManager);
  48800. else
  48801. parameters.push(trigger);
  48802. if (combine) {
  48803. var actions = new Array();
  48804. for (var j = 0; j < parsedAction.combine.length; j++) {
  48805. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48806. }
  48807. parameters.push(actions);
  48808. }
  48809. else {
  48810. for (var i = 0; i < parsedAction.properties.length; i++) {
  48811. var value = parsedAction.properties[i].value;
  48812. var name = parsedAction.properties[i].name;
  48813. var targetType = parsedAction.properties[i].targetType;
  48814. if (name === "target")
  48815. if (targetType !== null && targetType === "SceneProperties")
  48816. value = target = scene;
  48817. else
  48818. value = target = scene.getNodeByName(value);
  48819. else if (name === "parent")
  48820. value = scene.getNodeByName(value);
  48821. else if (name === "sound")
  48822. value = scene.getSoundByName(value);
  48823. else if (name !== "propertyPath") {
  48824. if (parsedAction.type === 2 && name === "operator")
  48825. value = BABYLON.ValueCondition[value];
  48826. else
  48827. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48828. }
  48829. else {
  48830. propertyPath = value;
  48831. }
  48832. parameters.push(value);
  48833. }
  48834. }
  48835. if (combineArray === null) {
  48836. parameters.push(condition);
  48837. }
  48838. else {
  48839. parameters.push(null);
  48840. }
  48841. // If interpolate value action
  48842. if (parsedAction.name === "InterpolateValueAction") {
  48843. var param = parameters[parameters.length - 2];
  48844. parameters[parameters.length - 1] = param;
  48845. parameters[parameters.length - 2] = condition;
  48846. }
  48847. // Action or condition(s) and not CombineAction
  48848. var newAction = instanciate(parsedAction.name, parameters);
  48849. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48850. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48851. if (action)
  48852. action.then(nothing);
  48853. else
  48854. actionManager.registerAction(nothing);
  48855. action = nothing;
  48856. }
  48857. if (combineArray === null) {
  48858. if (newAction instanceof BABYLON.Condition) {
  48859. condition = newAction;
  48860. newAction = action;
  48861. }
  48862. else {
  48863. condition = null;
  48864. if (action)
  48865. action.then(newAction);
  48866. else
  48867. actionManager.registerAction(newAction);
  48868. }
  48869. }
  48870. else {
  48871. combineArray.push(newAction);
  48872. }
  48873. for (var i = 0; i < parsedAction.children.length; i++)
  48874. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48875. };
  48876. // triggers
  48877. for (var i = 0; i < parsedActions.children.length; i++) {
  48878. var triggerParams;
  48879. var trigger = parsedActions.children[i];
  48880. if (trigger.properties.length > 0) {
  48881. var param = trigger.properties[0].value;
  48882. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48883. if (value._meshId) {
  48884. value.mesh = scene.getMeshByID(value._meshId);
  48885. }
  48886. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48887. }
  48888. else
  48889. triggerParams = ActionManager[trigger.name];
  48890. for (var j = 0; j < trigger.children.length; j++) {
  48891. if (!trigger.detached)
  48892. traverse(trigger.children[j], triggerParams, null, null);
  48893. }
  48894. }
  48895. };
  48896. ActionManager.GetTriggerName = function (trigger) {
  48897. switch (trigger) {
  48898. case 0: return "NothingTrigger";
  48899. case 1: return "OnPickTrigger";
  48900. case 2: return "OnLeftPickTrigger";
  48901. case 3: return "OnRightPickTrigger";
  48902. case 4: return "OnCenterPickTrigger";
  48903. case 5: return "OnPickDownTrigger";
  48904. case 6: return "OnPickUpTrigger";
  48905. case 7: return "OnLongPressTrigger";
  48906. case 8: return "OnPointerOverTrigger";
  48907. case 9: return "OnPointerOutTrigger";
  48908. case 10: return "OnEveryFrameTrigger";
  48909. case 11: return "OnIntersectionEnterTrigger";
  48910. case 12: return "OnIntersectionExitTrigger";
  48911. case 13: return "OnKeyDownTrigger";
  48912. case 14: return "OnKeyUpTrigger";
  48913. case 15: return "OnPickOutTrigger";
  48914. default: return "";
  48915. }
  48916. };
  48917. // Statics
  48918. ActionManager._NothingTrigger = 0;
  48919. ActionManager._OnPickTrigger = 1;
  48920. ActionManager._OnLeftPickTrigger = 2;
  48921. ActionManager._OnRightPickTrigger = 3;
  48922. ActionManager._OnCenterPickTrigger = 4;
  48923. ActionManager._OnPickDownTrigger = 5;
  48924. ActionManager._OnDoublePickTrigger = 6;
  48925. ActionManager._OnPickUpTrigger = 7;
  48926. ActionManager._OnLongPressTrigger = 8;
  48927. ActionManager._OnPointerOverTrigger = 9;
  48928. ActionManager._OnPointerOutTrigger = 10;
  48929. ActionManager._OnEveryFrameTrigger = 11;
  48930. ActionManager._OnIntersectionEnterTrigger = 12;
  48931. ActionManager._OnIntersectionExitTrigger = 13;
  48932. ActionManager._OnKeyDownTrigger = 14;
  48933. ActionManager._OnKeyUpTrigger = 15;
  48934. ActionManager._OnPickOutTrigger = 16;
  48935. ActionManager.Triggers = {};
  48936. return ActionManager;
  48937. }());
  48938. BABYLON.ActionManager = ActionManager;
  48939. })(BABYLON || (BABYLON = {}));
  48940. //# sourceMappingURL=babylon.actionManager.js.map
  48941. var BABYLON;
  48942. (function (BABYLON) {
  48943. var InterpolateValueAction = /** @class */ (function (_super) {
  48944. __extends(InterpolateValueAction, _super);
  48945. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48946. if (duration === void 0) { duration = 1000; }
  48947. var _this = _super.call(this, triggerOptions, condition) || this;
  48948. _this.propertyPath = propertyPath;
  48949. _this.value = value;
  48950. _this.duration = duration;
  48951. _this.stopOtherAnimations = stopOtherAnimations;
  48952. _this.onInterpolationDone = onInterpolationDone;
  48953. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48954. _this._target = _this._effectiveTarget = target;
  48955. return _this;
  48956. }
  48957. InterpolateValueAction.prototype._prepare = function () {
  48958. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48959. this._property = this._getProperty(this.propertyPath);
  48960. };
  48961. InterpolateValueAction.prototype.execute = function () {
  48962. var _this = this;
  48963. var scene = this._actionManager.getScene();
  48964. var keys = [
  48965. {
  48966. frame: 0,
  48967. value: this._effectiveTarget[this._property]
  48968. }, {
  48969. frame: 100,
  48970. value: this.value
  48971. }
  48972. ];
  48973. var dataType;
  48974. if (typeof this.value === "number") {
  48975. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48976. }
  48977. else if (this.value instanceof BABYLON.Color3) {
  48978. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48979. }
  48980. else if (this.value instanceof BABYLON.Vector3) {
  48981. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48982. }
  48983. else if (this.value instanceof BABYLON.Matrix) {
  48984. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48985. }
  48986. else if (this.value instanceof BABYLON.Quaternion) {
  48987. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48988. }
  48989. else {
  48990. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48991. return;
  48992. }
  48993. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48994. animation.setKeys(keys);
  48995. if (this.stopOtherAnimations) {
  48996. scene.stopAnimation(this._effectiveTarget);
  48997. }
  48998. var wrapper = function () {
  48999. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49000. if (_this.onInterpolationDone) {
  49001. _this.onInterpolationDone();
  49002. }
  49003. };
  49004. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49005. };
  49006. InterpolateValueAction.prototype.serialize = function (parent) {
  49007. return _super.prototype._serialize.call(this, {
  49008. name: "InterpolateValueAction",
  49009. properties: [
  49010. BABYLON.Action._GetTargetProperty(this._target),
  49011. { name: "propertyPath", value: this.propertyPath },
  49012. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49013. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49014. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49015. ]
  49016. }, parent);
  49017. };
  49018. return InterpolateValueAction;
  49019. }(BABYLON.Action));
  49020. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49021. })(BABYLON || (BABYLON = {}));
  49022. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49023. var BABYLON;
  49024. (function (BABYLON) {
  49025. var SwitchBooleanAction = /** @class */ (function (_super) {
  49026. __extends(SwitchBooleanAction, _super);
  49027. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49028. var _this = _super.call(this, triggerOptions, condition) || this;
  49029. _this.propertyPath = propertyPath;
  49030. _this._target = _this._effectiveTarget = target;
  49031. return _this;
  49032. }
  49033. SwitchBooleanAction.prototype._prepare = function () {
  49034. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49035. this._property = this._getProperty(this.propertyPath);
  49036. };
  49037. SwitchBooleanAction.prototype.execute = function () {
  49038. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49039. };
  49040. SwitchBooleanAction.prototype.serialize = function (parent) {
  49041. return _super.prototype._serialize.call(this, {
  49042. name: "SwitchBooleanAction",
  49043. properties: [
  49044. BABYLON.Action._GetTargetProperty(this._target),
  49045. { name: "propertyPath", value: this.propertyPath }
  49046. ]
  49047. }, parent);
  49048. };
  49049. return SwitchBooleanAction;
  49050. }(BABYLON.Action));
  49051. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49052. var SetStateAction = /** @class */ (function (_super) {
  49053. __extends(SetStateAction, _super);
  49054. function SetStateAction(triggerOptions, target, value, condition) {
  49055. var _this = _super.call(this, triggerOptions, condition) || this;
  49056. _this.value = value;
  49057. _this._target = target;
  49058. return _this;
  49059. }
  49060. SetStateAction.prototype.execute = function () {
  49061. this._target.state = this.value;
  49062. };
  49063. SetStateAction.prototype.serialize = function (parent) {
  49064. return _super.prototype._serialize.call(this, {
  49065. name: "SetStateAction",
  49066. properties: [
  49067. BABYLON.Action._GetTargetProperty(this._target),
  49068. { name: "value", value: this.value }
  49069. ]
  49070. }, parent);
  49071. };
  49072. return SetStateAction;
  49073. }(BABYLON.Action));
  49074. BABYLON.SetStateAction = SetStateAction;
  49075. var SetValueAction = /** @class */ (function (_super) {
  49076. __extends(SetValueAction, _super);
  49077. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49078. var _this = _super.call(this, triggerOptions, condition) || this;
  49079. _this.propertyPath = propertyPath;
  49080. _this.value = value;
  49081. _this._target = _this._effectiveTarget = target;
  49082. return _this;
  49083. }
  49084. SetValueAction.prototype._prepare = function () {
  49085. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49086. this._property = this._getProperty(this.propertyPath);
  49087. };
  49088. SetValueAction.prototype.execute = function () {
  49089. this._effectiveTarget[this._property] = this.value;
  49090. if (this._target.markAsDirty) {
  49091. this._target.markAsDirty(this._property);
  49092. }
  49093. };
  49094. SetValueAction.prototype.serialize = function (parent) {
  49095. return _super.prototype._serialize.call(this, {
  49096. name: "SetValueAction",
  49097. properties: [
  49098. BABYLON.Action._GetTargetProperty(this._target),
  49099. { name: "propertyPath", value: this.propertyPath },
  49100. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49101. ]
  49102. }, parent);
  49103. };
  49104. return SetValueAction;
  49105. }(BABYLON.Action));
  49106. BABYLON.SetValueAction = SetValueAction;
  49107. var IncrementValueAction = /** @class */ (function (_super) {
  49108. __extends(IncrementValueAction, _super);
  49109. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49110. var _this = _super.call(this, triggerOptions, condition) || this;
  49111. _this.propertyPath = propertyPath;
  49112. _this.value = value;
  49113. _this._target = _this._effectiveTarget = target;
  49114. return _this;
  49115. }
  49116. IncrementValueAction.prototype._prepare = function () {
  49117. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49118. this._property = this._getProperty(this.propertyPath);
  49119. if (typeof this._effectiveTarget[this._property] !== "number") {
  49120. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49121. }
  49122. };
  49123. IncrementValueAction.prototype.execute = function () {
  49124. this._effectiveTarget[this._property] += this.value;
  49125. if (this._target.markAsDirty) {
  49126. this._target.markAsDirty(this._property);
  49127. }
  49128. };
  49129. IncrementValueAction.prototype.serialize = function (parent) {
  49130. return _super.prototype._serialize.call(this, {
  49131. name: "IncrementValueAction",
  49132. properties: [
  49133. BABYLON.Action._GetTargetProperty(this._target),
  49134. { name: "propertyPath", value: this.propertyPath },
  49135. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49136. ]
  49137. }, parent);
  49138. };
  49139. return IncrementValueAction;
  49140. }(BABYLON.Action));
  49141. BABYLON.IncrementValueAction = IncrementValueAction;
  49142. var PlayAnimationAction = /** @class */ (function (_super) {
  49143. __extends(PlayAnimationAction, _super);
  49144. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49145. var _this = _super.call(this, triggerOptions, condition) || this;
  49146. _this.from = from;
  49147. _this.to = to;
  49148. _this.loop = loop;
  49149. _this._target = target;
  49150. return _this;
  49151. }
  49152. PlayAnimationAction.prototype._prepare = function () {
  49153. };
  49154. PlayAnimationAction.prototype.execute = function () {
  49155. var scene = this._actionManager.getScene();
  49156. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49157. };
  49158. PlayAnimationAction.prototype.serialize = function (parent) {
  49159. return _super.prototype._serialize.call(this, {
  49160. name: "PlayAnimationAction",
  49161. properties: [
  49162. BABYLON.Action._GetTargetProperty(this._target),
  49163. { name: "from", value: String(this.from) },
  49164. { name: "to", value: String(this.to) },
  49165. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49166. ]
  49167. }, parent);
  49168. };
  49169. return PlayAnimationAction;
  49170. }(BABYLON.Action));
  49171. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49172. var StopAnimationAction = /** @class */ (function (_super) {
  49173. __extends(StopAnimationAction, _super);
  49174. function StopAnimationAction(triggerOptions, target, condition) {
  49175. var _this = _super.call(this, triggerOptions, condition) || this;
  49176. _this._target = target;
  49177. return _this;
  49178. }
  49179. StopAnimationAction.prototype._prepare = function () {
  49180. };
  49181. StopAnimationAction.prototype.execute = function () {
  49182. var scene = this._actionManager.getScene();
  49183. scene.stopAnimation(this._target);
  49184. };
  49185. StopAnimationAction.prototype.serialize = function (parent) {
  49186. return _super.prototype._serialize.call(this, {
  49187. name: "StopAnimationAction",
  49188. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49189. }, parent);
  49190. };
  49191. return StopAnimationAction;
  49192. }(BABYLON.Action));
  49193. BABYLON.StopAnimationAction = StopAnimationAction;
  49194. var DoNothingAction = /** @class */ (function (_super) {
  49195. __extends(DoNothingAction, _super);
  49196. function DoNothingAction(triggerOptions, condition) {
  49197. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49198. return _super.call(this, triggerOptions, condition) || this;
  49199. }
  49200. DoNothingAction.prototype.execute = function () {
  49201. };
  49202. DoNothingAction.prototype.serialize = function (parent) {
  49203. return _super.prototype._serialize.call(this, {
  49204. name: "DoNothingAction",
  49205. properties: []
  49206. }, parent);
  49207. };
  49208. return DoNothingAction;
  49209. }(BABYLON.Action));
  49210. BABYLON.DoNothingAction = DoNothingAction;
  49211. var CombineAction = /** @class */ (function (_super) {
  49212. __extends(CombineAction, _super);
  49213. function CombineAction(triggerOptions, children, condition) {
  49214. var _this = _super.call(this, triggerOptions, condition) || this;
  49215. _this.children = children;
  49216. return _this;
  49217. }
  49218. CombineAction.prototype._prepare = function () {
  49219. for (var index = 0; index < this.children.length; index++) {
  49220. this.children[index]._actionManager = this._actionManager;
  49221. this.children[index]._prepare();
  49222. }
  49223. };
  49224. CombineAction.prototype.execute = function (evt) {
  49225. for (var index = 0; index < this.children.length; index++) {
  49226. this.children[index].execute(evt);
  49227. }
  49228. };
  49229. CombineAction.prototype.serialize = function (parent) {
  49230. var serializationObject = _super.prototype._serialize.call(this, {
  49231. name: "CombineAction",
  49232. properties: [],
  49233. combine: []
  49234. }, parent);
  49235. for (var i = 0; i < this.children.length; i++) {
  49236. serializationObject.combine.push(this.children[i].serialize(null));
  49237. }
  49238. return serializationObject;
  49239. };
  49240. return CombineAction;
  49241. }(BABYLON.Action));
  49242. BABYLON.CombineAction = CombineAction;
  49243. var ExecuteCodeAction = /** @class */ (function (_super) {
  49244. __extends(ExecuteCodeAction, _super);
  49245. function ExecuteCodeAction(triggerOptions, func, condition) {
  49246. var _this = _super.call(this, triggerOptions, condition) || this;
  49247. _this.func = func;
  49248. return _this;
  49249. }
  49250. ExecuteCodeAction.prototype.execute = function (evt) {
  49251. this.func(evt);
  49252. };
  49253. return ExecuteCodeAction;
  49254. }(BABYLON.Action));
  49255. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49256. var SetParentAction = /** @class */ (function (_super) {
  49257. __extends(SetParentAction, _super);
  49258. function SetParentAction(triggerOptions, target, parent, condition) {
  49259. var _this = _super.call(this, triggerOptions, condition) || this;
  49260. _this._target = target;
  49261. _this._parent = parent;
  49262. return _this;
  49263. }
  49264. SetParentAction.prototype._prepare = function () {
  49265. };
  49266. SetParentAction.prototype.execute = function () {
  49267. if (this._target.parent === this._parent) {
  49268. return;
  49269. }
  49270. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49271. invertParentWorldMatrix.invert();
  49272. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49273. this._target.parent = this._parent;
  49274. };
  49275. SetParentAction.prototype.serialize = function (parent) {
  49276. return _super.prototype._serialize.call(this, {
  49277. name: "SetParentAction",
  49278. properties: [
  49279. BABYLON.Action._GetTargetProperty(this._target),
  49280. BABYLON.Action._GetTargetProperty(this._parent),
  49281. ]
  49282. }, parent);
  49283. };
  49284. return SetParentAction;
  49285. }(BABYLON.Action));
  49286. BABYLON.SetParentAction = SetParentAction;
  49287. var PlaySoundAction = /** @class */ (function (_super) {
  49288. __extends(PlaySoundAction, _super);
  49289. function PlaySoundAction(triggerOptions, sound, condition) {
  49290. var _this = _super.call(this, triggerOptions, condition) || this;
  49291. _this._sound = sound;
  49292. return _this;
  49293. }
  49294. PlaySoundAction.prototype._prepare = function () {
  49295. };
  49296. PlaySoundAction.prototype.execute = function () {
  49297. if (this._sound !== undefined)
  49298. this._sound.play();
  49299. };
  49300. PlaySoundAction.prototype.serialize = function (parent) {
  49301. return _super.prototype._serialize.call(this, {
  49302. name: "PlaySoundAction",
  49303. properties: [{ name: "sound", value: this._sound.name }]
  49304. }, parent);
  49305. };
  49306. return PlaySoundAction;
  49307. }(BABYLON.Action));
  49308. BABYLON.PlaySoundAction = PlaySoundAction;
  49309. var StopSoundAction = /** @class */ (function (_super) {
  49310. __extends(StopSoundAction, _super);
  49311. function StopSoundAction(triggerOptions, sound, condition) {
  49312. var _this = _super.call(this, triggerOptions, condition) || this;
  49313. _this._sound = sound;
  49314. return _this;
  49315. }
  49316. StopSoundAction.prototype._prepare = function () {
  49317. };
  49318. StopSoundAction.prototype.execute = function () {
  49319. if (this._sound !== undefined)
  49320. this._sound.stop();
  49321. };
  49322. StopSoundAction.prototype.serialize = function (parent) {
  49323. return _super.prototype._serialize.call(this, {
  49324. name: "StopSoundAction",
  49325. properties: [{ name: "sound", value: this._sound.name }]
  49326. }, parent);
  49327. };
  49328. return StopSoundAction;
  49329. }(BABYLON.Action));
  49330. BABYLON.StopSoundAction = StopSoundAction;
  49331. })(BABYLON || (BABYLON = {}));
  49332. //# sourceMappingURL=babylon.directActions.js.map
  49333. var BABYLON;
  49334. (function (BABYLON) {
  49335. var SpriteManager = /** @class */ (function () {
  49336. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49337. if (epsilon === void 0) { epsilon = 0.01; }
  49338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49339. this.name = name;
  49340. this.sprites = new Array();
  49341. this.renderingGroupId = 0;
  49342. this.layerMask = 0x0FFFFFFF;
  49343. this.fogEnabled = true;
  49344. this.isPickable = false;
  49345. /**
  49346. * An event triggered when the manager is disposed.
  49347. * @type {BABYLON.Observable}
  49348. */
  49349. this.onDisposeObservable = new BABYLON.Observable();
  49350. this._vertexBuffers = {};
  49351. this._capacity = capacity;
  49352. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49353. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49354. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49355. if (cellSize.width && cellSize.height) {
  49356. this.cellWidth = cellSize.width;
  49357. this.cellHeight = cellSize.height;
  49358. }
  49359. else if (cellSize !== undefined) {
  49360. this.cellWidth = cellSize;
  49361. this.cellHeight = cellSize;
  49362. }
  49363. else {
  49364. return;
  49365. }
  49366. this._epsilon = epsilon;
  49367. this._scene = scene;
  49368. this._scene.spriteManagers.push(this);
  49369. var indices = [];
  49370. var index = 0;
  49371. for (var count = 0; count < capacity; count++) {
  49372. indices.push(index);
  49373. indices.push(index + 1);
  49374. indices.push(index + 2);
  49375. indices.push(index);
  49376. indices.push(index + 2);
  49377. indices.push(index + 3);
  49378. index += 4;
  49379. }
  49380. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49381. // VBO
  49382. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49383. this._vertexData = new Float32Array(capacity * 16 * 4);
  49384. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49385. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49386. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49387. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49388. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49389. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49390. this._vertexBuffers["options"] = options;
  49391. this._vertexBuffers["cellInfo"] = cellInfo;
  49392. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49393. // Effects
  49394. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49395. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49396. }
  49397. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49398. set: function (callback) {
  49399. if (this._onDisposeObserver) {
  49400. this.onDisposeObservable.remove(this._onDisposeObserver);
  49401. }
  49402. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49403. },
  49404. enumerable: true,
  49405. configurable: true
  49406. });
  49407. Object.defineProperty(SpriteManager.prototype, "texture", {
  49408. get: function () {
  49409. return this._spriteTexture;
  49410. },
  49411. set: function (value) {
  49412. this._spriteTexture = value;
  49413. },
  49414. enumerable: true,
  49415. configurable: true
  49416. });
  49417. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49418. var arrayOffset = index * 16;
  49419. if (offsetX === 0)
  49420. offsetX = this._epsilon;
  49421. else if (offsetX === 1)
  49422. offsetX = 1 - this._epsilon;
  49423. if (offsetY === 0)
  49424. offsetY = this._epsilon;
  49425. else if (offsetY === 1)
  49426. offsetY = 1 - this._epsilon;
  49427. this._vertexData[arrayOffset] = sprite.position.x;
  49428. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49429. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49430. this._vertexData[arrayOffset + 3] = sprite.angle;
  49431. this._vertexData[arrayOffset + 4] = sprite.width;
  49432. this._vertexData[arrayOffset + 5] = sprite.height;
  49433. this._vertexData[arrayOffset + 6] = offsetX;
  49434. this._vertexData[arrayOffset + 7] = offsetY;
  49435. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49436. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49437. var offset = (sprite.cellIndex / rowSize) >> 0;
  49438. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49439. this._vertexData[arrayOffset + 11] = offset;
  49440. // Color
  49441. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49442. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49443. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49444. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49445. };
  49446. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49447. var count = Math.min(this._capacity, this.sprites.length);
  49448. var min = BABYLON.Vector3.Zero();
  49449. var max = BABYLON.Vector3.Zero();
  49450. var distance = Number.MAX_VALUE;
  49451. var currentSprite = null;
  49452. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49453. var cameraView = camera.getViewMatrix();
  49454. for (var index = 0; index < count; index++) {
  49455. var sprite = this.sprites[index];
  49456. if (!sprite) {
  49457. continue;
  49458. }
  49459. if (predicate) {
  49460. if (!predicate(sprite)) {
  49461. continue;
  49462. }
  49463. }
  49464. else if (!sprite.isPickable) {
  49465. continue;
  49466. }
  49467. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49468. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49469. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49470. if (ray.intersectsBoxMinMax(min, max)) {
  49471. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49472. if (distance > currentDistance) {
  49473. distance = currentDistance;
  49474. currentSprite = sprite;
  49475. if (fastCheck) {
  49476. break;
  49477. }
  49478. }
  49479. }
  49480. }
  49481. if (currentSprite) {
  49482. var result = new BABYLON.PickingInfo();
  49483. result.hit = true;
  49484. result.pickedSprite = currentSprite;
  49485. result.distance = distance;
  49486. return result;
  49487. }
  49488. return null;
  49489. };
  49490. SpriteManager.prototype.render = function () {
  49491. // Check
  49492. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49493. return;
  49494. var engine = this._scene.getEngine();
  49495. var baseSize = this._spriteTexture.getBaseSize();
  49496. // Sprites
  49497. var deltaTime = engine.getDeltaTime();
  49498. var max = Math.min(this._capacity, this.sprites.length);
  49499. var rowSize = baseSize.width / this.cellWidth;
  49500. var offset = 0;
  49501. for (var index = 0; index < max; index++) {
  49502. var sprite = this.sprites[index];
  49503. if (!sprite) {
  49504. continue;
  49505. }
  49506. sprite._animate(deltaTime);
  49507. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49508. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49509. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49510. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49511. }
  49512. this._buffer.update(this._vertexData);
  49513. // Render
  49514. var effect = this._effectBase;
  49515. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49516. effect = this._effectFog;
  49517. }
  49518. engine.enableEffect(effect);
  49519. var viewMatrix = this._scene.getViewMatrix();
  49520. effect.setTexture("diffuseSampler", this._spriteTexture);
  49521. effect.setMatrix("view", viewMatrix);
  49522. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49523. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49524. // Fog
  49525. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49526. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49527. effect.setColor3("vFogColor", this._scene.fogColor);
  49528. }
  49529. // VBOs
  49530. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49531. // Draw order
  49532. engine.setDepthFunctionToLessOrEqual();
  49533. effect.setBool("alphaTest", true);
  49534. engine.setColorWrite(false);
  49535. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49536. engine.setColorWrite(true);
  49537. effect.setBool("alphaTest", false);
  49538. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49540. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49541. };
  49542. SpriteManager.prototype.dispose = function () {
  49543. if (this._buffer) {
  49544. this._buffer.dispose();
  49545. this._buffer = null;
  49546. }
  49547. if (this._indexBuffer) {
  49548. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49549. this._indexBuffer = null;
  49550. }
  49551. if (this._spriteTexture) {
  49552. this._spriteTexture.dispose();
  49553. this._spriteTexture = null;
  49554. }
  49555. // Remove from scene
  49556. var index = this._scene.spriteManagers.indexOf(this);
  49557. this._scene.spriteManagers.splice(index, 1);
  49558. // Callback
  49559. this.onDisposeObservable.notifyObservers(this);
  49560. this.onDisposeObservable.clear();
  49561. };
  49562. return SpriteManager;
  49563. }());
  49564. BABYLON.SpriteManager = SpriteManager;
  49565. })(BABYLON || (BABYLON = {}));
  49566. //# sourceMappingURL=babylon.spriteManager.js.map
  49567. var BABYLON;
  49568. (function (BABYLON) {
  49569. var Sprite = /** @class */ (function () {
  49570. function Sprite(name, manager) {
  49571. this.name = name;
  49572. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49573. this.width = 1.0;
  49574. this.height = 1.0;
  49575. this.angle = 0;
  49576. this.cellIndex = 0;
  49577. this.invertU = 0;
  49578. this.invertV = 0;
  49579. this.animations = new Array();
  49580. this.isPickable = false;
  49581. this._animationStarted = false;
  49582. this._loopAnimation = false;
  49583. this._fromIndex = 0;
  49584. this._toIndex = 0;
  49585. this._delay = 0;
  49586. this._direction = 1;
  49587. this._time = 0;
  49588. this._manager = manager;
  49589. this._manager.sprites.push(this);
  49590. this.position = BABYLON.Vector3.Zero();
  49591. }
  49592. Object.defineProperty(Sprite.prototype, "size", {
  49593. get: function () {
  49594. return this.width;
  49595. },
  49596. set: function (value) {
  49597. this.width = value;
  49598. this.height = value;
  49599. },
  49600. enumerable: true,
  49601. configurable: true
  49602. });
  49603. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49604. this._fromIndex = from;
  49605. this._toIndex = to;
  49606. this._loopAnimation = loop;
  49607. this._delay = delay;
  49608. this._animationStarted = true;
  49609. this._direction = from < to ? 1 : -1;
  49610. this.cellIndex = from;
  49611. this._time = 0;
  49612. this._onAnimationEnd = onAnimationEnd;
  49613. };
  49614. Sprite.prototype.stopAnimation = function () {
  49615. this._animationStarted = false;
  49616. };
  49617. Sprite.prototype._animate = function (deltaTime) {
  49618. if (!this._animationStarted)
  49619. return;
  49620. this._time += deltaTime;
  49621. if (this._time > this._delay) {
  49622. this._time = this._time % this._delay;
  49623. this.cellIndex += this._direction;
  49624. if (this.cellIndex > this._toIndex) {
  49625. if (this._loopAnimation) {
  49626. this.cellIndex = this._fromIndex;
  49627. }
  49628. else {
  49629. this.cellIndex = this._toIndex;
  49630. this._animationStarted = false;
  49631. if (this._onAnimationEnd) {
  49632. this._onAnimationEnd();
  49633. }
  49634. if (this.disposeWhenFinishedAnimating) {
  49635. this.dispose();
  49636. }
  49637. }
  49638. }
  49639. }
  49640. };
  49641. Sprite.prototype.dispose = function () {
  49642. for (var i = 0; i < this._manager.sprites.length; i++) {
  49643. if (this._manager.sprites[i] == this) {
  49644. this._manager.sprites.splice(i, 1);
  49645. }
  49646. }
  49647. };
  49648. return Sprite;
  49649. }());
  49650. BABYLON.Sprite = Sprite;
  49651. })(BABYLON || (BABYLON = {}));
  49652. //# sourceMappingURL=babylon.sprite.js.map
  49653. var BABYLON;
  49654. (function (BABYLON) {
  49655. var IntersectionInfo = /** @class */ (function () {
  49656. function IntersectionInfo(bu, bv, distance) {
  49657. this.bu = bu;
  49658. this.bv = bv;
  49659. this.distance = distance;
  49660. this.faceId = 0;
  49661. this.subMeshId = 0;
  49662. }
  49663. return IntersectionInfo;
  49664. }());
  49665. BABYLON.IntersectionInfo = IntersectionInfo;
  49666. var PickingInfo = /** @class */ (function () {
  49667. function PickingInfo() {
  49668. this.hit = false;
  49669. this.distance = 0;
  49670. this.pickedPoint = null;
  49671. this.pickedMesh = null;
  49672. this.bu = 0;
  49673. this.bv = 0;
  49674. this.faceId = -1;
  49675. this.subMeshId = 0;
  49676. this.pickedSprite = null;
  49677. }
  49678. // Methods
  49679. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49680. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49681. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49682. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49683. return null;
  49684. }
  49685. var indices = this.pickedMesh.getIndices();
  49686. if (!indices) {
  49687. return null;
  49688. }
  49689. var result;
  49690. if (useVerticesNormals) {
  49691. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49692. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49693. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49694. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49695. normal0 = normal0.scale(this.bu);
  49696. normal1 = normal1.scale(this.bv);
  49697. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49698. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49699. }
  49700. else {
  49701. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49702. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49703. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49704. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49705. var p1p2 = vertex1.subtract(vertex2);
  49706. var p3p2 = vertex3.subtract(vertex2);
  49707. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49708. }
  49709. if (useWorldCoordinates) {
  49710. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49711. }
  49712. return BABYLON.Vector3.Normalize(result);
  49713. };
  49714. PickingInfo.prototype.getTextureCoordinates = function () {
  49715. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49716. return null;
  49717. }
  49718. var indices = this.pickedMesh.getIndices();
  49719. if (!indices) {
  49720. return null;
  49721. }
  49722. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49723. if (!uvs) {
  49724. return null;
  49725. }
  49726. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49727. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49728. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49729. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49730. uv1 = uv1.scale(this.bu);
  49731. uv2 = uv2.scale(this.bv);
  49732. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49733. };
  49734. return PickingInfo;
  49735. }());
  49736. BABYLON.PickingInfo = PickingInfo;
  49737. })(BABYLON || (BABYLON = {}));
  49738. //# sourceMappingURL=babylon.pickingInfo.js.map
  49739. var BABYLON;
  49740. (function (BABYLON) {
  49741. var Ray = /** @class */ (function () {
  49742. function Ray(origin, direction, length) {
  49743. if (length === void 0) { length = Number.MAX_VALUE; }
  49744. this.origin = origin;
  49745. this.direction = direction;
  49746. this.length = length;
  49747. }
  49748. // Methods
  49749. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49750. var d = 0.0;
  49751. var maxValue = Number.MAX_VALUE;
  49752. var inv;
  49753. var min;
  49754. var max;
  49755. var temp;
  49756. if (Math.abs(this.direction.x) < 0.0000001) {
  49757. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49758. return false;
  49759. }
  49760. }
  49761. else {
  49762. inv = 1.0 / this.direction.x;
  49763. min = (minimum.x - this.origin.x) * inv;
  49764. max = (maximum.x - this.origin.x) * inv;
  49765. if (max === -Infinity) {
  49766. max = Infinity;
  49767. }
  49768. if (min > max) {
  49769. temp = min;
  49770. min = max;
  49771. max = temp;
  49772. }
  49773. d = Math.max(min, d);
  49774. maxValue = Math.min(max, maxValue);
  49775. if (d > maxValue) {
  49776. return false;
  49777. }
  49778. }
  49779. if (Math.abs(this.direction.y) < 0.0000001) {
  49780. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49781. return false;
  49782. }
  49783. }
  49784. else {
  49785. inv = 1.0 / this.direction.y;
  49786. min = (minimum.y - this.origin.y) * inv;
  49787. max = (maximum.y - this.origin.y) * inv;
  49788. if (max === -Infinity) {
  49789. max = Infinity;
  49790. }
  49791. if (min > max) {
  49792. temp = min;
  49793. min = max;
  49794. max = temp;
  49795. }
  49796. d = Math.max(min, d);
  49797. maxValue = Math.min(max, maxValue);
  49798. if (d > maxValue) {
  49799. return false;
  49800. }
  49801. }
  49802. if (Math.abs(this.direction.z) < 0.0000001) {
  49803. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49804. return false;
  49805. }
  49806. }
  49807. else {
  49808. inv = 1.0 / this.direction.z;
  49809. min = (minimum.z - this.origin.z) * inv;
  49810. max = (maximum.z - this.origin.z) * inv;
  49811. if (max === -Infinity) {
  49812. max = Infinity;
  49813. }
  49814. if (min > max) {
  49815. temp = min;
  49816. min = max;
  49817. max = temp;
  49818. }
  49819. d = Math.max(min, d);
  49820. maxValue = Math.min(max, maxValue);
  49821. if (d > maxValue) {
  49822. return false;
  49823. }
  49824. }
  49825. return true;
  49826. };
  49827. Ray.prototype.intersectsBox = function (box) {
  49828. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49829. };
  49830. Ray.prototype.intersectsSphere = function (sphere) {
  49831. var x = sphere.center.x - this.origin.x;
  49832. var y = sphere.center.y - this.origin.y;
  49833. var z = sphere.center.z - this.origin.z;
  49834. var pyth = (x * x) + (y * y) + (z * z);
  49835. var rr = sphere.radius * sphere.radius;
  49836. if (pyth <= rr) {
  49837. return true;
  49838. }
  49839. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49840. if (dot < 0.0) {
  49841. return false;
  49842. }
  49843. var temp = pyth - (dot * dot);
  49844. return temp <= rr;
  49845. };
  49846. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49847. if (!this._edge1) {
  49848. this._edge1 = BABYLON.Vector3.Zero();
  49849. this._edge2 = BABYLON.Vector3.Zero();
  49850. this._pvec = BABYLON.Vector3.Zero();
  49851. this._tvec = BABYLON.Vector3.Zero();
  49852. this._qvec = BABYLON.Vector3.Zero();
  49853. }
  49854. vertex1.subtractToRef(vertex0, this._edge1);
  49855. vertex2.subtractToRef(vertex0, this._edge2);
  49856. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49857. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49858. if (det === 0) {
  49859. return null;
  49860. }
  49861. var invdet = 1 / det;
  49862. this.origin.subtractToRef(vertex0, this._tvec);
  49863. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49864. if (bu < 0 || bu > 1.0) {
  49865. return null;
  49866. }
  49867. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49868. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49869. if (bv < 0 || bu + bv > 1.0) {
  49870. return null;
  49871. }
  49872. //check if the distance is longer than the predefined length.
  49873. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49874. if (distance > this.length) {
  49875. return null;
  49876. }
  49877. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49878. };
  49879. Ray.prototype.intersectsPlane = function (plane) {
  49880. var distance;
  49881. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49882. if (Math.abs(result1) < 9.99999997475243E-07) {
  49883. return null;
  49884. }
  49885. else {
  49886. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49887. distance = (-plane.d - result2) / result1;
  49888. if (distance < 0.0) {
  49889. if (distance < -9.99999997475243E-07) {
  49890. return null;
  49891. }
  49892. else {
  49893. return 0;
  49894. }
  49895. }
  49896. return distance;
  49897. }
  49898. };
  49899. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49900. var tm = BABYLON.Tmp.Matrix[0];
  49901. mesh.getWorldMatrix().invertToRef(tm);
  49902. if (this._tmpRay) {
  49903. Ray.TransformToRef(this, tm, this._tmpRay);
  49904. }
  49905. else {
  49906. this._tmpRay = Ray.Transform(this, tm);
  49907. }
  49908. return mesh.intersects(this._tmpRay, fastCheck);
  49909. };
  49910. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49911. if (results) {
  49912. results.length = 0;
  49913. }
  49914. else {
  49915. results = [];
  49916. }
  49917. for (var i = 0; i < meshes.length; i++) {
  49918. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49919. if (pickInfo.hit) {
  49920. results.push(pickInfo);
  49921. }
  49922. }
  49923. results.sort(this._comparePickingInfo);
  49924. return results;
  49925. };
  49926. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49927. if (pickingInfoA.distance < pickingInfoB.distance) {
  49928. return -1;
  49929. }
  49930. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49931. return 1;
  49932. }
  49933. else {
  49934. return 0;
  49935. }
  49936. };
  49937. /**
  49938. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49939. * @param sega the first point of the segment to test the intersection against
  49940. * @param segb the second point of the segment to test the intersection against
  49941. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49942. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49943. */
  49944. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49945. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49946. var u = segb.subtract(sega);
  49947. var v = rsegb.subtract(this.origin);
  49948. var w = sega.subtract(this.origin);
  49949. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49950. var b = BABYLON.Vector3.Dot(u, v);
  49951. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49952. var d = BABYLON.Vector3.Dot(u, w);
  49953. var e = BABYLON.Vector3.Dot(v, w);
  49954. var D = a * c - b * b; // always >= 0
  49955. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49956. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49957. // compute the line parameters of the two closest points
  49958. if (D < Ray.smallnum) {
  49959. sN = 0.0; // force using point P0 on segment S1
  49960. sD = 1.0; // to prevent possible division by 0.0 later
  49961. tN = e;
  49962. tD = c;
  49963. }
  49964. else {
  49965. sN = (b * e - c * d);
  49966. tN = (a * e - b * d);
  49967. if (sN < 0.0) {
  49968. sN = 0.0;
  49969. tN = e;
  49970. tD = c;
  49971. }
  49972. else if (sN > sD) {
  49973. sN = sD;
  49974. tN = e + b;
  49975. tD = c;
  49976. }
  49977. }
  49978. if (tN < 0.0) {
  49979. tN = 0.0;
  49980. // recompute sc for this edge
  49981. if (-d < 0.0) {
  49982. sN = 0.0;
  49983. }
  49984. else if (-d > a)
  49985. sN = sD;
  49986. else {
  49987. sN = -d;
  49988. sD = a;
  49989. }
  49990. }
  49991. else if (tN > tD) {
  49992. tN = tD;
  49993. // recompute sc for this edge
  49994. if ((-d + b) < 0.0) {
  49995. sN = 0;
  49996. }
  49997. else if ((-d + b) > a) {
  49998. sN = sD;
  49999. }
  50000. else {
  50001. sN = (-d + b);
  50002. sD = a;
  50003. }
  50004. }
  50005. // finally do the division to get sc and tc
  50006. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50007. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50008. // get the difference of the two closest points
  50009. var qtc = v.multiplyByFloats(tc, tc, tc);
  50010. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50011. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50012. if (isIntersected) {
  50013. return qtc.length();
  50014. }
  50015. return -1;
  50016. };
  50017. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50018. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50019. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50020. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50021. this.direction.normalize();
  50022. return this;
  50023. };
  50024. // Statics
  50025. Ray.Zero = function () {
  50026. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50027. };
  50028. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50029. var result = Ray.Zero();
  50030. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50031. };
  50032. /**
  50033. * 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
  50034. * transformed to the given world matrix.
  50035. * @param origin The origin point
  50036. * @param end The end point
  50037. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50038. */
  50039. Ray.CreateNewFromTo = function (origin, end, world) {
  50040. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50041. var direction = end.subtract(origin);
  50042. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50043. direction.normalize();
  50044. return Ray.Transform(new Ray(origin, direction, length), world);
  50045. };
  50046. Ray.Transform = function (ray, matrix) {
  50047. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50048. Ray.TransformToRef(ray, matrix, result);
  50049. return result;
  50050. };
  50051. Ray.TransformToRef = function (ray, matrix, result) {
  50052. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50053. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50054. result.length = ray.length;
  50055. var dir = result.direction;
  50056. var len = dir.length();
  50057. if (!(len === 0 || len === 1)) {
  50058. var num = 1.0 / len;
  50059. dir.x *= num;
  50060. dir.y *= num;
  50061. dir.z *= num;
  50062. result.length *= len;
  50063. }
  50064. };
  50065. Ray.smallnum = 0.00000001;
  50066. Ray.rayl = 10e8;
  50067. return Ray;
  50068. }());
  50069. BABYLON.Ray = Ray;
  50070. })(BABYLON || (BABYLON = {}));
  50071. //# sourceMappingURL=babylon.ray.js.map
  50072. var BABYLON;
  50073. (function (BABYLON) {
  50074. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50075. if (boxMin.x > sphereCenter.x + sphereRadius)
  50076. return false;
  50077. if (sphereCenter.x - sphereRadius > boxMax.x)
  50078. return false;
  50079. if (boxMin.y > sphereCenter.y + sphereRadius)
  50080. return false;
  50081. if (sphereCenter.y - sphereRadius > boxMax.y)
  50082. return false;
  50083. if (boxMin.z > sphereCenter.z + sphereRadius)
  50084. return false;
  50085. if (sphereCenter.z - sphereRadius > boxMax.z)
  50086. return false;
  50087. return true;
  50088. };
  50089. var getLowestRoot = (function () {
  50090. var result = { root: 0, found: false };
  50091. return function (a, b, c, maxR) {
  50092. result.root = 0;
  50093. result.found = false;
  50094. var determinant = b * b - 4.0 * a * c;
  50095. if (determinant < 0)
  50096. return result;
  50097. var sqrtD = Math.sqrt(determinant);
  50098. var r1 = (-b - sqrtD) / (2.0 * a);
  50099. var r2 = (-b + sqrtD) / (2.0 * a);
  50100. if (r1 > r2) {
  50101. var temp = r2;
  50102. r2 = r1;
  50103. r1 = temp;
  50104. }
  50105. if (r1 > 0 && r1 < maxR) {
  50106. result.root = r1;
  50107. result.found = true;
  50108. return result;
  50109. }
  50110. if (r2 > 0 && r2 < maxR) {
  50111. result.root = r2;
  50112. result.found = true;
  50113. return result;
  50114. }
  50115. return result;
  50116. };
  50117. })();
  50118. var Collider = /** @class */ (function () {
  50119. function Collider() {
  50120. this._collisionPoint = BABYLON.Vector3.Zero();
  50121. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50122. this._tempVector = BABYLON.Vector3.Zero();
  50123. this._tempVector2 = BABYLON.Vector3.Zero();
  50124. this._tempVector3 = BABYLON.Vector3.Zero();
  50125. this._tempVector4 = BABYLON.Vector3.Zero();
  50126. this._edge = BABYLON.Vector3.Zero();
  50127. this._baseToVertex = BABYLON.Vector3.Zero();
  50128. this._destinationPoint = BABYLON.Vector3.Zero();
  50129. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50130. this._displacementVector = BABYLON.Vector3.Zero();
  50131. this._radius = BABYLON.Vector3.One();
  50132. this._retry = 0;
  50133. this._basePointWorld = BABYLON.Vector3.Zero();
  50134. this._velocityWorld = BABYLON.Vector3.Zero();
  50135. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50136. this._collisionMask = -1;
  50137. }
  50138. Object.defineProperty(Collider.prototype, "collisionMask", {
  50139. get: function () {
  50140. return this._collisionMask;
  50141. },
  50142. set: function (mask) {
  50143. this._collisionMask = !isNaN(mask) ? mask : -1;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50149. /**
  50150. * Gets the plane normal used to compute the sliding response (in local space)
  50151. */
  50152. get: function () {
  50153. return this._slidePlaneNormal;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. // Methods
  50159. Collider.prototype._initialize = function (source, dir, e) {
  50160. this._velocity = dir;
  50161. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50162. this._basePoint = source;
  50163. source.multiplyToRef(this._radius, this._basePointWorld);
  50164. dir.multiplyToRef(this._radius, this._velocityWorld);
  50165. this._velocityWorldLength = this._velocityWorld.length();
  50166. this._epsilon = e;
  50167. this.collisionFound = false;
  50168. };
  50169. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50170. pa.subtractToRef(point, this._tempVector);
  50171. pb.subtractToRef(point, this._tempVector2);
  50172. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50173. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50174. if (d < 0)
  50175. return false;
  50176. pc.subtractToRef(point, this._tempVector3);
  50177. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50178. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50179. if (d < 0)
  50180. return false;
  50181. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50182. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50183. return d >= 0;
  50184. };
  50185. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50186. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50187. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50188. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50189. return false;
  50190. }
  50191. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50192. return false;
  50193. return true;
  50194. };
  50195. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50196. var t0;
  50197. var embeddedInPlane = false;
  50198. //defensive programming, actually not needed.
  50199. if (!trianglePlaneArray) {
  50200. trianglePlaneArray = [];
  50201. }
  50202. if (!trianglePlaneArray[faceIndex]) {
  50203. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50204. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50205. }
  50206. var trianglePlane = trianglePlaneArray[faceIndex];
  50207. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50208. return;
  50209. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50210. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50211. if (normalDotVelocity == 0) {
  50212. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50213. return;
  50214. embeddedInPlane = true;
  50215. t0 = 0;
  50216. }
  50217. else {
  50218. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50219. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50220. if (t0 > t1) {
  50221. var temp = t1;
  50222. t1 = t0;
  50223. t0 = temp;
  50224. }
  50225. if (t0 > 1.0 || t1 < 0.0)
  50226. return;
  50227. if (t0 < 0)
  50228. t0 = 0;
  50229. if (t0 > 1.0)
  50230. t0 = 1.0;
  50231. }
  50232. this._collisionPoint.copyFromFloats(0, 0, 0);
  50233. var found = false;
  50234. var t = 1.0;
  50235. if (!embeddedInPlane) {
  50236. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50237. this._velocity.scaleToRef(t0, this._tempVector);
  50238. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50239. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50240. found = true;
  50241. t = t0;
  50242. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50243. }
  50244. }
  50245. if (!found) {
  50246. var velocitySquaredLength = this._velocity.lengthSquared();
  50247. var a = velocitySquaredLength;
  50248. this._basePoint.subtractToRef(p1, this._tempVector);
  50249. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50250. var c = this._tempVector.lengthSquared() - 1.0;
  50251. var lowestRoot = getLowestRoot(a, b, c, t);
  50252. if (lowestRoot.found) {
  50253. t = lowestRoot.root;
  50254. found = true;
  50255. this._collisionPoint.copyFrom(p1);
  50256. }
  50257. this._basePoint.subtractToRef(p2, this._tempVector);
  50258. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50259. c = this._tempVector.lengthSquared() - 1.0;
  50260. lowestRoot = getLowestRoot(a, b, c, t);
  50261. if (lowestRoot.found) {
  50262. t = lowestRoot.root;
  50263. found = true;
  50264. this._collisionPoint.copyFrom(p2);
  50265. }
  50266. this._basePoint.subtractToRef(p3, this._tempVector);
  50267. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50268. c = this._tempVector.lengthSquared() - 1.0;
  50269. lowestRoot = getLowestRoot(a, b, c, t);
  50270. if (lowestRoot.found) {
  50271. t = lowestRoot.root;
  50272. found = true;
  50273. this._collisionPoint.copyFrom(p3);
  50274. }
  50275. p2.subtractToRef(p1, this._edge);
  50276. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50277. var edgeSquaredLength = this._edge.lengthSquared();
  50278. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50279. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50280. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50281. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50282. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50283. lowestRoot = getLowestRoot(a, b, c, t);
  50284. if (lowestRoot.found) {
  50285. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50286. if (f >= 0.0 && f <= 1.0) {
  50287. t = lowestRoot.root;
  50288. found = true;
  50289. this._edge.scaleInPlace(f);
  50290. p1.addToRef(this._edge, this._collisionPoint);
  50291. }
  50292. }
  50293. p3.subtractToRef(p2, this._edge);
  50294. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50295. edgeSquaredLength = this._edge.lengthSquared();
  50296. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50297. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50298. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50299. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50300. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50301. lowestRoot = getLowestRoot(a, b, c, t);
  50302. if (lowestRoot.found) {
  50303. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50304. if (f >= 0.0 && f <= 1.0) {
  50305. t = lowestRoot.root;
  50306. found = true;
  50307. this._edge.scaleInPlace(f);
  50308. p2.addToRef(this._edge, this._collisionPoint);
  50309. }
  50310. }
  50311. p1.subtractToRef(p3, this._edge);
  50312. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50313. edgeSquaredLength = this._edge.lengthSquared();
  50314. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50315. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50316. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50317. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50318. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50319. lowestRoot = getLowestRoot(a, b, c, t);
  50320. if (lowestRoot.found) {
  50321. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50322. if (f >= 0.0 && f <= 1.0) {
  50323. t = lowestRoot.root;
  50324. found = true;
  50325. this._edge.scaleInPlace(f);
  50326. p3.addToRef(this._edge, this._collisionPoint);
  50327. }
  50328. }
  50329. }
  50330. if (found) {
  50331. var distToCollision = t * this._velocity.length();
  50332. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50333. if (!this.intersectionPoint) {
  50334. this.intersectionPoint = this._collisionPoint.clone();
  50335. }
  50336. else {
  50337. this.intersectionPoint.copyFrom(this._collisionPoint);
  50338. }
  50339. this._nearestDistance = distToCollision;
  50340. this.collisionFound = true;
  50341. }
  50342. }
  50343. };
  50344. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50345. for (var i = indexStart; i < indexEnd; i += 3) {
  50346. var p1 = pts[indices[i] - decal];
  50347. var p2 = pts[indices[i + 1] - decal];
  50348. var p3 = pts[indices[i + 2] - decal];
  50349. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50350. }
  50351. };
  50352. Collider.prototype._getResponse = function (pos, vel) {
  50353. pos.addToRef(vel, this._destinationPoint);
  50354. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50355. this._basePoint.addToRef(vel, pos);
  50356. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50357. this._slidePlaneNormal.normalize();
  50358. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50359. pos.addInPlace(this._displacementVector);
  50360. this.intersectionPoint.addInPlace(this._displacementVector);
  50361. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50362. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50363. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50364. };
  50365. return Collider;
  50366. }());
  50367. BABYLON.Collider = Collider;
  50368. })(BABYLON || (BABYLON = {}));
  50369. //# sourceMappingURL=babylon.collider.js.map
  50370. var BABYLON;
  50371. (function (BABYLON) {
  50372. //WebWorker code will be inserted to this variable.
  50373. BABYLON.CollisionWorker = "";
  50374. var WorkerTaskType;
  50375. (function (WorkerTaskType) {
  50376. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50377. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50378. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50379. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50380. var WorkerReplyType;
  50381. (function (WorkerReplyType) {
  50382. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50383. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50384. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50385. var CollisionCoordinatorWorker = /** @class */ (function () {
  50386. function CollisionCoordinatorWorker() {
  50387. var _this = this;
  50388. this._scaledPosition = BABYLON.Vector3.Zero();
  50389. this._scaledVelocity = BABYLON.Vector3.Zero();
  50390. this.onMeshUpdated = function (transformNode) {
  50391. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50392. };
  50393. this.onGeometryUpdated = function (geometry) {
  50394. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50395. };
  50396. this._afterRender = function () {
  50397. if (!_this._init)
  50398. return;
  50399. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50400. return;
  50401. }
  50402. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50403. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50404. if (_this._runningUpdated > 4) {
  50405. return;
  50406. }
  50407. ++_this._runningUpdated;
  50408. var payload = {
  50409. updatedMeshes: _this._addUpdateMeshesList,
  50410. updatedGeometries: _this._addUpdateGeometriesList,
  50411. removedGeometries: _this._toRemoveGeometryArray,
  50412. removedMeshes: _this._toRemoveMeshesArray
  50413. };
  50414. var message = {
  50415. payload: payload,
  50416. taskType: WorkerTaskType.UPDATE
  50417. };
  50418. var serializable = [];
  50419. for (var id in payload.updatedGeometries) {
  50420. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50421. //prepare transferables
  50422. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50423. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50424. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50425. }
  50426. }
  50427. _this._worker.postMessage(message, serializable);
  50428. _this._addUpdateMeshesList = {};
  50429. _this._addUpdateGeometriesList = {};
  50430. _this._toRemoveGeometryArray = [];
  50431. _this._toRemoveMeshesArray = [];
  50432. };
  50433. this._onMessageFromWorker = function (e) {
  50434. var returnData = e.data;
  50435. if (returnData.error != WorkerReplyType.SUCCESS) {
  50436. //TODO what errors can be returned from the worker?
  50437. BABYLON.Tools.Warn("error returned from worker!");
  50438. return;
  50439. }
  50440. switch (returnData.taskType) {
  50441. case WorkerTaskType.INIT:
  50442. _this._init = true;
  50443. //Update the worked with ALL of the scene's current state
  50444. _this._scene.meshes.forEach(function (mesh) {
  50445. _this.onMeshAdded(mesh);
  50446. });
  50447. _this._scene.getGeometries().forEach(function (geometry) {
  50448. _this.onGeometryAdded(geometry);
  50449. });
  50450. break;
  50451. case WorkerTaskType.UPDATE:
  50452. _this._runningUpdated--;
  50453. break;
  50454. case WorkerTaskType.COLLIDE:
  50455. var returnPayload = returnData.payload;
  50456. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50457. return;
  50458. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50459. if (callback) {
  50460. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50461. if (mesh) {
  50462. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50463. }
  50464. }
  50465. //cleanup
  50466. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50467. break;
  50468. }
  50469. };
  50470. this._collisionsCallbackArray = [];
  50471. this._init = false;
  50472. this._runningUpdated = 0;
  50473. this._addUpdateMeshesList = {};
  50474. this._addUpdateGeometriesList = {};
  50475. this._toRemoveGeometryArray = [];
  50476. this._toRemoveMeshesArray = [];
  50477. }
  50478. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50479. if (!this._init)
  50480. return;
  50481. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50482. return;
  50483. position.divideToRef(collider._radius, this._scaledPosition);
  50484. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50485. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50486. var payload = {
  50487. collider: {
  50488. position: this._scaledPosition.asArray(),
  50489. velocity: this._scaledVelocity.asArray(),
  50490. radius: collider._radius.asArray()
  50491. },
  50492. collisionId: collisionIndex,
  50493. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50494. maximumRetry: maximumRetry
  50495. };
  50496. var message = {
  50497. payload: payload,
  50498. taskType: WorkerTaskType.COLLIDE
  50499. };
  50500. this._worker.postMessage(message);
  50501. };
  50502. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50503. this._scene = scene;
  50504. this._scene.registerAfterRender(this._afterRender);
  50505. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50506. this._worker = new Worker(workerUrl);
  50507. this._worker.onmessage = this._onMessageFromWorker;
  50508. var message = {
  50509. payload: {},
  50510. taskType: WorkerTaskType.INIT
  50511. };
  50512. this._worker.postMessage(message);
  50513. };
  50514. CollisionCoordinatorWorker.prototype.destroy = function () {
  50515. this._scene.unregisterAfterRender(this._afterRender);
  50516. this._worker.terminate();
  50517. };
  50518. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50519. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50520. this.onMeshUpdated(mesh);
  50521. };
  50522. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50523. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50524. };
  50525. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50526. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50527. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50528. this.onGeometryUpdated(geometry);
  50529. };
  50530. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50531. this._toRemoveGeometryArray.push(geometry.id);
  50532. };
  50533. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50534. var submeshes = [];
  50535. if (mesh.subMeshes) {
  50536. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50537. var boundingInfo = sm.getBoundingInfo();
  50538. return {
  50539. position: idx,
  50540. verticesStart: sm.verticesStart,
  50541. verticesCount: sm.verticesCount,
  50542. indexStart: sm.indexStart,
  50543. indexCount: sm.indexCount,
  50544. hasMaterial: !!sm.getMaterial(),
  50545. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50546. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50547. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50548. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50549. };
  50550. });
  50551. }
  50552. var geometryId = null;
  50553. if (mesh instanceof BABYLON.Mesh) {
  50554. var geometry = mesh.geometry;
  50555. geometryId = geometry ? geometry.id : null;
  50556. }
  50557. else if (mesh instanceof BABYLON.InstancedMesh) {
  50558. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50559. geometryId = geometry ? geometry.id : null;
  50560. }
  50561. var boundingInfo = mesh.getBoundingInfo();
  50562. return {
  50563. uniqueId: mesh.uniqueId,
  50564. id: mesh.id,
  50565. name: mesh.name,
  50566. geometryId: geometryId,
  50567. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50568. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50569. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50570. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50571. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50572. subMeshes: submeshes,
  50573. checkCollisions: mesh.checkCollisions
  50574. };
  50575. };
  50576. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50577. return {
  50578. id: geometry.id,
  50579. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50580. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50581. indices: new Uint32Array(geometry.getIndices() || []),
  50582. };
  50583. };
  50584. return CollisionCoordinatorWorker;
  50585. }());
  50586. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50587. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50588. function CollisionCoordinatorLegacy() {
  50589. this._scaledPosition = BABYLON.Vector3.Zero();
  50590. this._scaledVelocity = BABYLON.Vector3.Zero();
  50591. this._finalPosition = BABYLON.Vector3.Zero();
  50592. }
  50593. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50594. position.divideToRef(collider._radius, this._scaledPosition);
  50595. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50596. collider.collidedMesh = null;
  50597. collider._retry = 0;
  50598. collider._initialVelocity = this._scaledVelocity;
  50599. collider._initialPosition = this._scaledPosition;
  50600. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50601. this._finalPosition.multiplyInPlace(collider._radius);
  50602. //run the callback
  50603. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50604. };
  50605. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50606. this._scene = scene;
  50607. };
  50608. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50609. //Legacy need no destruction method.
  50610. };
  50611. //No update in legacy mode
  50612. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50613. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50614. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50615. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50616. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50617. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50618. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50619. if (excludedMesh === void 0) { excludedMesh = null; }
  50620. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50621. if (collider._retry >= maximumRetry) {
  50622. finalPosition.copyFrom(position);
  50623. return;
  50624. }
  50625. // Check if this is a mesh else camera or -1
  50626. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50627. collider._initialize(position, velocity, closeDistance);
  50628. // Check all meshes
  50629. for (var index = 0; index < this._scene.meshes.length; index++) {
  50630. var mesh = this._scene.meshes[index];
  50631. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50632. mesh._checkCollision(collider);
  50633. }
  50634. }
  50635. if (!collider.collisionFound) {
  50636. position.addToRef(velocity, finalPosition);
  50637. return;
  50638. }
  50639. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50640. collider._getResponse(position, velocity);
  50641. }
  50642. if (velocity.length() <= closeDistance) {
  50643. finalPosition.copyFrom(position);
  50644. return;
  50645. }
  50646. collider._retry++;
  50647. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50648. };
  50649. return CollisionCoordinatorLegacy;
  50650. }());
  50651. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50652. })(BABYLON || (BABYLON = {}));
  50653. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50654. var BABYLON;
  50655. (function (BABYLON) {
  50656. /**
  50657. * A particle represents one of the element emitted by a particle system.
  50658. * This is mainly define by its coordinates, direction, velocity and age.
  50659. */
  50660. var Particle = /** @class */ (function () {
  50661. /**
  50662. * Creates a new instance of @see Particle
  50663. * @param particleSystem the particle system the particle belongs to
  50664. */
  50665. function Particle(particleSystem) {
  50666. this.particleSystem = particleSystem;
  50667. /**
  50668. * The world position of the particle in the scene.
  50669. */
  50670. this.position = BABYLON.Vector3.Zero();
  50671. /**
  50672. * The world direction of the particle in the scene.
  50673. */
  50674. this.direction = BABYLON.Vector3.Zero();
  50675. /**
  50676. * The color of the particle.
  50677. */
  50678. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50679. /**
  50680. * The color change of the particle per step.
  50681. */
  50682. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50683. /**
  50684. * Defines how long will the life of the particle be.
  50685. */
  50686. this.lifeTime = 1.0;
  50687. /**
  50688. * The current age of the particle.
  50689. */
  50690. this.age = 0;
  50691. /**
  50692. * The current size of the particle.
  50693. */
  50694. this.size = 0;
  50695. /**
  50696. * The current angle of the particle.
  50697. */
  50698. this.angle = 0;
  50699. /**
  50700. * Defines how fast is the angle changing.
  50701. */
  50702. this.angularSpeed = 0;
  50703. /**
  50704. * Defines the cell index used by the particle to be rendered from a sprite.
  50705. */
  50706. this.cellIndex = 0;
  50707. this._currentFrameCounter = 0;
  50708. if (!this.particleSystem.isAnimationSheetEnabled) {
  50709. return;
  50710. }
  50711. this.cellIndex = this.particleSystem.startSpriteCellID;
  50712. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50713. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50714. }
  50715. else {
  50716. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50717. }
  50718. }
  50719. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50720. // (ageOffset / scaledUpdateSpeed) / available cells
  50721. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50722. this._currentFrameCounter += scaledUpdateSpeed;
  50723. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50724. this._currentFrameCounter = 0;
  50725. this.cellIndex++;
  50726. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50727. this.cellIndex = this.particleSystem.endSpriteCellID;
  50728. }
  50729. }
  50730. };
  50731. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50732. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50733. this.cellIndex++;
  50734. this._currentFrameCounter = 0;
  50735. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50736. if (this.particleSystem.spriteCellLoop) {
  50737. this.cellIndex = this.particleSystem.startSpriteCellID;
  50738. }
  50739. else {
  50740. this.cellIndex = this.particleSystem.endSpriteCellID;
  50741. }
  50742. }
  50743. }
  50744. else {
  50745. this._currentFrameCounter++;
  50746. }
  50747. };
  50748. /**
  50749. * Copy the properties of particle to another one.
  50750. * @param other the particle to copy the information to.
  50751. */
  50752. Particle.prototype.copyTo = function (other) {
  50753. other.position.copyFrom(this.position);
  50754. other.direction.copyFrom(this.direction);
  50755. other.color.copyFrom(this.color);
  50756. other.colorStep.copyFrom(this.colorStep);
  50757. other.lifeTime = this.lifeTime;
  50758. other.age = this.age;
  50759. other.size = this.size;
  50760. other.angle = this.angle;
  50761. other.angularSpeed = this.angularSpeed;
  50762. other.particleSystem = this.particleSystem;
  50763. other.cellIndex = this.cellIndex;
  50764. };
  50765. return Particle;
  50766. }());
  50767. BABYLON.Particle = Particle;
  50768. })(BABYLON || (BABYLON = {}));
  50769. //# sourceMappingURL=babylon.particle.js.map
  50770. var BABYLON;
  50771. (function (BABYLON) {
  50772. /**
  50773. * This represents a particle system in Babylon.
  50774. * 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.
  50775. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50776. * @example https://doc.babylonjs.com/babylon101/particles
  50777. */
  50778. var ParticleSystem = /** @class */ (function () {
  50779. /**
  50780. * Instantiates a particle system.
  50781. * 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.
  50782. * @param name The name of the particle system
  50783. * @param capacity The max number of particles alive at the same time
  50784. * @param scene The scene the particle system belongs to
  50785. * @param customEffect a custom effect used to change the way particles are rendered by default
  50786. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50787. * @param epsilon Offset used to render the particles
  50788. */
  50789. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50790. if (customEffect === void 0) { customEffect = null; }
  50791. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50792. if (epsilon === void 0) { epsilon = 0.01; }
  50793. var _this = this;
  50794. /**
  50795. * List of animations used by the particle system.
  50796. */
  50797. this.animations = [];
  50798. /**
  50799. * The rendering group used by the Particle system to chose when to render.
  50800. */
  50801. this.renderingGroupId = 0;
  50802. /**
  50803. * The emitter represents the Mesh or position we are attaching the particle system to.
  50804. */
  50805. this.emitter = null;
  50806. /**
  50807. * The maximum number of particles to emit per frame
  50808. */
  50809. this.emitRate = 10;
  50810. /**
  50811. * If you want to launch only a few particles at once, that can be done, as well.
  50812. */
  50813. this.manualEmitCount = -1;
  50814. /**
  50815. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50816. */
  50817. this.updateSpeed = 0.01;
  50818. /**
  50819. * The amount of time the particle system is running (depends of the overall update speed).
  50820. */
  50821. this.targetStopDuration = 0;
  50822. /**
  50823. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50824. */
  50825. this.disposeOnStop = false;
  50826. /**
  50827. * Minimum power of emitting particles.
  50828. */
  50829. this.minEmitPower = 1;
  50830. /**
  50831. * Maximum power of emitting particles.
  50832. */
  50833. this.maxEmitPower = 1;
  50834. /**
  50835. * Minimum life time of emitting particles.
  50836. */
  50837. this.minLifeTime = 1;
  50838. /**
  50839. * Maximum life time of emitting particles.
  50840. */
  50841. this.maxLifeTime = 1;
  50842. /**
  50843. * Minimum Size of emitting particles.
  50844. */
  50845. this.minSize = 1;
  50846. /**
  50847. * Maximum Size of emitting particles.
  50848. */
  50849. this.maxSize = 1;
  50850. /**
  50851. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50852. */
  50853. this.minAngularSpeed = 0;
  50854. /**
  50855. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50856. */
  50857. this.maxAngularSpeed = 0;
  50858. /**
  50859. * The layer mask we are rendering the particles through.
  50860. */
  50861. this.layerMask = 0x0FFFFFFF;
  50862. /**
  50863. * This can help using your own shader to render the particle system.
  50864. * The according effect will be created
  50865. */
  50866. this.customShader = null;
  50867. /**
  50868. * By default particle system starts as soon as they are created. This prevents the
  50869. * automatic start to happen and let you decide when to start emitting particles.
  50870. */
  50871. this.preventAutoStart = false;
  50872. /**
  50873. * Callback triggered when the particle animation is ending.
  50874. */
  50875. this.onAnimationEnd = null;
  50876. /**
  50877. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50878. */
  50879. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50880. /**
  50881. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50882. * to override the particles.
  50883. */
  50884. this.forceDepthWrite = false;
  50885. /**
  50886. * You can use gravity if you want to give an orientation to your particles.
  50887. */
  50888. this.gravity = BABYLON.Vector3.Zero();
  50889. /**
  50890. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50891. */
  50892. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50893. /**
  50894. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50895. */
  50896. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50897. /**
  50898. * Color the particle will have at the end of its lifetime.
  50899. */
  50900. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50901. /**
  50902. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50903. */
  50904. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50905. /**
  50906. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50907. */
  50908. this.spriteCellLoop = true;
  50909. /**
  50910. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50911. */
  50912. this.spriteCellChangeSpeed = 0;
  50913. /**
  50914. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50915. */
  50916. this.startSpriteCellID = 0;
  50917. /**
  50918. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50919. */
  50920. this.endSpriteCellID = 0;
  50921. /**
  50922. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50923. */
  50924. this.spriteCellWidth = 0;
  50925. /**
  50926. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50927. */
  50928. this.spriteCellHeight = 0;
  50929. /**
  50930. * An event triggered when the system is disposed.
  50931. */
  50932. this.onDisposeObservable = new BABYLON.Observable();
  50933. this._particles = new Array();
  50934. this._stockParticles = new Array();
  50935. this._newPartsExcess = 0;
  50936. this._vertexBuffers = {};
  50937. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50938. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50939. this._scaledDirection = BABYLON.Vector3.Zero();
  50940. this._scaledGravity = BABYLON.Vector3.Zero();
  50941. this._currentRenderId = -1;
  50942. this._started = false;
  50943. this._stopped = false;
  50944. this._actualFrame = 0;
  50945. this._vertexBufferSize = 11;
  50946. this._appendParticleVertexes = null;
  50947. this.id = name;
  50948. this.name = name;
  50949. this._capacity = capacity;
  50950. this._epsilon = epsilon;
  50951. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50952. if (isAnimationSheetEnabled) {
  50953. this._vertexBufferSize = 12;
  50954. }
  50955. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50956. this._customEffect = customEffect;
  50957. scene.particleSystems.push(this);
  50958. this._createIndexBuffer();
  50959. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50960. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50961. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50962. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50963. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50964. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50965. if (this._isAnimationSheetEnabled) {
  50966. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50967. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50968. }
  50969. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50970. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50971. this._vertexBuffers["options"] = options;
  50972. // Default emitter type
  50973. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50974. this.updateFunction = function (particles) {
  50975. for (var index = 0; index < particles.length; index++) {
  50976. var particle = particles[index];
  50977. particle.age += _this._scaledUpdateSpeed;
  50978. if (particle.age >= particle.lifeTime) {
  50979. _this.recycleParticle(particle);
  50980. index--;
  50981. continue;
  50982. }
  50983. else {
  50984. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50985. particle.color.addInPlace(_this._scaledColorStep);
  50986. if (particle.color.a < 0)
  50987. particle.color.a = 0;
  50988. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50989. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50990. particle.position.addInPlace(_this._scaledDirection);
  50991. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50992. particle.direction.addInPlace(_this._scaledGravity);
  50993. if (_this._isAnimationSheetEnabled) {
  50994. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50995. }
  50996. }
  50997. }
  50998. };
  50999. }
  51000. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51001. /**
  51002. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51003. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51004. */
  51005. get: function () {
  51006. if (this.particleEmitterType.direction1) {
  51007. return this.particleEmitterType.direction1;
  51008. }
  51009. return BABYLON.Vector3.Zero();
  51010. },
  51011. set: function (value) {
  51012. if (this.particleEmitterType.direction1) {
  51013. this.particleEmitterType.direction1 = value;
  51014. }
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51020. /**
  51021. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51022. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51023. */
  51024. get: function () {
  51025. if (this.particleEmitterType.direction2) {
  51026. return this.particleEmitterType.direction2;
  51027. }
  51028. return BABYLON.Vector3.Zero();
  51029. },
  51030. set: function (value) {
  51031. if (this.particleEmitterType.direction2) {
  51032. this.particleEmitterType.direction2 = value;
  51033. }
  51034. },
  51035. enumerable: true,
  51036. configurable: true
  51037. });
  51038. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51039. /**
  51040. * 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.
  51041. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51042. */
  51043. get: function () {
  51044. if (this.particleEmitterType.minEmitBox) {
  51045. return this.particleEmitterType.minEmitBox;
  51046. }
  51047. return BABYLON.Vector3.Zero();
  51048. },
  51049. set: function (value) {
  51050. if (this.particleEmitterType.minEmitBox) {
  51051. this.particleEmitterType.minEmitBox = value;
  51052. }
  51053. },
  51054. enumerable: true,
  51055. configurable: true
  51056. });
  51057. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51058. /**
  51059. * 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.
  51060. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51061. */
  51062. get: function () {
  51063. if (this.particleEmitterType.maxEmitBox) {
  51064. return this.particleEmitterType.maxEmitBox;
  51065. }
  51066. return BABYLON.Vector3.Zero();
  51067. },
  51068. set: function (value) {
  51069. if (this.particleEmitterType.maxEmitBox) {
  51070. this.particleEmitterType.maxEmitBox = value;
  51071. }
  51072. },
  51073. enumerable: true,
  51074. configurable: true
  51075. });
  51076. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51077. /**
  51078. * Sets a callback that will be triggered when the system is disposed.
  51079. */
  51080. set: function (callback) {
  51081. if (this._onDisposeObserver) {
  51082. this.onDisposeObservable.remove(this._onDisposeObserver);
  51083. }
  51084. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51085. },
  51086. enumerable: true,
  51087. configurable: true
  51088. });
  51089. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51090. /**
  51091. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51092. */
  51093. get: function () {
  51094. return this._isAnimationSheetEnabled;
  51095. },
  51096. enumerable: true,
  51097. configurable: true
  51098. });
  51099. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51100. /**
  51101. * Gets the current list of active particles
  51102. */
  51103. get: function () {
  51104. return this._particles;
  51105. },
  51106. enumerable: true,
  51107. configurable: true
  51108. });
  51109. /**
  51110. * Returns the string "ParticleSystem"
  51111. * @returns a string containing the class name
  51112. */
  51113. ParticleSystem.prototype.getClassName = function () {
  51114. return "ParticleSystem";
  51115. };
  51116. ParticleSystem.prototype._createIndexBuffer = function () {
  51117. var indices = [];
  51118. var index = 0;
  51119. for (var count = 0; count < this._capacity; count++) {
  51120. indices.push(index);
  51121. indices.push(index + 1);
  51122. indices.push(index + 2);
  51123. indices.push(index);
  51124. indices.push(index + 2);
  51125. indices.push(index + 3);
  51126. index += 4;
  51127. }
  51128. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51129. };
  51130. /**
  51131. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51132. * Its lifetime will start back at 0.
  51133. * @param particle The particle to recycle
  51134. */
  51135. ParticleSystem.prototype.recycleParticle = function (particle) {
  51136. var lastParticle = this._particles.pop();
  51137. if (lastParticle !== particle) {
  51138. lastParticle.copyTo(particle);
  51139. this._stockParticles.push(lastParticle);
  51140. }
  51141. };
  51142. /**
  51143. * Gets the maximum number of particles active at the same time.
  51144. * @returns The max number of active particles.
  51145. */
  51146. ParticleSystem.prototype.getCapacity = function () {
  51147. return this._capacity;
  51148. };
  51149. /**
  51150. * Gets Wether there are still active particles in the system.
  51151. * @returns True if it is alive, otherwise false.
  51152. */
  51153. ParticleSystem.prototype.isAlive = function () {
  51154. return this._alive;
  51155. };
  51156. /**
  51157. * Gets Wether the system has been started.
  51158. * @returns True if it has been started, otherwise false.
  51159. */
  51160. ParticleSystem.prototype.isStarted = function () {
  51161. return this._started;
  51162. };
  51163. /**
  51164. * Starts the particle system and begins to emit.
  51165. */
  51166. ParticleSystem.prototype.start = function () {
  51167. this._started = true;
  51168. this._stopped = false;
  51169. this._actualFrame = 0;
  51170. };
  51171. /**
  51172. * Stops the particle system.
  51173. */
  51174. ParticleSystem.prototype.stop = function () {
  51175. this._stopped = true;
  51176. };
  51177. /**
  51178. * Remove all active particles
  51179. */
  51180. ParticleSystem.prototype.reset = function () {
  51181. this._stockParticles = [];
  51182. this._particles = [];
  51183. };
  51184. /**
  51185. * @ignore (for internal use only)
  51186. */
  51187. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51188. var offset = index * this._vertexBufferSize;
  51189. this._vertexData[offset] = particle.position.x;
  51190. this._vertexData[offset + 1] = particle.position.y;
  51191. this._vertexData[offset + 2] = particle.position.z;
  51192. this._vertexData[offset + 3] = particle.color.r;
  51193. this._vertexData[offset + 4] = particle.color.g;
  51194. this._vertexData[offset + 5] = particle.color.b;
  51195. this._vertexData[offset + 6] = particle.color.a;
  51196. this._vertexData[offset + 7] = particle.angle;
  51197. this._vertexData[offset + 8] = particle.size;
  51198. this._vertexData[offset + 9] = offsetX;
  51199. this._vertexData[offset + 10] = offsetY;
  51200. };
  51201. /**
  51202. * @ignore (for internal use only)
  51203. */
  51204. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51205. if (offsetX === 0)
  51206. offsetX = this._epsilon;
  51207. else if (offsetX === 1)
  51208. offsetX = 1 - this._epsilon;
  51209. if (offsetY === 0)
  51210. offsetY = this._epsilon;
  51211. else if (offsetY === 1)
  51212. offsetY = 1 - this._epsilon;
  51213. var offset = index * this._vertexBufferSize;
  51214. this._vertexData[offset] = particle.position.x;
  51215. this._vertexData[offset + 1] = particle.position.y;
  51216. this._vertexData[offset + 2] = particle.position.z;
  51217. this._vertexData[offset + 3] = particle.color.r;
  51218. this._vertexData[offset + 4] = particle.color.g;
  51219. this._vertexData[offset + 5] = particle.color.b;
  51220. this._vertexData[offset + 6] = particle.color.a;
  51221. this._vertexData[offset + 7] = particle.angle;
  51222. this._vertexData[offset + 8] = particle.size;
  51223. this._vertexData[offset + 9] = offsetX;
  51224. this._vertexData[offset + 10] = offsetY;
  51225. this._vertexData[offset + 11] = particle.cellIndex;
  51226. };
  51227. ParticleSystem.prototype._update = function (newParticles) {
  51228. // Update current
  51229. this._alive = this._particles.length > 0;
  51230. this.updateFunction(this._particles);
  51231. // Add new ones
  51232. var worldMatrix;
  51233. if (this.emitter.position) {
  51234. var emitterMesh = this.emitter;
  51235. worldMatrix = emitterMesh.getWorldMatrix();
  51236. }
  51237. else {
  51238. var emitterPosition = this.emitter;
  51239. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51240. }
  51241. var particle;
  51242. for (var index = 0; index < newParticles; index++) {
  51243. if (this._particles.length === this._capacity) {
  51244. break;
  51245. }
  51246. if (this._stockParticles.length !== 0) {
  51247. particle = this._stockParticles.pop();
  51248. particle.age = 0;
  51249. particle.cellIndex = this.startSpriteCellID;
  51250. }
  51251. else {
  51252. particle = new BABYLON.Particle(this);
  51253. }
  51254. this._particles.push(particle);
  51255. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51256. if (this.startPositionFunction) {
  51257. this.startPositionFunction(worldMatrix, particle.position, particle);
  51258. }
  51259. else {
  51260. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51261. }
  51262. if (this.startDirectionFunction) {
  51263. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51264. }
  51265. else {
  51266. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51267. }
  51268. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51269. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51270. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51271. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51272. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51273. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51274. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51275. }
  51276. };
  51277. ParticleSystem.prototype._getEffect = function () {
  51278. if (this._customEffect) {
  51279. return this._customEffect;
  51280. }
  51281. ;
  51282. var defines = [];
  51283. if (this._scene.clipPlane) {
  51284. defines.push("#define CLIPPLANE");
  51285. }
  51286. if (this._isAnimationSheetEnabled) {
  51287. defines.push("#define ANIMATESHEET");
  51288. }
  51289. // Effect
  51290. var join = defines.join("\n");
  51291. if (this._cachedDefines !== join) {
  51292. this._cachedDefines = join;
  51293. var attributesNamesOrOptions;
  51294. var effectCreationOption;
  51295. if (this._isAnimationSheetEnabled) {
  51296. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51297. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51298. }
  51299. else {
  51300. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51301. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51302. }
  51303. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51304. }
  51305. return this._effect;
  51306. };
  51307. /**
  51308. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51309. */
  51310. ParticleSystem.prototype.animate = function () {
  51311. if (!this._started)
  51312. return;
  51313. var effect = this._getEffect();
  51314. // Check
  51315. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51316. return;
  51317. if (this._currentRenderId === this._scene.getRenderId()) {
  51318. return;
  51319. }
  51320. this._currentRenderId = this._scene.getRenderId();
  51321. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51322. // determine the number of particles we need to create
  51323. var newParticles;
  51324. if (this.manualEmitCount > -1) {
  51325. newParticles = this.manualEmitCount;
  51326. this._newPartsExcess = 0;
  51327. this.manualEmitCount = 0;
  51328. }
  51329. else {
  51330. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51331. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51332. }
  51333. if (this._newPartsExcess > 1.0) {
  51334. newParticles += this._newPartsExcess >> 0;
  51335. this._newPartsExcess -= this._newPartsExcess >> 0;
  51336. }
  51337. this._alive = false;
  51338. if (!this._stopped) {
  51339. this._actualFrame += this._scaledUpdateSpeed;
  51340. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51341. this.stop();
  51342. }
  51343. else {
  51344. newParticles = 0;
  51345. }
  51346. this._update(newParticles);
  51347. // Stopped?
  51348. if (this._stopped) {
  51349. if (!this._alive) {
  51350. this._started = false;
  51351. if (this.onAnimationEnd) {
  51352. this.onAnimationEnd();
  51353. }
  51354. if (this.disposeOnStop) {
  51355. this._scene._toBeDisposed.push(this);
  51356. }
  51357. }
  51358. }
  51359. // Animation sheet
  51360. if (this._isAnimationSheetEnabled) {
  51361. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51362. }
  51363. else {
  51364. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51365. }
  51366. // Update VBO
  51367. var offset = 0;
  51368. for (var index = 0; index < this._particles.length; index++) {
  51369. var particle = this._particles[index];
  51370. this._appendParticleVertexes(offset, particle);
  51371. offset += 4;
  51372. }
  51373. if (this._vertexBuffer) {
  51374. this._vertexBuffer.update(this._vertexData);
  51375. }
  51376. };
  51377. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51378. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51379. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51380. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51381. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51382. };
  51383. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51384. this._appendParticleVertex(offset++, particle, 0, 0);
  51385. this._appendParticleVertex(offset++, particle, 1, 0);
  51386. this._appendParticleVertex(offset++, particle, 1, 1);
  51387. this._appendParticleVertex(offset++, particle, 0, 1);
  51388. };
  51389. /**
  51390. * Rebuilds the particle system.
  51391. */
  51392. ParticleSystem.prototype.rebuild = function () {
  51393. this._createIndexBuffer();
  51394. if (this._vertexBuffer) {
  51395. this._vertexBuffer._rebuild();
  51396. }
  51397. };
  51398. /**
  51399. * Renders the particle system in its current state.
  51400. * @returns the current number of particles
  51401. */
  51402. ParticleSystem.prototype.render = function () {
  51403. var effect = this._getEffect();
  51404. // Check
  51405. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51406. return 0;
  51407. }
  51408. var engine = this._scene.getEngine();
  51409. // Render
  51410. engine.enableEffect(effect);
  51411. engine.setState(false);
  51412. var viewMatrix = this._scene.getViewMatrix();
  51413. effect.setTexture("diffuseSampler", this.particleTexture);
  51414. effect.setMatrix("view", viewMatrix);
  51415. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51416. if (this._isAnimationSheetEnabled) {
  51417. var baseSize = this.particleTexture.getBaseSize();
  51418. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51419. }
  51420. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51421. if (this._scene.clipPlane) {
  51422. var clipPlane = this._scene.clipPlane;
  51423. var invView = viewMatrix.clone();
  51424. invView.invert();
  51425. effect.setMatrix("invView", invView);
  51426. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51427. }
  51428. // VBOs
  51429. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51430. // Draw order
  51431. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51432. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51433. }
  51434. else {
  51435. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51436. }
  51437. if (this.forceDepthWrite) {
  51438. engine.setDepthWrite(true);
  51439. }
  51440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51441. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51442. return this._particles.length;
  51443. };
  51444. /**
  51445. * Disposes the particle system and free the associated resources
  51446. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51447. */
  51448. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51449. if (disposeTexture === void 0) { disposeTexture = true; }
  51450. if (this._vertexBuffer) {
  51451. this._vertexBuffer.dispose();
  51452. this._vertexBuffer = null;
  51453. }
  51454. if (this._indexBuffer) {
  51455. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51456. this._indexBuffer = null;
  51457. }
  51458. if (disposeTexture && this.particleTexture) {
  51459. this.particleTexture.dispose();
  51460. this.particleTexture = null;
  51461. }
  51462. // Remove from scene
  51463. var index = this._scene.particleSystems.indexOf(this);
  51464. if (index > -1) {
  51465. this._scene.particleSystems.splice(index, 1);
  51466. }
  51467. // Callback
  51468. this.onDisposeObservable.notifyObservers(this);
  51469. this.onDisposeObservable.clear();
  51470. };
  51471. /**
  51472. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51473. * @param radius The radius of the sphere to emit from
  51474. * @returns the emitter
  51475. */
  51476. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51477. if (radius === void 0) { radius = 1; }
  51478. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51479. this.particleEmitterType = particleEmitter;
  51480. return particleEmitter;
  51481. };
  51482. /**
  51483. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51484. * @param radius The radius of the sphere to emit from
  51485. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51486. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51487. * @returns the emitter
  51488. */
  51489. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51490. if (radius === void 0) { radius = 1; }
  51491. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51492. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51493. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51494. this.particleEmitterType = particleEmitter;
  51495. return particleEmitter;
  51496. };
  51497. /**
  51498. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51499. * @param radius The radius of the cone to emit from
  51500. * @param angle The base angle of the cone
  51501. * @returns the emitter
  51502. */
  51503. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51504. if (radius === void 0) { radius = 1; }
  51505. if (angle === void 0) { angle = Math.PI / 4; }
  51506. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51507. this.particleEmitterType = particleEmitter;
  51508. return particleEmitter;
  51509. };
  51510. // 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.
  51511. /**
  51512. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51513. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51514. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51515. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51516. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51517. * @returns the emitter
  51518. */
  51519. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51520. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51521. this.direction1 = direction1;
  51522. this.direction2 = direction2;
  51523. this.minEmitBox = minEmitBox;
  51524. this.maxEmitBox = maxEmitBox;
  51525. this.particleEmitterType = particleEmitter;
  51526. return particleEmitter;
  51527. };
  51528. /**
  51529. * Clones the particle system.
  51530. * @param name The name of the cloned object
  51531. * @param newEmitter The new emitter to use
  51532. * @returns the cloned particle system
  51533. */
  51534. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51535. var custom = null;
  51536. var program = null;
  51537. if (this.customShader != null) {
  51538. program = this.customShader;
  51539. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51540. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51541. }
  51542. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51543. result.customShader = program;
  51544. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51545. if (newEmitter === undefined) {
  51546. newEmitter = this.emitter;
  51547. }
  51548. result.emitter = newEmitter;
  51549. if (this.particleTexture) {
  51550. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51551. }
  51552. if (!this.preventAutoStart) {
  51553. result.start();
  51554. }
  51555. return result;
  51556. };
  51557. /**
  51558. * Serializes the particle system to a JSON object.
  51559. * @returns the JSON object
  51560. */
  51561. ParticleSystem.prototype.serialize = function () {
  51562. var serializationObject = {};
  51563. serializationObject.name = this.name;
  51564. serializationObject.id = this.id;
  51565. // Emitter
  51566. if (this.emitter.position) {
  51567. var emitterMesh = this.emitter;
  51568. serializationObject.emitterId = emitterMesh.id;
  51569. }
  51570. else {
  51571. var emitterPosition = this.emitter;
  51572. serializationObject.emitter = emitterPosition.asArray();
  51573. }
  51574. serializationObject.capacity = this.getCapacity();
  51575. if (this.particleTexture) {
  51576. serializationObject.textureName = this.particleTexture.name;
  51577. }
  51578. // Animations
  51579. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51580. // Particle system
  51581. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51582. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51583. serializationObject.minSize = this.minSize;
  51584. serializationObject.maxSize = this.maxSize;
  51585. serializationObject.minEmitPower = this.minEmitPower;
  51586. serializationObject.maxEmitPower = this.maxEmitPower;
  51587. serializationObject.minLifeTime = this.minLifeTime;
  51588. serializationObject.maxLifeTime = this.maxLifeTime;
  51589. serializationObject.emitRate = this.emitRate;
  51590. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51591. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51592. serializationObject.gravity = this.gravity.asArray();
  51593. serializationObject.direction1 = this.direction1.asArray();
  51594. serializationObject.direction2 = this.direction2.asArray();
  51595. serializationObject.color1 = this.color1.asArray();
  51596. serializationObject.color2 = this.color2.asArray();
  51597. serializationObject.colorDead = this.colorDead.asArray();
  51598. serializationObject.updateSpeed = this.updateSpeed;
  51599. serializationObject.targetStopDuration = this.targetStopDuration;
  51600. serializationObject.textureMask = this.textureMask.asArray();
  51601. serializationObject.blendMode = this.blendMode;
  51602. serializationObject.customShader = this.customShader;
  51603. serializationObject.preventAutoStart = this.preventAutoStart;
  51604. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51605. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51606. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51607. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51608. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51609. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51610. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51611. // Emitter
  51612. if (this.particleEmitterType) {
  51613. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51614. }
  51615. return serializationObject;
  51616. };
  51617. /**
  51618. * Parses a JSON object to create a particle system.
  51619. * @param parsedParticleSystem The JSON object to parse
  51620. * @param scene The scene to create the particle system in
  51621. * @param rootUrl The root url to use to load external dependencies like texture
  51622. * @returns the Parsed particle system
  51623. */
  51624. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51625. var name = parsedParticleSystem.name;
  51626. var custom = null;
  51627. var program = null;
  51628. if (parsedParticleSystem.customShader) {
  51629. program = parsedParticleSystem.customShader;
  51630. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51631. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51632. }
  51633. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51634. particleSystem.customShader = program;
  51635. if (parsedParticleSystem.id) {
  51636. particleSystem.id = parsedParticleSystem.id;
  51637. }
  51638. // Auto start
  51639. if (parsedParticleSystem.preventAutoStart) {
  51640. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51641. }
  51642. // Texture
  51643. if (parsedParticleSystem.textureName) {
  51644. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51645. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51646. }
  51647. // Emitter
  51648. if (parsedParticleSystem.emitterId) {
  51649. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51650. }
  51651. else {
  51652. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51653. }
  51654. // Animations
  51655. if (parsedParticleSystem.animations) {
  51656. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51657. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51658. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51659. }
  51660. }
  51661. if (parsedParticleSystem.autoAnimate) {
  51662. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51663. }
  51664. // Particle system
  51665. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51666. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51667. particleSystem.minSize = parsedParticleSystem.minSize;
  51668. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51669. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51670. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51671. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51672. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51673. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51674. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51675. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51676. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51677. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51678. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51679. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51680. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51681. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51682. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51683. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51684. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51685. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51686. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51687. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51688. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51689. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51690. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51691. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51692. if (!particleSystem.preventAutoStart) {
  51693. particleSystem.start();
  51694. }
  51695. return particleSystem;
  51696. };
  51697. /**
  51698. * Source color is added to the destination color without alpha affecting the result.
  51699. */
  51700. ParticleSystem.BLENDMODE_ONEONE = 0;
  51701. /**
  51702. * Blend current color and particle color using particle’s alpha.
  51703. */
  51704. ParticleSystem.BLENDMODE_STANDARD = 1;
  51705. return ParticleSystem;
  51706. }());
  51707. BABYLON.ParticleSystem = ParticleSystem;
  51708. })(BABYLON || (BABYLON = {}));
  51709. //# sourceMappingURL=babylon.particleSystem.js.map
  51710. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51711. var BABYLON;
  51712. (function (BABYLON) {
  51713. /**
  51714. * Particle emitter emitting particles from the inside of a box.
  51715. * It emits the particles randomly between 2 given directions.
  51716. */
  51717. var BoxParticleEmitter = /** @class */ (function () {
  51718. /**
  51719. * Creates a new instance of @see BoxParticleEmitter
  51720. */
  51721. function BoxParticleEmitter() {
  51722. /**
  51723. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51724. */
  51725. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51726. /**
  51727. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51728. */
  51729. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51730. /**
  51731. * 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.
  51732. */
  51733. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51734. /**
  51735. * 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.
  51736. */
  51737. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51738. }
  51739. /**
  51740. * Called by the particle System when the direction is computed for the created particle.
  51741. * @param emitPower is the power of the particle (speed)
  51742. * @param worldMatrix is the world matrix of the particle system
  51743. * @param directionToUpdate is the direction vector to update with the result
  51744. * @param particle is the particle we are computed the direction for
  51745. */
  51746. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51747. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51748. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51749. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51750. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51751. };
  51752. /**
  51753. * Called by the particle System when the position is computed for the created particle.
  51754. * @param worldMatrix is the world matrix of the particle system
  51755. * @param positionToUpdate is the position vector to update with the result
  51756. * @param particle is the particle we are computed the position for
  51757. */
  51758. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51759. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51760. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51761. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51762. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51763. };
  51764. /**
  51765. * Clones the current emitter and returns a copy of it
  51766. * @returns the new emitter
  51767. */
  51768. BoxParticleEmitter.prototype.clone = function () {
  51769. var newOne = new BoxParticleEmitter();
  51770. BABYLON.Tools.DeepCopy(this, newOne);
  51771. return newOne;
  51772. };
  51773. /**
  51774. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51775. * @param effect defines the update shader
  51776. */
  51777. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51778. effect.setVector3("direction1", this.direction1);
  51779. effect.setVector3("direction2", this.direction2);
  51780. effect.setVector3("minEmitBox", this.minEmitBox);
  51781. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51782. };
  51783. /**
  51784. * Returns a string to use to update the GPU particles update shader
  51785. * @returns a string containng the defines string
  51786. */
  51787. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51788. return "#define BOXEMITTER";
  51789. };
  51790. /**
  51791. * Returns the string "BoxEmitter"
  51792. * @returns a string containing the class name
  51793. */
  51794. BoxParticleEmitter.prototype.getClassName = function () {
  51795. return "BoxEmitter";
  51796. };
  51797. /**
  51798. * Serializes the particle system to a JSON object.
  51799. * @returns the JSON object
  51800. */
  51801. BoxParticleEmitter.prototype.serialize = function () {
  51802. var serializationObject = {};
  51803. serializationObject.type = this.getClassName();
  51804. serializationObject.direction1 = this.direction1.asArray();
  51805. ;
  51806. serializationObject.direction2 = this.direction2.asArray();
  51807. ;
  51808. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51809. ;
  51810. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51811. ;
  51812. return serializationObject;
  51813. };
  51814. /**
  51815. * Parse properties from a JSON object
  51816. * @param serializationObject defines the JSON object
  51817. */
  51818. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51819. this.direction1.copyFrom(serializationObject.direction1);
  51820. this.direction2.copyFrom(serializationObject.direction2);
  51821. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51822. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51823. };
  51824. return BoxParticleEmitter;
  51825. }());
  51826. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51827. })(BABYLON || (BABYLON = {}));
  51828. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51829. var BABYLON;
  51830. (function (BABYLON) {
  51831. /**
  51832. * Particle emitter emitting particles from the inside of a cone.
  51833. * It emits the particles alongside the cone volume from the base to the particle.
  51834. * The emission direction might be randomized.
  51835. */
  51836. var ConeParticleEmitter = /** @class */ (function () {
  51837. /**
  51838. * Creates a new instance of @see ConeParticleEmitter
  51839. * @param radius the radius of the emission cone (1 by default)
  51840. * @param angles the cone base angle (PI by default)
  51841. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51842. */
  51843. function ConeParticleEmitter(radius,
  51844. /**
  51845. * The radius of the emission cone.
  51846. */
  51847. angle,
  51848. /**
  51849. * The cone base angle.
  51850. */
  51851. directionRandomizer) {
  51852. if (radius === void 0) { radius = 1; }
  51853. if (angle === void 0) { angle = Math.PI; }
  51854. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51855. this.angle = angle;
  51856. this.directionRandomizer = directionRandomizer;
  51857. this.radius = radius;
  51858. }
  51859. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51860. /**
  51861. * Gets the radius of the emission cone.
  51862. */
  51863. get: function () {
  51864. return this._radius;
  51865. },
  51866. /**
  51867. * Sets the radius of the emission cone.
  51868. */
  51869. set: function (value) {
  51870. this._radius = value;
  51871. if (this.angle !== 0) {
  51872. this._height = value / Math.tan(this.angle / 2);
  51873. }
  51874. else {
  51875. this._height = 1;
  51876. }
  51877. },
  51878. enumerable: true,
  51879. configurable: true
  51880. });
  51881. /**
  51882. * Called by the particle System when the direction is computed for the created particle.
  51883. * @param emitPower is the power of the particle (speed)
  51884. * @param worldMatrix is the world matrix of the particle system
  51885. * @param directionToUpdate is the direction vector to update with the result
  51886. * @param particle is the particle we are computed the direction for
  51887. */
  51888. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51889. if (this.angle === 0) {
  51890. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51891. }
  51892. else {
  51893. // measure the direction Vector from the emitter to the particle.
  51894. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51895. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51896. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51897. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51898. direction.x += randX;
  51899. direction.y += randY;
  51900. direction.z += randZ;
  51901. direction.normalize();
  51902. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51903. }
  51904. };
  51905. /**
  51906. * Called by the particle System when the position is computed for the created particle.
  51907. * @param worldMatrix is the world matrix of the particle system
  51908. * @param positionToUpdate is the position vector to update with the result
  51909. * @param particle is the particle we are computed the position for
  51910. */
  51911. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51912. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51913. var h = BABYLON.Scalar.RandomRange(0, 1);
  51914. // Better distribution in a cone at normal angles.
  51915. h = 1 - h * h;
  51916. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51917. radius = radius * h / this._height;
  51918. var randX = radius * Math.sin(s);
  51919. var randZ = radius * Math.cos(s);
  51920. var randY = h * this._height;
  51921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51922. };
  51923. /**
  51924. * Clones the current emitter and returns a copy of it
  51925. * @returns the new emitter
  51926. */
  51927. ConeParticleEmitter.prototype.clone = function () {
  51928. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51929. BABYLON.Tools.DeepCopy(this, newOne);
  51930. return newOne;
  51931. };
  51932. /**
  51933. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51934. * @param effect defines the update shader
  51935. */
  51936. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51937. effect.setFloat("radius", this.radius);
  51938. effect.setFloat("angle", this.angle);
  51939. effect.setFloat("height", this._height);
  51940. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51941. };
  51942. /**
  51943. * Returns a string to use to update the GPU particles update shader
  51944. * @returns a string containng the defines string
  51945. */
  51946. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51947. return "#define CONEEMITTER";
  51948. };
  51949. /**
  51950. * Returns the string "BoxEmitter"
  51951. * @returns a string containing the class name
  51952. */
  51953. ConeParticleEmitter.prototype.getClassName = function () {
  51954. return "ConeEmitter";
  51955. };
  51956. /**
  51957. * Serializes the particle system to a JSON object.
  51958. * @returns the JSON object
  51959. */
  51960. ConeParticleEmitter.prototype.serialize = function () {
  51961. var serializationObject = {};
  51962. serializationObject.type = this.getClassName();
  51963. serializationObject.radius = this.radius;
  51964. serializationObject.angle = this.angle;
  51965. serializationObject.directionRandomizer = this.directionRandomizer;
  51966. return serializationObject;
  51967. };
  51968. /**
  51969. * Parse properties from a JSON object
  51970. * @param serializationObject defines the JSON object
  51971. */
  51972. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51973. this.radius = serializationObject.radius;
  51974. this.angle = serializationObject.angle;
  51975. this.directionRandomizer = serializationObject.directionRandomizer;
  51976. };
  51977. return ConeParticleEmitter;
  51978. }());
  51979. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51980. })(BABYLON || (BABYLON = {}));
  51981. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51982. var BABYLON;
  51983. (function (BABYLON) {
  51984. /**
  51985. * Particle emitter emitting particles from the inside of a sphere.
  51986. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51987. */
  51988. var SphereParticleEmitter = /** @class */ (function () {
  51989. /**
  51990. * Creates a new instance of @see SphereParticleEmitter
  51991. * @param radius the radius of the emission sphere (1 by default)
  51992. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51993. */
  51994. function SphereParticleEmitter(
  51995. /**
  51996. * The radius of the emission sphere.
  51997. */
  51998. radius,
  51999. /**
  52000. * How much to randomize the particle direction [0-1].
  52001. */
  52002. directionRandomizer) {
  52003. if (radius === void 0) { radius = 1; }
  52004. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52005. this.radius = radius;
  52006. this.directionRandomizer = directionRandomizer;
  52007. }
  52008. /**
  52009. * Called by the particle System when the direction is computed for the created particle.
  52010. * @param emitPower is the power of the particle (speed)
  52011. * @param worldMatrix is the world matrix of the particle system
  52012. * @param directionToUpdate is the direction vector to update with the result
  52013. * @param particle is the particle we are computed the direction for
  52014. */
  52015. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52016. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52017. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52018. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52019. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52020. direction.x += randX;
  52021. direction.y += randY;
  52022. direction.z += randZ;
  52023. direction.normalize();
  52024. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52025. };
  52026. /**
  52027. * Called by the particle System when the position is computed for the created particle.
  52028. * @param worldMatrix is the world matrix of the particle system
  52029. * @param positionToUpdate is the position vector to update with the result
  52030. * @param particle is the particle we are computed the position for
  52031. */
  52032. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52033. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52034. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52035. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52036. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52037. var randY = randRadius * Math.cos(theta);
  52038. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52040. };
  52041. /**
  52042. * Clones the current emitter and returns a copy of it
  52043. * @returns the new emitter
  52044. */
  52045. SphereParticleEmitter.prototype.clone = function () {
  52046. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52047. BABYLON.Tools.DeepCopy(this, newOne);
  52048. return newOne;
  52049. };
  52050. /**
  52051. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52052. * @param effect defines the update shader
  52053. */
  52054. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52055. effect.setFloat("radius", this.radius);
  52056. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52057. };
  52058. /**
  52059. * Returns a string to use to update the GPU particles update shader
  52060. * @returns a string containng the defines string
  52061. */
  52062. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52063. return "#define SPHEREEMITTER";
  52064. };
  52065. /**
  52066. * Returns the string "SphereParticleEmitter"
  52067. * @returns a string containing the class name
  52068. */
  52069. SphereParticleEmitter.prototype.getClassName = function () {
  52070. return "SphereParticleEmitter";
  52071. };
  52072. /**
  52073. * Serializes the particle system to a JSON object.
  52074. * @returns the JSON object
  52075. */
  52076. SphereParticleEmitter.prototype.serialize = function () {
  52077. var serializationObject = {};
  52078. serializationObject.type = this.getClassName();
  52079. serializationObject.radius = this.radius;
  52080. serializationObject.directionRandomizer = this.directionRandomizer;
  52081. return serializationObject;
  52082. };
  52083. /**
  52084. * Parse properties from a JSON object
  52085. * @param serializationObject defines the JSON object
  52086. */
  52087. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52088. this.radius = serializationObject.radius;
  52089. this.directionRandomizer = serializationObject.directionRandomizer;
  52090. };
  52091. return SphereParticleEmitter;
  52092. }());
  52093. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52094. /**
  52095. * Particle emitter emitting particles from the inside of a sphere.
  52096. * It emits the particles randomly between two vectors.
  52097. */
  52098. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52099. __extends(SphereDirectedParticleEmitter, _super);
  52100. /**
  52101. * Creates a new instance of @see SphereDirectedParticleEmitter
  52102. * @param radius the radius of the emission sphere (1 by default)
  52103. * @param direction1 the min limit of the emission direction (up vector by default)
  52104. * @param direction2 the max limit of the emission direction (up vector by default)
  52105. */
  52106. function SphereDirectedParticleEmitter(radius,
  52107. /**
  52108. * The min limit of the emission direction.
  52109. */
  52110. direction1,
  52111. /**
  52112. * The max limit of the emission direction.
  52113. */
  52114. direction2) {
  52115. if (radius === void 0) { radius = 1; }
  52116. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52117. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52118. var _this = _super.call(this, radius) || this;
  52119. _this.direction1 = direction1;
  52120. _this.direction2 = direction2;
  52121. return _this;
  52122. }
  52123. /**
  52124. * Called by the particle System when the direction is computed for the created particle.
  52125. * @param emitPower is the power of the particle (speed)
  52126. * @param worldMatrix is the world matrix of the particle system
  52127. * @param directionToUpdate is the direction vector to update with the result
  52128. * @param particle is the particle we are computed the direction for
  52129. */
  52130. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52131. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52132. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52133. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52134. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52135. };
  52136. /**
  52137. * Clones the current emitter and returns a copy of it
  52138. * @returns the new emitter
  52139. */
  52140. SphereDirectedParticleEmitter.prototype.clone = function () {
  52141. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52142. BABYLON.Tools.DeepCopy(this, newOne);
  52143. return newOne;
  52144. };
  52145. /**
  52146. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52147. * @param effect defines the update shader
  52148. */
  52149. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52150. effect.setFloat("radius", this.radius);
  52151. effect.setVector3("direction1", this.direction1);
  52152. effect.setVector3("direction2", this.direction2);
  52153. };
  52154. /**
  52155. * Returns a string to use to update the GPU particles update shader
  52156. * @returns a string containng the defines string
  52157. */
  52158. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52159. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52160. };
  52161. /**
  52162. * Returns the string "SphereDirectedParticleEmitter"
  52163. * @returns a string containing the class name
  52164. */
  52165. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52166. return "SphereDirectedParticleEmitter";
  52167. };
  52168. /**
  52169. * Serializes the particle system to a JSON object.
  52170. * @returns the JSON object
  52171. */
  52172. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52173. var serializationObject = _super.prototype.serialize.call(this);
  52174. ;
  52175. serializationObject.direction1 = this.direction1.asArray();
  52176. ;
  52177. serializationObject.direction2 = this.direction2.asArray();
  52178. ;
  52179. return serializationObject;
  52180. };
  52181. /**
  52182. * Parse properties from a JSON object
  52183. * @param serializationObject defines the JSON object
  52184. */
  52185. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52186. _super.prototype.parse.call(this, serializationObject);
  52187. this.direction1.copyFrom(serializationObject.direction1);
  52188. this.direction2.copyFrom(serializationObject.direction2);
  52189. };
  52190. return SphereDirectedParticleEmitter;
  52191. }(SphereParticleEmitter));
  52192. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52193. })(BABYLON || (BABYLON = {}));
  52194. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52195. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52196. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52197. s = arguments[i];
  52198. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52199. t[p] = s[p];
  52200. }
  52201. return t;
  52202. };
  52203. var BABYLON;
  52204. (function (BABYLON) {
  52205. /**
  52206. * This represents a GPU particle system in Babylon
  52207. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52208. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52209. */
  52210. var GPUParticleSystem = /** @class */ (function () {
  52211. /**
  52212. * Instantiates a GPU particle system.
  52213. * 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.
  52214. * @param name The name of the particle system
  52215. * @param capacity The max number of particles alive at the same time
  52216. * @param scene The scene the particle system belongs to
  52217. */
  52218. function GPUParticleSystem(name, options, scene) {
  52219. /**
  52220. * The emitter represents the Mesh or position we are attaching the particle system to.
  52221. */
  52222. this.emitter = null;
  52223. /**
  52224. * The rendering group used by the Particle system to chose when to render.
  52225. */
  52226. this.renderingGroupId = 0;
  52227. /**
  52228. * The layer mask we are rendering the particles through.
  52229. */
  52230. this.layerMask = 0x0FFFFFFF;
  52231. this._targetIndex = 0;
  52232. this._currentRenderId = -1;
  52233. this._started = false;
  52234. this._stopped = false;
  52235. this._timeDelta = 0;
  52236. this._attributesStrideSize = 14;
  52237. this._actualFrame = 0;
  52238. /**
  52239. * List of animations used by the particle system.
  52240. */
  52241. this.animations = [];
  52242. /**
  52243. * An event triggered when the system is disposed.
  52244. */
  52245. this.onDisposeObservable = new BABYLON.Observable();
  52246. /**
  52247. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52248. */
  52249. this.updateSpeed = 0.01;
  52250. /**
  52251. * The amount of time the particle system is running (depends of the overall update speed).
  52252. */
  52253. this.targetStopDuration = 0;
  52254. /**
  52255. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52256. */
  52257. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52258. /**
  52259. * Minimum life time of emitting particles.
  52260. */
  52261. this.minLifeTime = 1;
  52262. /**
  52263. * Maximum life time of emitting particles.
  52264. */
  52265. this.maxLifeTime = 1;
  52266. /**
  52267. * Minimum Size of emitting particles.
  52268. */
  52269. this.minSize = 1;
  52270. /**
  52271. * Maximum Size of emitting particles.
  52272. */
  52273. this.maxSize = 1;
  52274. /**
  52275. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52276. */
  52277. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52278. /**
  52279. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52280. */
  52281. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52282. /**
  52283. * Color the particle will have at the end of its lifetime.
  52284. */
  52285. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52286. /**
  52287. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52288. */
  52289. this.emitRate = 100;
  52290. /**
  52291. * You can use gravity if you want to give an orientation to your particles.
  52292. */
  52293. this.gravity = BABYLON.Vector3.Zero();
  52294. /**
  52295. * Minimum power of emitting particles.
  52296. */
  52297. this.minEmitPower = 1;
  52298. /**
  52299. * Maximum power of emitting particles.
  52300. */
  52301. this.maxEmitPower = 1;
  52302. /**
  52303. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52304. * to override the particles.
  52305. */
  52306. this.forceDepthWrite = false;
  52307. this.id = name;
  52308. this.name = name;
  52309. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52310. this._engine = this._scene.getEngine();
  52311. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52312. this._capacity = fullOptions.capacity;
  52313. this._activeCount = fullOptions.capacity;
  52314. this._currentActiveCount = 0;
  52315. this._scene.particleSystems.push(this);
  52316. this._updateEffectOptions = {
  52317. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52318. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52319. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  52320. uniformBuffersNames: [],
  52321. samplers: ["randomSampler"],
  52322. defines: "",
  52323. fallbacks: null,
  52324. onCompiled: null,
  52325. onError: null,
  52326. indexParameters: null,
  52327. maxSimultaneousLights: 0,
  52328. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52329. };
  52330. // Random data
  52331. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52332. var d = [];
  52333. for (var i = 0; i < maxTextureSize; ++i) {
  52334. d.push(Math.random());
  52335. d.push(Math.random());
  52336. d.push(Math.random());
  52337. d.push(Math.random());
  52338. }
  52339. 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);
  52340. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52341. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52342. this._randomTextureSize = maxTextureSize;
  52343. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52344. }
  52345. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52346. /**
  52347. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52348. */
  52349. get: function () {
  52350. if (!BABYLON.Engine.LastCreatedEngine) {
  52351. return false;
  52352. }
  52353. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52354. },
  52355. enumerable: true,
  52356. configurable: true
  52357. });
  52358. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52359. /**
  52360. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52361. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52362. */
  52363. get: function () {
  52364. if (this.particleEmitterType.direction1) {
  52365. return this.particleEmitterType.direction1;
  52366. }
  52367. return BABYLON.Vector3.Zero();
  52368. },
  52369. set: function (value) {
  52370. if (this.particleEmitterType.direction1) {
  52371. this.particleEmitterType.direction1 = value;
  52372. }
  52373. },
  52374. enumerable: true,
  52375. configurable: true
  52376. });
  52377. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52378. /**
  52379. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52380. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52381. */
  52382. get: function () {
  52383. if (this.particleEmitterType.direction2) {
  52384. return this.particleEmitterType.direction2;
  52385. }
  52386. return BABYLON.Vector3.Zero();
  52387. },
  52388. set: function (value) {
  52389. if (this.particleEmitterType.direction2) {
  52390. this.particleEmitterType.direction2 = value;
  52391. }
  52392. },
  52393. enumerable: true,
  52394. configurable: true
  52395. });
  52396. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52397. /**
  52398. * 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.
  52399. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52400. */
  52401. get: function () {
  52402. if (this.particleEmitterType.minEmitBox) {
  52403. return this.particleEmitterType.minEmitBox;
  52404. }
  52405. return BABYLON.Vector3.Zero();
  52406. },
  52407. set: function (value) {
  52408. if (this.particleEmitterType.minEmitBox) {
  52409. this.particleEmitterType.minEmitBox = value;
  52410. }
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52416. /**
  52417. * 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.
  52418. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52419. */
  52420. get: function () {
  52421. if (this.particleEmitterType.maxEmitBox) {
  52422. return this.particleEmitterType.maxEmitBox;
  52423. }
  52424. return BABYLON.Vector3.Zero();
  52425. },
  52426. set: function (value) {
  52427. if (this.particleEmitterType.maxEmitBox) {
  52428. this.particleEmitterType.maxEmitBox = value;
  52429. }
  52430. },
  52431. enumerable: true,
  52432. configurable: true
  52433. });
  52434. /**
  52435. * Gets the maximum number of particles active at the same time.
  52436. * @returns The max number of active particles.
  52437. */
  52438. GPUParticleSystem.prototype.getCapacity = function () {
  52439. return this._capacity;
  52440. };
  52441. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52442. /**
  52443. * Gets or set the number of active particles
  52444. */
  52445. get: function () {
  52446. return this._activeCount;
  52447. },
  52448. set: function (value) {
  52449. this._activeCount = Math.min(value, this._capacity);
  52450. },
  52451. enumerable: true,
  52452. configurable: true
  52453. });
  52454. /**
  52455. * Gets Wether the system has been started.
  52456. * @returns True if it has been started, otherwise false.
  52457. */
  52458. GPUParticleSystem.prototype.isStarted = function () {
  52459. return this._started;
  52460. };
  52461. /**
  52462. * Starts the particle system and begins to emit.
  52463. */
  52464. GPUParticleSystem.prototype.start = function () {
  52465. this._started = true;
  52466. this._stopped = false;
  52467. };
  52468. /**
  52469. * Stops the particle system.
  52470. */
  52471. GPUParticleSystem.prototype.stop = function () {
  52472. this._stopped = true;
  52473. };
  52474. /**
  52475. * Remove all active particles
  52476. */
  52477. GPUParticleSystem.prototype.reset = function () {
  52478. this._releaseBuffers();
  52479. this._releaseVAOs();
  52480. this._currentActiveCount = 0;
  52481. this._targetIndex = 0;
  52482. };
  52483. /**
  52484. * Returns the string "GPUParticleSystem"
  52485. * @returns a string containing the class name
  52486. */
  52487. GPUParticleSystem.prototype.getClassName = function () {
  52488. return "GPUParticleSystem";
  52489. };
  52490. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52491. var updateVertexBuffers = {};
  52492. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52493. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52494. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52495. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52496. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52497. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52498. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52499. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52500. this._engine.bindArrayBuffer(null);
  52501. return vao;
  52502. };
  52503. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52504. var renderVertexBuffers = {};
  52505. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52506. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52507. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52508. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52509. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52510. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52511. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52512. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52513. this._engine.bindArrayBuffer(null);
  52514. return vao;
  52515. };
  52516. GPUParticleSystem.prototype._initialize = function (force) {
  52517. if (force === void 0) { force = false; }
  52518. if (this._buffer0 && !force) {
  52519. return;
  52520. }
  52521. var engine = this._scene.getEngine();
  52522. var data = new Array();
  52523. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52524. // position
  52525. data.push(0.0);
  52526. data.push(0.0);
  52527. data.push(0.0);
  52528. // Age and life
  52529. data.push(0.0); // create the particle as a dead one to create a new one at start
  52530. data.push(0.0);
  52531. // Seed
  52532. data.push(Math.random());
  52533. // Size
  52534. data.push(0.0);
  52535. // color
  52536. data.push(0.0);
  52537. data.push(0.0);
  52538. data.push(0.0);
  52539. data.push(0.0);
  52540. // direction
  52541. data.push(0.0);
  52542. data.push(0.0);
  52543. data.push(0.0);
  52544. }
  52545. // Sprite data
  52546. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52547. -0.5, 0.5, 0, 1,
  52548. -0.5, -0.5, 0, 0,
  52549. 0.5, -0.5, 1, 0]);
  52550. // Buffers
  52551. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52552. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52553. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52554. // Update VAO
  52555. this._updateVAO = [];
  52556. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52557. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52558. // Render VAO
  52559. this._renderVAO = [];
  52560. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52561. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52562. // Links
  52563. this._sourceBuffer = this._buffer0;
  52564. this._targetBuffer = this._buffer1;
  52565. };
  52566. /** @ignore */
  52567. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52568. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52569. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52570. return;
  52571. }
  52572. this._updateEffectOptions.defines = defines;
  52573. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52574. };
  52575. /** @ignore */
  52576. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52577. var defines = "";
  52578. if (this._scene.clipPlane) {
  52579. defines = "\n#define CLIPPLANE";
  52580. }
  52581. if (this._renderEffect && this._renderEffect.defines === defines) {
  52582. return;
  52583. }
  52584. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52585. };
  52586. /**
  52587. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52588. */
  52589. GPUParticleSystem.prototype.animate = function () {
  52590. if (!this._stopped) {
  52591. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52592. this._actualFrame += this._timeDelta;
  52593. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52594. this.stop();
  52595. }
  52596. else {
  52597. this._timeDelta = 0;
  52598. }
  52599. };
  52600. /**
  52601. * Renders the particle system in its current state.
  52602. * @returns the current number of particles
  52603. */
  52604. GPUParticleSystem.prototype.render = function () {
  52605. if (!this._started) {
  52606. return 0;
  52607. }
  52608. this._recreateUpdateEffect();
  52609. this._recreateRenderEffect();
  52610. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52611. return 0;
  52612. }
  52613. if (this._currentRenderId === this._scene.getRenderId()) {
  52614. return 0;
  52615. }
  52616. this._currentRenderId = this._scene.getRenderId();
  52617. // Get everything ready to render
  52618. this._initialize();
  52619. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52620. // Enable update effect
  52621. this._engine.enableEffect(this._updateEffect);
  52622. this._engine.setState(false);
  52623. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52624. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52625. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52626. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52627. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52628. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52629. this._updateEffect.setDirectColor4("color1", this.color1);
  52630. this._updateEffect.setDirectColor4("color2", this.color2);
  52631. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52632. this._updateEffect.setVector3("gravity", this.gravity);
  52633. if (this.particleEmitterType) {
  52634. this.particleEmitterType.applyToShader(this._updateEffect);
  52635. }
  52636. var emitterWM;
  52637. if (this.emitter.position) {
  52638. var emitterMesh = this.emitter;
  52639. emitterWM = emitterMesh.getWorldMatrix();
  52640. }
  52641. else {
  52642. var emitterPosition = this.emitter;
  52643. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52644. }
  52645. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52646. // Bind source VAO
  52647. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52648. // Update
  52649. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52650. this._engine.setRasterizerState(false);
  52651. this._engine.beginTransformFeedback();
  52652. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52653. this._engine.endTransformFeedback();
  52654. this._engine.setRasterizerState(true);
  52655. this._engine.bindTransformFeedbackBuffer(null);
  52656. // Enable render effect
  52657. this._engine.enableEffect(this._renderEffect);
  52658. var viewMatrix = this._scene.getViewMatrix();
  52659. this._renderEffect.setMatrix("view", viewMatrix);
  52660. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52661. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52662. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52663. if (this._scene.clipPlane) {
  52664. var clipPlane = this._scene.clipPlane;
  52665. var invView = viewMatrix.clone();
  52666. invView.invert();
  52667. this._renderEffect.setMatrix("invView", invView);
  52668. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52669. }
  52670. // Draw order
  52671. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52672. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52673. }
  52674. else {
  52675. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52676. }
  52677. if (this.forceDepthWrite) {
  52678. this._engine.setDepthWrite(true);
  52679. }
  52680. // Bind source VAO
  52681. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52682. // Render
  52683. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52684. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52685. // Switch VAOs
  52686. this._targetIndex++;
  52687. if (this._targetIndex === 2) {
  52688. this._targetIndex = 0;
  52689. }
  52690. // Switch buffers
  52691. var tmpBuffer = this._sourceBuffer;
  52692. this._sourceBuffer = this._targetBuffer;
  52693. this._targetBuffer = tmpBuffer;
  52694. return this._currentActiveCount;
  52695. };
  52696. /**
  52697. * Rebuilds the particle system
  52698. */
  52699. GPUParticleSystem.prototype.rebuild = function () {
  52700. this._initialize(true);
  52701. };
  52702. GPUParticleSystem.prototype._releaseBuffers = function () {
  52703. if (this._buffer0) {
  52704. this._buffer0.dispose();
  52705. this._buffer0 = null;
  52706. }
  52707. if (this._buffer1) {
  52708. this._buffer1.dispose();
  52709. this._buffer1 = null;
  52710. }
  52711. if (this._spriteBuffer) {
  52712. this._spriteBuffer.dispose();
  52713. this._spriteBuffer = null;
  52714. }
  52715. };
  52716. GPUParticleSystem.prototype._releaseVAOs = function () {
  52717. if (!this._updateVAO) {
  52718. return;
  52719. }
  52720. for (var index = 0; index < this._updateVAO.length; index++) {
  52721. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52722. }
  52723. this._updateVAO = [];
  52724. for (var index = 0; index < this._renderVAO.length; index++) {
  52725. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52726. }
  52727. this._renderVAO = [];
  52728. };
  52729. /**
  52730. * Disposes the particle system and free the associated resources
  52731. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52732. */
  52733. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52734. if (disposeTexture === void 0) { disposeTexture = true; }
  52735. var index = this._scene.particleSystems.indexOf(this);
  52736. if (index > -1) {
  52737. this._scene.particleSystems.splice(index, 1);
  52738. }
  52739. this._releaseBuffers();
  52740. this._releaseVAOs();
  52741. if (this._randomTexture) {
  52742. this._randomTexture.dispose();
  52743. this._randomTexture = null;
  52744. }
  52745. if (disposeTexture && this.particleTexture) {
  52746. this.particleTexture.dispose();
  52747. this.particleTexture = null;
  52748. }
  52749. // Callback
  52750. this.onDisposeObservable.notifyObservers(this);
  52751. this.onDisposeObservable.clear();
  52752. };
  52753. /**
  52754. * Clones the particle system.
  52755. * @param name The name of the cloned object
  52756. * @param newEmitter The new emitter to use
  52757. * @returns the cloned particle system
  52758. */
  52759. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52760. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52761. BABYLON.Tools.DeepCopy(this, result);
  52762. if (newEmitter === undefined) {
  52763. newEmitter = this.emitter;
  52764. }
  52765. result.emitter = newEmitter;
  52766. if (this.particleTexture) {
  52767. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52768. }
  52769. return result;
  52770. };
  52771. /**
  52772. * Serializes the particle system to a JSON object.
  52773. * @returns the JSON object
  52774. */
  52775. GPUParticleSystem.prototype.serialize = function () {
  52776. var serializationObject = {};
  52777. serializationObject.name = this.name;
  52778. serializationObject.id = this.id;
  52779. // Emitter
  52780. if (this.emitter.position) {
  52781. var emitterMesh = this.emitter;
  52782. serializationObject.emitterId = emitterMesh.id;
  52783. }
  52784. else {
  52785. var emitterPosition = this.emitter;
  52786. serializationObject.emitter = emitterPosition.asArray();
  52787. }
  52788. serializationObject.capacity = this.getCapacity();
  52789. if (this.particleTexture) {
  52790. serializationObject.textureName = this.particleTexture.name;
  52791. }
  52792. // Animations
  52793. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52794. // Particle system
  52795. serializationObject.activeParticleCount = this.activeParticleCount;
  52796. serializationObject.randomTextureSize = this._randomTextureSize;
  52797. serializationObject.minSize = this.minSize;
  52798. serializationObject.maxSize = this.maxSize;
  52799. serializationObject.minEmitPower = this.minEmitPower;
  52800. serializationObject.maxEmitPower = this.maxEmitPower;
  52801. serializationObject.minLifeTime = this.minLifeTime;
  52802. serializationObject.maxLifeTime = this.maxLifeTime;
  52803. serializationObject.emitRate = this.emitRate;
  52804. serializationObject.gravity = this.gravity.asArray();
  52805. serializationObject.color1 = this.color1.asArray();
  52806. serializationObject.color2 = this.color2.asArray();
  52807. serializationObject.colorDead = this.colorDead.asArray();
  52808. serializationObject.updateSpeed = this.updateSpeed;
  52809. serializationObject.targetStopDuration = this.targetStopDuration;
  52810. serializationObject.blendMode = this.blendMode;
  52811. // Emitter
  52812. if (this.particleEmitterType) {
  52813. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52814. }
  52815. return serializationObject;
  52816. };
  52817. /**
  52818. * Parses a JSON object to create a GPU particle system.
  52819. * @param parsedParticleSystem The JSON object to parse
  52820. * @param scene The scene to create the particle system in
  52821. * @param rootUrl The root url to use to load external dependencies like texture
  52822. * @returns the parsed GPU particle system
  52823. */
  52824. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52825. var name = parsedParticleSystem.name;
  52826. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52827. if (parsedParticleSystem.id) {
  52828. particleSystem.id = parsedParticleSystem.id;
  52829. }
  52830. // Texture
  52831. if (parsedParticleSystem.textureName) {
  52832. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52833. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52834. }
  52835. // Emitter
  52836. if (parsedParticleSystem.emitterId) {
  52837. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52838. }
  52839. else {
  52840. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52841. }
  52842. // Animations
  52843. if (parsedParticleSystem.animations) {
  52844. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52845. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52846. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52847. }
  52848. }
  52849. // Particle system
  52850. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52851. particleSystem.minSize = parsedParticleSystem.minSize;
  52852. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52853. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52854. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52855. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52856. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52857. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52858. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52859. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52860. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52861. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52862. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52863. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52864. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52865. // Emitter
  52866. if (parsedParticleSystem.particleEmitterType) {
  52867. var emitterType = void 0;
  52868. switch (parsedParticleSystem.particleEmitterType.type) {
  52869. case "SphereEmitter":
  52870. emitterType = new BABYLON.SphereParticleEmitter();
  52871. break;
  52872. case "SphereDirectedParticleEmitter":
  52873. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52874. break;
  52875. case "ConeEmitter":
  52876. emitterType = new BABYLON.ConeParticleEmitter();
  52877. break;
  52878. case "BoxEmitter":
  52879. default:
  52880. emitterType = new BABYLON.BoxParticleEmitter();
  52881. break;
  52882. }
  52883. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52884. particleSystem.particleEmitterType = emitterType;
  52885. }
  52886. return particleSystem;
  52887. };
  52888. return GPUParticleSystem;
  52889. }());
  52890. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52891. })(BABYLON || (BABYLON = {}));
  52892. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52893. var BABYLON;
  52894. (function (BABYLON) {
  52895. /**
  52896. * Represents one particle of a solid particle system.
  52897. * @see SolidParticleSystem
  52898. */
  52899. var SolidParticle = /** @class */ (function () {
  52900. /**
  52901. * Creates a Solid Particle object.
  52902. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52903. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52904. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52905. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52906. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52907. * @param shapeId (integer) is the model shape identifier in the SPS.
  52908. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52909. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52910. */
  52911. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52912. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52913. /**
  52914. * particle global index
  52915. */
  52916. this.idx = 0;
  52917. /**
  52918. * The color of the particle
  52919. */
  52920. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52921. /**
  52922. * The world space position of the particle.
  52923. */
  52924. this.position = BABYLON.Vector3.Zero();
  52925. /**
  52926. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52927. */
  52928. this.rotation = BABYLON.Vector3.Zero();
  52929. /**
  52930. * The scaling of the particle.
  52931. */
  52932. this.scaling = BABYLON.Vector3.One();
  52933. /**
  52934. * The uvs of the particle.
  52935. */
  52936. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52937. /**
  52938. * The current speed of the particle.
  52939. */
  52940. this.velocity = BABYLON.Vector3.Zero();
  52941. /**
  52942. * The pivot point in the particle local space.
  52943. */
  52944. this.pivot = BABYLON.Vector3.Zero();
  52945. /**
  52946. * Must the particle be translated from its pivot point in its local space ?
  52947. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52948. * Default : false
  52949. */
  52950. this.translateFromPivot = false;
  52951. /**
  52952. * Is the particle active or not ?
  52953. */
  52954. this.alive = true;
  52955. /**
  52956. * Is the particle visible or not ?
  52957. */
  52958. this.isVisible = true;
  52959. /**
  52960. * Index of this particle in the global "positions" array (Internal use)
  52961. */
  52962. this._pos = 0;
  52963. /**
  52964. * Index of this particle in the global "indices" array (Internal use)
  52965. */
  52966. this._ind = 0;
  52967. /**
  52968. * ModelShape id of this particle
  52969. */
  52970. this.shapeId = 0;
  52971. /**
  52972. * Index of the particle in its shape id (Internal use)
  52973. */
  52974. this.idxInShape = 0;
  52975. /**
  52976. * Still set as invisible in order to skip useless computations (Internal use)
  52977. */
  52978. this._stillInvisible = false;
  52979. /**
  52980. * Last computed particle rotation matrix
  52981. */
  52982. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52983. /**
  52984. * Parent particle Id, if any.
  52985. * Default null.
  52986. */
  52987. this.parentId = null;
  52988. /**
  52989. * Internal global position in the SPS.
  52990. */
  52991. this._globalPosition = BABYLON.Vector3.Zero();
  52992. this.idx = particleIndex;
  52993. this._pos = positionIndex;
  52994. this._ind = indiceIndex;
  52995. this._model = model;
  52996. this.shapeId = shapeId;
  52997. this.idxInShape = idxInShape;
  52998. this._sps = sps;
  52999. if (modelBoundingInfo) {
  53000. this._modelBoundingInfo = modelBoundingInfo;
  53001. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53002. }
  53003. }
  53004. Object.defineProperty(SolidParticle.prototype, "scale", {
  53005. /**
  53006. * Legacy support, changed scale to scaling
  53007. */
  53008. get: function () {
  53009. return this.scaling;
  53010. },
  53011. /**
  53012. * Legacy support, changed scale to scaling
  53013. */
  53014. set: function (scale) {
  53015. this.scaling = scale;
  53016. },
  53017. enumerable: true,
  53018. configurable: true
  53019. });
  53020. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53021. /**
  53022. * Legacy support, changed quaternion to rotationQuaternion
  53023. */
  53024. get: function () {
  53025. return this.rotationQuaternion;
  53026. },
  53027. /**
  53028. * Legacy support, changed quaternion to rotationQuaternion
  53029. */
  53030. set: function (q) {
  53031. this.rotationQuaternion = q;
  53032. },
  53033. enumerable: true,
  53034. configurable: true
  53035. });
  53036. /**
  53037. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53038. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53039. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53040. * @returns true if it intersects
  53041. */
  53042. SolidParticle.prototype.intersectsMesh = function (target) {
  53043. if (!this._boundingInfo || !target._boundingInfo) {
  53044. return false;
  53045. }
  53046. if (this._sps._bSphereOnly) {
  53047. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53048. }
  53049. return this._boundingInfo.intersects(target._boundingInfo, false);
  53050. };
  53051. return SolidParticle;
  53052. }());
  53053. BABYLON.SolidParticle = SolidParticle;
  53054. /**
  53055. * Represents the shape of the model used by one particle of a solid particle system.
  53056. * SPS internal tool, don't use it manually.
  53057. * @see SolidParticleSystem
  53058. */
  53059. var ModelShape = /** @class */ (function () {
  53060. /**
  53061. * 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.
  53062. * SPS internal tool, don't use it manually.
  53063. * @ignore
  53064. */
  53065. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53066. /**
  53067. * length of the shape in the model indices array (internal use)
  53068. */
  53069. this._indicesLength = 0;
  53070. this.shapeID = id;
  53071. this._shape = shape;
  53072. this._indicesLength = indicesLength;
  53073. this._shapeUV = shapeUV;
  53074. this._positionFunction = posFunction;
  53075. this._vertexFunction = vtxFunction;
  53076. }
  53077. return ModelShape;
  53078. }());
  53079. BABYLON.ModelShape = ModelShape;
  53080. /**
  53081. * Represents a Depth Sorted Particle in the solid particle system.
  53082. * @see SolidParticleSystem
  53083. */
  53084. var DepthSortedParticle = /** @class */ (function () {
  53085. function DepthSortedParticle() {
  53086. /**
  53087. * Index of the particle in the "indices" array
  53088. */
  53089. this.ind = 0;
  53090. /**
  53091. * Length of the particle shape in the "indices" array
  53092. */
  53093. this.indicesLength = 0;
  53094. /**
  53095. * Squared distance from the particle to the camera
  53096. */
  53097. this.sqDistance = 0.0;
  53098. }
  53099. return DepthSortedParticle;
  53100. }());
  53101. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53102. })(BABYLON || (BABYLON = {}));
  53103. //# sourceMappingURL=babylon.solidParticle.js.map
  53104. var BABYLON;
  53105. (function (BABYLON) {
  53106. /**
  53107. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53108. *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.
  53109. * The SPS is also a particle system. It provides some methods to manage the particles.
  53110. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53111. *
  53112. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53113. */
  53114. var SolidParticleSystem = /** @class */ (function () {
  53115. /**
  53116. * Creates a SPS (Solid Particle System) object.
  53117. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53118. * @param scene (Scene) is the scene in which the SPS is added.
  53119. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53120. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53121. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53122. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53123. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53124. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53125. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53126. */
  53127. function SolidParticleSystem(name, scene, options) {
  53128. /**
  53129. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53130. * Example : var p = SPS.particles[i];
  53131. */
  53132. this.particles = new Array();
  53133. /**
  53134. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53135. */
  53136. this.nbParticles = 0;
  53137. /**
  53138. * If the particles must ever face the camera (default false). Useful for planar particles.
  53139. */
  53140. this.billboard = false;
  53141. /**
  53142. * Recompute normals when adding a shape
  53143. */
  53144. this.recomputeNormals = true;
  53145. /**
  53146. * This a counter ofr your own usage. It's not set by any SPS functions.
  53147. */
  53148. this.counter = 0;
  53149. /**
  53150. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53151. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53152. */
  53153. this.vars = {};
  53154. /**
  53155. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53156. */
  53157. this._bSphereOnly = false;
  53158. /**
  53159. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53160. */
  53161. this._bSphereRadiusFactor = 1.0;
  53162. this._positions = new Array();
  53163. this._indices = new Array();
  53164. this._normals = new Array();
  53165. this._colors = new Array();
  53166. this._uvs = new Array();
  53167. this._index = 0; // indices index
  53168. this._updatable = true;
  53169. this._pickable = false;
  53170. this._isVisibilityBoxLocked = false;
  53171. this._alwaysVisible = false;
  53172. this._depthSort = false;
  53173. this._shapeCounter = 0;
  53174. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53175. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53176. this._computeParticleColor = true;
  53177. this._computeParticleTexture = true;
  53178. this._computeParticleRotation = true;
  53179. this._computeParticleVertex = false;
  53180. this._computeBoundingBox = false;
  53181. this._depthSortParticles = true;
  53182. this._cam_axisZ = BABYLON.Vector3.Zero();
  53183. this._cam_axisY = BABYLON.Vector3.Zero();
  53184. this._cam_axisX = BABYLON.Vector3.Zero();
  53185. this._axisZ = BABYLON.Axis.Z;
  53186. this._camDir = BABYLON.Vector3.Zero();
  53187. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53188. this._rotMatrix = new BABYLON.Matrix();
  53189. this._invertMatrix = new BABYLON.Matrix();
  53190. this._rotated = BABYLON.Vector3.Zero();
  53191. this._quaternion = new BABYLON.Quaternion();
  53192. this._vertex = BABYLON.Vector3.Zero();
  53193. this._normal = BABYLON.Vector3.Zero();
  53194. this._yaw = 0.0;
  53195. this._pitch = 0.0;
  53196. this._roll = 0.0;
  53197. this._halfroll = 0.0;
  53198. this._halfpitch = 0.0;
  53199. this._halfyaw = 0.0;
  53200. this._sinRoll = 0.0;
  53201. this._cosRoll = 0.0;
  53202. this._sinPitch = 0.0;
  53203. this._cosPitch = 0.0;
  53204. this._sinYaw = 0.0;
  53205. this._cosYaw = 0.0;
  53206. this._mustUnrotateFixedNormals = false;
  53207. this._minimum = BABYLON.Vector3.Zero();
  53208. this._maximum = BABYLON.Vector3.Zero();
  53209. this._minBbox = BABYLON.Vector3.Zero();
  53210. this._maxBbox = BABYLON.Vector3.Zero();
  53211. this._particlesIntersect = false;
  53212. this._depthSortFunction = function (p1, p2) {
  53213. return (p2.sqDistance - p1.sqDistance);
  53214. };
  53215. this._needs32Bits = false;
  53216. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53217. this._scaledPivot = BABYLON.Vector3.Zero();
  53218. this._particleHasParent = false;
  53219. this.name = name;
  53220. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53221. this._camera = scene.activeCamera;
  53222. this._pickable = options ? options.isPickable : false;
  53223. this._depthSort = options ? options.enableDepthSort : false;
  53224. this._particlesIntersect = options ? options.particleIntersection : false;
  53225. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53226. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53227. if (options && options.updatable) {
  53228. this._updatable = options.updatable;
  53229. }
  53230. else {
  53231. this._updatable = true;
  53232. }
  53233. if (this._pickable) {
  53234. this.pickedParticles = [];
  53235. }
  53236. if (this._depthSort) {
  53237. this.depthSortedParticles = [];
  53238. }
  53239. }
  53240. /**
  53241. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53242. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53243. * @returns the created mesh
  53244. */
  53245. SolidParticleSystem.prototype.buildMesh = function () {
  53246. if (this.nbParticles === 0) {
  53247. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53248. this.addShape(triangle, 1);
  53249. triangle.dispose();
  53250. }
  53251. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53252. this._positions32 = new Float32Array(this._positions);
  53253. this._uvs32 = new Float32Array(this._uvs);
  53254. this._colors32 = new Float32Array(this._colors);
  53255. if (this.recomputeNormals) {
  53256. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53257. }
  53258. this._normals32 = new Float32Array(this._normals);
  53259. this._fixedNormal32 = new Float32Array(this._normals);
  53260. if (this._mustUnrotateFixedNormals) {
  53261. this._unrotateFixedNormals();
  53262. }
  53263. var vertexData = new BABYLON.VertexData();
  53264. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53265. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53266. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53267. if (this._uvs32) {
  53268. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53269. ;
  53270. }
  53271. if (this._colors32) {
  53272. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53273. }
  53274. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53275. vertexData.applyToMesh(mesh, this._updatable);
  53276. this.mesh = mesh;
  53277. this.mesh.isPickable = this._pickable;
  53278. // free memory
  53279. if (!this._depthSort) {
  53280. this._indices = null;
  53281. }
  53282. this._positions = null;
  53283. this._normals = null;
  53284. this._uvs = null;
  53285. this._colors = null;
  53286. if (!this._updatable) {
  53287. this.particles.length = 0;
  53288. }
  53289. return mesh;
  53290. };
  53291. /**
  53292. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53293. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53294. * Thus the particles generated from `digest()` have their property `position` set yet.
  53295. * @param mesh ( Mesh ) is the mesh to be digested
  53296. * @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
  53297. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53298. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53299. * @returns the current SPS
  53300. */
  53301. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53302. var size = (options && options.facetNb) || 1;
  53303. var number = (options && options.number) || 0;
  53304. var delta = (options && options.delta) || 0;
  53305. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53306. var meshInd = mesh.getIndices();
  53307. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53308. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53309. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53310. var f = 0; // facet counter
  53311. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53312. // compute size from number
  53313. if (number) {
  53314. number = (number > totalFacets) ? totalFacets : number;
  53315. size = Math.round(totalFacets / number);
  53316. delta = 0;
  53317. }
  53318. else {
  53319. size = (size > totalFacets) ? totalFacets : size;
  53320. }
  53321. var facetPos = []; // submesh positions
  53322. var facetInd = []; // submesh indices
  53323. var facetUV = []; // submesh UV
  53324. var facetCol = []; // submesh colors
  53325. var barycenter = BABYLON.Vector3.Zero();
  53326. var sizeO = size;
  53327. while (f < totalFacets) {
  53328. size = sizeO + Math.floor((1 + delta) * Math.random());
  53329. if (f > totalFacets - size) {
  53330. size = totalFacets - f;
  53331. }
  53332. // reset temp arrays
  53333. facetPos.length = 0;
  53334. facetInd.length = 0;
  53335. facetUV.length = 0;
  53336. facetCol.length = 0;
  53337. // iterate over "size" facets
  53338. var fi = 0;
  53339. for (var j = f * 3; j < (f + size) * 3; j++) {
  53340. facetInd.push(fi);
  53341. var i = meshInd[j];
  53342. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53343. if (meshUV) {
  53344. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53345. }
  53346. if (meshCol) {
  53347. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53348. }
  53349. fi++;
  53350. }
  53351. // create a model shape for each single particle
  53352. var idx = this.nbParticles;
  53353. var shape = this._posToShape(facetPos);
  53354. var shapeUV = this._uvsToShapeUV(facetUV);
  53355. // compute the barycenter of the shape
  53356. var v;
  53357. for (v = 0; v < shape.length; v++) {
  53358. barycenter.addInPlace(shape[v]);
  53359. }
  53360. barycenter.scaleInPlace(1 / shape.length);
  53361. // shift the shape from its barycenter to the origin
  53362. for (v = 0; v < shape.length; v++) {
  53363. shape[v].subtractInPlace(barycenter);
  53364. }
  53365. var bInfo;
  53366. if (this._particlesIntersect) {
  53367. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53368. }
  53369. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53370. // add the particle in the SPS
  53371. var currentPos = this._positions.length;
  53372. var currentInd = this._indices.length;
  53373. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53374. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53375. // initialize the particle position
  53376. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53377. this._index += shape.length;
  53378. idx++;
  53379. this.nbParticles++;
  53380. this._shapeCounter++;
  53381. f += size;
  53382. }
  53383. return this;
  53384. };
  53385. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53386. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53387. var index = 0;
  53388. var idx = 0;
  53389. for (var p = 0; p < this.particles.length; p++) {
  53390. this._particle = this.particles[p];
  53391. this._shape = this._particle._model._shape;
  53392. if (this._particle.rotationQuaternion) {
  53393. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53394. }
  53395. else {
  53396. this._yaw = this._particle.rotation.y;
  53397. this._pitch = this._particle.rotation.x;
  53398. this._roll = this._particle.rotation.z;
  53399. this._quaternionRotationYPR();
  53400. }
  53401. this._quaternionToRotationMatrix();
  53402. this._rotMatrix.invertToRef(this._invertMatrix);
  53403. for (var pt = 0; pt < this._shape.length; pt++) {
  53404. idx = index + pt * 3;
  53405. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53406. this._fixedNormal32[idx] = this._normal.x;
  53407. this._fixedNormal32[idx + 1] = this._normal.y;
  53408. this._fixedNormal32[idx + 2] = this._normal.z;
  53409. }
  53410. index = idx + 3;
  53411. }
  53412. };
  53413. //reset copy
  53414. SolidParticleSystem.prototype._resetCopy = function () {
  53415. this._copy.position.x = 0;
  53416. this._copy.position.y = 0;
  53417. this._copy.position.z = 0;
  53418. this._copy.rotation.x = 0;
  53419. this._copy.rotation.y = 0;
  53420. this._copy.rotation.z = 0;
  53421. this._copy.rotationQuaternion = null;
  53422. this._copy.scaling.x = 1.0;
  53423. this._copy.scaling.y = 1.0;
  53424. this._copy.scaling.z = 1.0;
  53425. this._copy.uvs.x = 0;
  53426. this._copy.uvs.y = 0;
  53427. this._copy.uvs.z = 1.0;
  53428. this._copy.uvs.w = 1.0;
  53429. this._copy.color = null;
  53430. this._copy.translateFromPivot = false;
  53431. };
  53432. // _meshBuilder : inserts the shape model in the global SPS mesh
  53433. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53434. var i;
  53435. var u = 0;
  53436. var c = 0;
  53437. var n = 0;
  53438. this._resetCopy();
  53439. if (options && options.positionFunction) {
  53440. options.positionFunction(this._copy, idx, idxInShape);
  53441. this._mustUnrotateFixedNormals = true;
  53442. }
  53443. if (this._copy.rotationQuaternion) {
  53444. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53445. }
  53446. else {
  53447. this._yaw = this._copy.rotation.y;
  53448. this._pitch = this._copy.rotation.x;
  53449. this._roll = this._copy.rotation.z;
  53450. this._quaternionRotationYPR();
  53451. }
  53452. this._quaternionToRotationMatrix();
  53453. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53454. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53455. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53456. if (this._copy.translateFromPivot) {
  53457. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53458. }
  53459. else {
  53460. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53461. }
  53462. for (i = 0; i < shape.length; i++) {
  53463. this._vertex.x = shape[i].x;
  53464. this._vertex.y = shape[i].y;
  53465. this._vertex.z = shape[i].z;
  53466. if (options && options.vertexFunction) {
  53467. options.vertexFunction(this._copy, this._vertex, i);
  53468. }
  53469. this._vertex.x *= this._copy.scaling.x;
  53470. this._vertex.y *= this._copy.scaling.y;
  53471. this._vertex.z *= this._copy.scaling.z;
  53472. this._vertex.x -= this._scaledPivot.x;
  53473. this._vertex.y -= this._scaledPivot.y;
  53474. this._vertex.z -= this._scaledPivot.z;
  53475. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53476. this._rotated.addInPlace(this._pivotBackTranslation);
  53477. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53478. if (meshUV) {
  53479. 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);
  53480. u += 2;
  53481. }
  53482. if (this._copy.color) {
  53483. this._color = this._copy.color;
  53484. }
  53485. else if (meshCol && meshCol[c] !== undefined) {
  53486. this._color.r = meshCol[c];
  53487. this._color.g = meshCol[c + 1];
  53488. this._color.b = meshCol[c + 2];
  53489. this._color.a = meshCol[c + 3];
  53490. }
  53491. else {
  53492. this._color.r = 1.0;
  53493. this._color.g = 1.0;
  53494. this._color.b = 1.0;
  53495. this._color.a = 1.0;
  53496. }
  53497. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53498. c += 4;
  53499. if (!this.recomputeNormals && meshNor) {
  53500. this._normal.x = meshNor[n];
  53501. this._normal.y = meshNor[n + 1];
  53502. this._normal.z = meshNor[n + 2];
  53503. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53504. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53505. n += 3;
  53506. }
  53507. }
  53508. for (i = 0; i < meshInd.length; i++) {
  53509. var current_ind = p + meshInd[i];
  53510. indices.push(current_ind);
  53511. if (current_ind > 65535) {
  53512. this._needs32Bits = true;
  53513. }
  53514. }
  53515. if (this._pickable) {
  53516. var nbfaces = meshInd.length / 3;
  53517. for (i = 0; i < nbfaces; i++) {
  53518. this.pickedParticles.push({ idx: idx, faceId: i });
  53519. }
  53520. }
  53521. if (this._depthSort) {
  53522. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53523. }
  53524. return this._copy;
  53525. };
  53526. // returns a shape array from positions array
  53527. SolidParticleSystem.prototype._posToShape = function (positions) {
  53528. var shape = [];
  53529. for (var i = 0; i < positions.length; i += 3) {
  53530. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53531. }
  53532. return shape;
  53533. };
  53534. // returns a shapeUV array from a Vector4 uvs
  53535. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53536. var shapeUV = [];
  53537. if (uvs) {
  53538. for (var i = 0; i < uvs.length; i++)
  53539. shapeUV.push(uvs[i]);
  53540. }
  53541. return shapeUV;
  53542. };
  53543. // adds a new particle object in the particles array
  53544. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53545. if (bInfo === void 0) { bInfo = null; }
  53546. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53547. this.particles.push(sp);
  53548. return sp;
  53549. };
  53550. /**
  53551. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53552. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53553. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53554. * @param nb (positive integer) the number of particles to be created from this model
  53555. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53556. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53557. * @returns the number of shapes in the system
  53558. */
  53559. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53560. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53561. var meshInd = mesh.getIndices();
  53562. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53563. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53564. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53565. var bbInfo;
  53566. if (this._particlesIntersect) {
  53567. bbInfo = mesh.getBoundingInfo();
  53568. }
  53569. var shape = this._posToShape(meshPos);
  53570. var shapeUV = this._uvsToShapeUV(meshUV);
  53571. var posfunc = options ? options.positionFunction : null;
  53572. var vtxfunc = options ? options.vertexFunction : null;
  53573. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53574. // particles
  53575. var sp;
  53576. var currentCopy;
  53577. var idx = this.nbParticles;
  53578. for (var i = 0; i < nb; i++) {
  53579. var currentPos = this._positions.length;
  53580. var currentInd = this._indices.length;
  53581. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53582. if (this._updatable) {
  53583. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53584. sp.position.copyFrom(currentCopy.position);
  53585. sp.rotation.copyFrom(currentCopy.rotation);
  53586. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53587. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53588. }
  53589. if (currentCopy.color && sp.color) {
  53590. sp.color.copyFrom(currentCopy.color);
  53591. }
  53592. sp.scaling.copyFrom(currentCopy.scaling);
  53593. sp.uvs.copyFrom(currentCopy.uvs);
  53594. }
  53595. this._index += shape.length;
  53596. idx++;
  53597. }
  53598. this.nbParticles += nb;
  53599. this._shapeCounter++;
  53600. return this._shapeCounter - 1;
  53601. };
  53602. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53603. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53604. this._resetCopy();
  53605. if (particle._model._positionFunction) {
  53606. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53607. }
  53608. if (this._copy.rotationQuaternion) {
  53609. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53610. }
  53611. else {
  53612. this._yaw = this._copy.rotation.y;
  53613. this._pitch = this._copy.rotation.x;
  53614. this._roll = this._copy.rotation.z;
  53615. this._quaternionRotationYPR();
  53616. }
  53617. this._quaternionToRotationMatrix();
  53618. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53619. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53620. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53621. if (this._copy.translateFromPivot) {
  53622. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53623. }
  53624. else {
  53625. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53626. }
  53627. this._shape = particle._model._shape;
  53628. for (var pt = 0; pt < this._shape.length; pt++) {
  53629. this._vertex.x = this._shape[pt].x;
  53630. this._vertex.y = this._shape[pt].y;
  53631. this._vertex.z = this._shape[pt].z;
  53632. if (particle._model._vertexFunction) {
  53633. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53634. }
  53635. this._vertex.x *= this._copy.scaling.x;
  53636. this._vertex.y *= this._copy.scaling.y;
  53637. this._vertex.z *= this._copy.scaling.z;
  53638. this._vertex.x -= this._scaledPivot.x;
  53639. this._vertex.y -= this._scaledPivot.y;
  53640. this._vertex.z -= this._scaledPivot.z;
  53641. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53642. this._rotated.addInPlace(this._pivotBackTranslation);
  53643. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53644. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53645. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53646. }
  53647. particle.position.x = 0.0;
  53648. particle.position.y = 0.0;
  53649. particle.position.z = 0.0;
  53650. particle.rotation.x = 0.0;
  53651. particle.rotation.y = 0.0;
  53652. particle.rotation.z = 0.0;
  53653. particle.rotationQuaternion = null;
  53654. particle.scaling.x = 1.0;
  53655. particle.scaling.y = 1.0;
  53656. particle.scaling.z = 1.0;
  53657. particle.uvs.x = 0.0;
  53658. particle.uvs.y = 0.0;
  53659. particle.uvs.z = 1.0;
  53660. particle.uvs.w = 1.0;
  53661. particle.pivot.x = 0.0;
  53662. particle.pivot.y = 0.0;
  53663. particle.pivot.z = 0.0;
  53664. particle.translateFromPivot = false;
  53665. particle.parentId = null;
  53666. };
  53667. /**
  53668. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53669. * @returns the SPS.
  53670. */
  53671. SolidParticleSystem.prototype.rebuildMesh = function () {
  53672. for (var p = 0; p < this.particles.length; p++) {
  53673. this._rebuildParticle(this.particles[p]);
  53674. }
  53675. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53676. return this;
  53677. };
  53678. /**
  53679. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53680. * This method calls `updateParticle()` for each particle of the SPS.
  53681. * For an animated SPS, it is usually called within the render loop.
  53682. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53683. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53684. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53685. * @returns the SPS.
  53686. */
  53687. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53688. if (start === void 0) { start = 0; }
  53689. if (end === void 0) { end = this.nbParticles - 1; }
  53690. if (update === void 0) { update = true; }
  53691. if (!this._updatable) {
  53692. return this;
  53693. }
  53694. // custom beforeUpdate
  53695. this.beforeUpdateParticles(start, end, update);
  53696. this._cam_axisX.x = 1.0;
  53697. this._cam_axisX.y = 0.0;
  53698. this._cam_axisX.z = 0.0;
  53699. this._cam_axisY.x = 0.0;
  53700. this._cam_axisY.y = 1.0;
  53701. this._cam_axisY.z = 0.0;
  53702. this._cam_axisZ.x = 0.0;
  53703. this._cam_axisZ.y = 0.0;
  53704. this._cam_axisZ.z = 1.0;
  53705. // cases when the World Matrix is to be computed first
  53706. if (this.billboard || this._depthSort) {
  53707. this.mesh.computeWorldMatrix(true);
  53708. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53709. }
  53710. // if the particles will always face the camera
  53711. if (this.billboard) {
  53712. // compute the camera position and un-rotate it by the current mesh rotation
  53713. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53714. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53715. this._cam_axisZ.normalize();
  53716. // same for camera up vector extracted from the cam view matrix
  53717. var view = this._camera.getViewMatrix(true);
  53718. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53719. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53720. this._cam_axisY.normalize();
  53721. this._cam_axisX.normalize();
  53722. }
  53723. // if depthSort, compute the camera global position in the mesh local system
  53724. if (this._depthSort) {
  53725. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53726. }
  53727. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53728. var idx = 0; // current position index in the global array positions32
  53729. var index = 0; // position start index in the global array positions32 of the current particle
  53730. var colidx = 0; // current color index in the global array colors32
  53731. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53732. var uvidx = 0; // current uv index in the global array uvs32
  53733. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53734. var pt = 0; // current index in the particle model shape
  53735. if (this.mesh.isFacetDataEnabled) {
  53736. this._computeBoundingBox = true;
  53737. }
  53738. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53739. if (this._computeBoundingBox) {
  53740. if (start == 0 && end == this.nbParticles - 1) {
  53741. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53742. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53743. }
  53744. else {
  53745. if (this.mesh._boundingInfo) {
  53746. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53747. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53748. }
  53749. }
  53750. }
  53751. // particle loop
  53752. index = this.particles[start]._pos;
  53753. var vpos = (index / 3) | 0;
  53754. colorIndex = vpos * 4;
  53755. uvIndex = vpos * 2;
  53756. for (var p = start; p <= end; p++) {
  53757. this._particle = this.particles[p];
  53758. this._shape = this._particle._model._shape;
  53759. this._shapeUV = this._particle._model._shapeUV;
  53760. // call to custom user function to update the particle properties
  53761. this.updateParticle(this._particle);
  53762. // camera-particle distance for depth sorting
  53763. if (this._depthSort && this._depthSortParticles) {
  53764. var dsp = this.depthSortedParticles[p];
  53765. dsp.ind = this._particle._ind;
  53766. dsp.indicesLength = this._particle._model._indicesLength;
  53767. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53768. }
  53769. // skip the computations for inactive or already invisible particles
  53770. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53771. // increment indexes for the next particle
  53772. pt = this._shape.length;
  53773. index += pt * 3;
  53774. colorIndex += pt * 4;
  53775. uvIndex += pt * 2;
  53776. continue;
  53777. }
  53778. if (this._particle.isVisible) {
  53779. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53780. this._particleHasParent = (this._particle.parentId !== null);
  53781. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53782. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53783. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53784. // particle rotation matrix
  53785. if (this.billboard) {
  53786. this._particle.rotation.x = 0.0;
  53787. this._particle.rotation.y = 0.0;
  53788. }
  53789. if (this._computeParticleRotation || this.billboard) {
  53790. if (this._particle.rotationQuaternion) {
  53791. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53792. }
  53793. else {
  53794. this._yaw = this._particle.rotation.y;
  53795. this._pitch = this._particle.rotation.x;
  53796. this._roll = this._particle.rotation.z;
  53797. this._quaternionRotationYPR();
  53798. }
  53799. this._quaternionToRotationMatrix();
  53800. }
  53801. if (this._particleHasParent) {
  53802. this._parent = this.particles[this._particle.parentId];
  53803. 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];
  53804. 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];
  53805. 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];
  53806. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53807. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53808. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53809. if (this._computeParticleRotation || this.billboard) {
  53810. 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];
  53811. 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];
  53812. 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];
  53813. 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];
  53814. 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];
  53815. 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];
  53816. 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];
  53817. 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];
  53818. 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];
  53819. }
  53820. }
  53821. else {
  53822. this._particle._globalPosition.x = this._particle.position.x;
  53823. this._particle._globalPosition.y = this._particle.position.y;
  53824. this._particle._globalPosition.z = this._particle.position.z;
  53825. if (this._computeParticleRotation || this.billboard) {
  53826. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53827. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53828. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53829. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53830. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53831. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53832. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53833. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53834. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53835. }
  53836. }
  53837. if (this._particle.translateFromPivot) {
  53838. this._pivotBackTranslation.x = 0.0;
  53839. this._pivotBackTranslation.y = 0.0;
  53840. this._pivotBackTranslation.z = 0.0;
  53841. }
  53842. else {
  53843. this._pivotBackTranslation.x = this._scaledPivot.x;
  53844. this._pivotBackTranslation.y = this._scaledPivot.y;
  53845. this._pivotBackTranslation.z = this._scaledPivot.z;
  53846. }
  53847. // particle vertex loop
  53848. for (pt = 0; pt < this._shape.length; pt++) {
  53849. idx = index + pt * 3;
  53850. colidx = colorIndex + pt * 4;
  53851. uvidx = uvIndex + pt * 2;
  53852. this._vertex.x = this._shape[pt].x;
  53853. this._vertex.y = this._shape[pt].y;
  53854. this._vertex.z = this._shape[pt].z;
  53855. if (this._computeParticleVertex) {
  53856. this.updateParticleVertex(this._particle, this._vertex, pt);
  53857. }
  53858. // positions
  53859. this._vertex.x *= this._particle.scaling.x;
  53860. this._vertex.y *= this._particle.scaling.y;
  53861. this._vertex.z *= this._particle.scaling.z;
  53862. this._vertex.x -= this._scaledPivot.x;
  53863. this._vertex.y -= this._scaledPivot.y;
  53864. this._vertex.z -= this._scaledPivot.z;
  53865. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53866. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53867. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53868. this._rotated.x += this._pivotBackTranslation.x;
  53869. this._rotated.y += this._pivotBackTranslation.y;
  53870. this._rotated.z += this._pivotBackTranslation.z;
  53871. 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;
  53872. 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;
  53873. 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;
  53874. if (this._computeBoundingBox) {
  53875. if (this._positions32[idx] < this._minimum.x) {
  53876. this._minimum.x = this._positions32[idx];
  53877. }
  53878. if (this._positions32[idx] > this._maximum.x) {
  53879. this._maximum.x = this._positions32[idx];
  53880. }
  53881. if (this._positions32[idx + 1] < this._minimum.y) {
  53882. this._minimum.y = this._positions32[idx + 1];
  53883. }
  53884. if (this._positions32[idx + 1] > this._maximum.y) {
  53885. this._maximum.y = this._positions32[idx + 1];
  53886. }
  53887. if (this._positions32[idx + 2] < this._minimum.z) {
  53888. this._minimum.z = this._positions32[idx + 2];
  53889. }
  53890. if (this._positions32[idx + 2] > this._maximum.z) {
  53891. this._maximum.z = this._positions32[idx + 2];
  53892. }
  53893. }
  53894. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53895. if (!this._computeParticleVertex) {
  53896. this._normal.x = this._fixedNormal32[idx];
  53897. this._normal.y = this._fixedNormal32[idx + 1];
  53898. this._normal.z = this._fixedNormal32[idx + 2];
  53899. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53900. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53901. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53902. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53903. 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;
  53904. 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;
  53905. }
  53906. if (this._computeParticleColor && this._particle.color) {
  53907. this._colors32[colidx] = this._particle.color.r;
  53908. this._colors32[colidx + 1] = this._particle.color.g;
  53909. this._colors32[colidx + 2] = this._particle.color.b;
  53910. this._colors32[colidx + 3] = this._particle.color.a;
  53911. }
  53912. if (this._computeParticleTexture) {
  53913. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53914. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53915. }
  53916. }
  53917. }
  53918. else {
  53919. this._particle._stillInvisible = true; // mark the particle as invisible
  53920. for (pt = 0; pt < this._shape.length; pt++) {
  53921. idx = index + pt * 3;
  53922. colidx = colorIndex + pt * 4;
  53923. uvidx = uvIndex + pt * 2;
  53924. this._positions32[idx] = 0.0;
  53925. this._positions32[idx + 1] = 0.0;
  53926. this._positions32[idx + 2] = 0.0;
  53927. this._normals32[idx] = 0.0;
  53928. this._normals32[idx + 1] = 0.0;
  53929. this._normals32[idx + 2] = 0.0;
  53930. if (this._computeParticleColor && this._particle.color) {
  53931. this._colors32[colidx] = this._particle.color.r;
  53932. this._colors32[colidx + 1] = this._particle.color.g;
  53933. this._colors32[colidx + 2] = this._particle.color.b;
  53934. this._colors32[colidx + 3] = this._particle.color.a;
  53935. }
  53936. if (this._computeParticleTexture) {
  53937. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53938. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53939. }
  53940. }
  53941. }
  53942. // if the particle intersections must be computed : update the bbInfo
  53943. if (this._particlesIntersect) {
  53944. var bInfo = this._particle._boundingInfo;
  53945. var bBox = bInfo.boundingBox;
  53946. var bSphere = bInfo.boundingSphere;
  53947. if (!this._bSphereOnly) {
  53948. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53949. for (var b = 0; b < bBox.vectors.length; b++) {
  53950. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53951. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53952. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53953. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53954. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53955. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53956. 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;
  53957. 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;
  53958. 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;
  53959. }
  53960. bBox._update(this.mesh._worldMatrix);
  53961. }
  53962. // place and scale the particle bouding sphere in the SPS local system, then update it
  53963. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53964. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53965. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53966. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53967. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53968. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53969. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53970. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53971. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53972. 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));
  53973. bSphere._update(this.mesh._worldMatrix);
  53974. }
  53975. // increment indexes for the next particle
  53976. index = idx + 3;
  53977. colorIndex = colidx + 4;
  53978. uvIndex = uvidx + 2;
  53979. }
  53980. // if the VBO must be updated
  53981. if (update) {
  53982. if (this._computeParticleColor) {
  53983. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53984. }
  53985. if (this._computeParticleTexture) {
  53986. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53987. }
  53988. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53989. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53990. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53991. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53992. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53993. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53994. for (var i = 0; i < this._normals32.length; i++) {
  53995. this._fixedNormal32[i] = this._normals32[i];
  53996. }
  53997. }
  53998. if (!this.mesh.areNormalsFrozen) {
  53999. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54000. }
  54001. }
  54002. if (this._depthSort && this._depthSortParticles) {
  54003. this.depthSortedParticles.sort(this._depthSortFunction);
  54004. var dspl = this.depthSortedParticles.length;
  54005. var sorted = 0;
  54006. var lind = 0;
  54007. var sind = 0;
  54008. var sid = 0;
  54009. for (sorted = 0; sorted < dspl; sorted++) {
  54010. lind = this.depthSortedParticles[sorted].indicesLength;
  54011. sind = this.depthSortedParticles[sorted].ind;
  54012. for (var i = 0; i < lind; i++) {
  54013. this._indices32[sid] = this._indices[sind + i];
  54014. sid++;
  54015. }
  54016. }
  54017. this.mesh.updateIndices(this._indices32);
  54018. }
  54019. }
  54020. if (this._computeBoundingBox) {
  54021. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54022. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54023. }
  54024. this.afterUpdateParticles(start, end, update);
  54025. return this;
  54026. };
  54027. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54028. this._halfroll = this._roll * 0.5;
  54029. this._halfpitch = this._pitch * 0.5;
  54030. this._halfyaw = this._yaw * 0.5;
  54031. this._sinRoll = Math.sin(this._halfroll);
  54032. this._cosRoll = Math.cos(this._halfroll);
  54033. this._sinPitch = Math.sin(this._halfpitch);
  54034. this._cosPitch = Math.cos(this._halfpitch);
  54035. this._sinYaw = Math.sin(this._halfyaw);
  54036. this._cosYaw = Math.cos(this._halfyaw);
  54037. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54038. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54039. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54040. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54041. };
  54042. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54043. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54044. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54045. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54046. this._rotMatrix.m[3] = 0;
  54047. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54048. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54049. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54050. this._rotMatrix.m[7] = 0;
  54051. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54052. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54053. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54054. this._rotMatrix.m[11] = 0;
  54055. this._rotMatrix.m[12] = 0;
  54056. this._rotMatrix.m[13] = 0;
  54057. this._rotMatrix.m[14] = 0;
  54058. this._rotMatrix.m[15] = 1.0;
  54059. };
  54060. /**
  54061. * Disposes the SPS.
  54062. */
  54063. SolidParticleSystem.prototype.dispose = function () {
  54064. this.mesh.dispose();
  54065. this.vars = null;
  54066. // drop references to internal big arrays for the GC
  54067. this._positions = null;
  54068. this._indices = null;
  54069. this._normals = null;
  54070. this._uvs = null;
  54071. this._colors = null;
  54072. this._indices32 = null;
  54073. this._positions32 = null;
  54074. this._normals32 = null;
  54075. this._fixedNormal32 = null;
  54076. this._uvs32 = null;
  54077. this._colors32 = null;
  54078. this.pickedParticles = null;
  54079. };
  54080. /**
  54081. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54082. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54083. * @returns the SPS.
  54084. */
  54085. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54086. if (!this._isVisibilityBoxLocked) {
  54087. this.mesh.refreshBoundingInfo();
  54088. }
  54089. return this;
  54090. };
  54091. /**
  54092. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54093. * @param size the size (float) of the visibility box
  54094. * note : this doesn't lock the SPS mesh bounding box.
  54095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54096. */
  54097. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54098. var vis = size / 2;
  54099. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54100. };
  54101. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54102. /**
  54103. * Gets whether the SPS as always visible or not
  54104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54105. */
  54106. get: function () {
  54107. return this._alwaysVisible;
  54108. },
  54109. /**
  54110. * Sets the SPS as always visible or not
  54111. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54112. */
  54113. set: function (val) {
  54114. this._alwaysVisible = val;
  54115. this.mesh.alwaysSelectAsActiveMesh = val;
  54116. },
  54117. enumerable: true,
  54118. configurable: true
  54119. });
  54120. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54121. /**
  54122. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54123. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54124. */
  54125. get: function () {
  54126. return this._isVisibilityBoxLocked;
  54127. },
  54128. /**
  54129. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54130. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54131. */
  54132. set: function (val) {
  54133. this._isVisibilityBoxLocked = val;
  54134. var boundingInfo = this.mesh.getBoundingInfo();
  54135. boundingInfo.isLocked = val;
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54141. /**
  54142. * Gets if `setParticles()` computes the particle rotations or not.
  54143. * Default value : true. The SPS is faster when it's set to false.
  54144. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54145. */
  54146. get: function () {
  54147. return this._computeParticleRotation;
  54148. },
  54149. /**
  54150. * Tells to `setParticles()` to compute the particle rotations or not.
  54151. * Default value : true. The SPS is faster when it's set to false.
  54152. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54153. */
  54154. set: function (val) {
  54155. this._computeParticleRotation = val;
  54156. },
  54157. enumerable: true,
  54158. configurable: true
  54159. });
  54160. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54161. /**
  54162. * Gets if `setParticles()` computes the particle colors or not.
  54163. * Default value : true. The SPS is faster when it's set to false.
  54164. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54165. */
  54166. get: function () {
  54167. return this._computeParticleColor;
  54168. },
  54169. /**
  54170. * Tells to `setParticles()` to compute the particle colors or not.
  54171. * Default value : true. The SPS is faster when it's set to false.
  54172. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54173. */
  54174. set: function (val) {
  54175. this._computeParticleColor = val;
  54176. },
  54177. enumerable: true,
  54178. configurable: true
  54179. });
  54180. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54181. /**
  54182. * Gets if `setParticles()` computes the particle textures or not.
  54183. * Default value : true. The SPS is faster when it's set to false.
  54184. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54185. */
  54186. get: function () {
  54187. return this._computeParticleTexture;
  54188. },
  54189. set: function (val) {
  54190. this._computeParticleTexture = val;
  54191. },
  54192. enumerable: true,
  54193. configurable: true
  54194. });
  54195. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54196. /**
  54197. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54198. * Default value : false. The SPS is faster when it's set to false.
  54199. * Note : the particle custom vertex positions aren't stored values.
  54200. */
  54201. get: function () {
  54202. return this._computeParticleVertex;
  54203. },
  54204. /**
  54205. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54206. * Default value : false. The SPS is faster when it's set to false.
  54207. * Note : the particle custom vertex positions aren't stored values.
  54208. */
  54209. set: function (val) {
  54210. this._computeParticleVertex = val;
  54211. },
  54212. enumerable: true,
  54213. configurable: true
  54214. });
  54215. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54216. /**
  54217. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54218. */
  54219. get: function () {
  54220. return this._computeBoundingBox;
  54221. },
  54222. /**
  54223. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54224. */
  54225. set: function (val) {
  54226. this._computeBoundingBox = val;
  54227. },
  54228. enumerable: true,
  54229. configurable: true
  54230. });
  54231. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54232. /**
  54233. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54234. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54235. * Default : `true`
  54236. */
  54237. get: function () {
  54238. return this._depthSortParticles;
  54239. },
  54240. /**
  54241. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54242. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54243. * Default : `true`
  54244. */
  54245. set: function (val) {
  54246. this._depthSortParticles = val;
  54247. },
  54248. enumerable: true,
  54249. configurable: true
  54250. });
  54251. // =======================================================================
  54252. // Particle behavior logic
  54253. // these following methods may be overwritten by the user to fit his needs
  54254. /**
  54255. * This function does nothing. It may be overwritten to set all the particle first values.
  54256. * The SPS doesn't call this function, you may have to call it by your own.
  54257. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54258. */
  54259. SolidParticleSystem.prototype.initParticles = function () {
  54260. };
  54261. /**
  54262. * This function does nothing. It may be overwritten to recycle a particle.
  54263. * The SPS doesn't call this function, you may have to call it by your own.
  54264. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54265. * @param particle The particle to recycle
  54266. * @returns the recycled particle
  54267. */
  54268. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54269. return particle;
  54270. };
  54271. /**
  54272. * Updates a particle : this function should be overwritten by the user.
  54273. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54274. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54275. * @example : just set a particle position or velocity and recycle conditions
  54276. * @param particle The particle to update
  54277. * @returns the updated particle
  54278. */
  54279. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54280. return particle;
  54281. };
  54282. /**
  54283. * Updates a vertex of a particle : it can be overwritten by the user.
  54284. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54285. * @param particle the current particle
  54286. * @param vertex the current index of the current particle
  54287. * @param pt the index of the current vertex in the particle shape
  54288. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54289. * @example : just set a vertex particle position
  54290. * @returns the updated vertex
  54291. */
  54292. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54293. return vertex;
  54294. };
  54295. /**
  54296. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54297. * This does nothing and may be overwritten by the user.
  54298. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54299. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54300. * @param update the boolean update value actually passed to setParticles()
  54301. */
  54302. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54303. };
  54304. /**
  54305. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54306. * This will be passed three parameters.
  54307. * This does nothing and may be overwritten by the user.
  54308. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54309. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54310. * @param update the boolean update value actually passed to setParticles()
  54311. */
  54312. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54313. };
  54314. return SolidParticleSystem;
  54315. }());
  54316. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54317. })(BABYLON || (BABYLON = {}));
  54318. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54319. var BABYLON;
  54320. (function (BABYLON) {
  54321. var ShaderMaterial = /** @class */ (function (_super) {
  54322. __extends(ShaderMaterial, _super);
  54323. function ShaderMaterial(name, scene, shaderPath, options) {
  54324. var _this = _super.call(this, name, scene) || this;
  54325. _this._textures = {};
  54326. _this._textureArrays = {};
  54327. _this._floats = {};
  54328. _this._ints = {};
  54329. _this._floatsArrays = {};
  54330. _this._colors3 = {};
  54331. _this._colors3Arrays = {};
  54332. _this._colors4 = {};
  54333. _this._vectors2 = {};
  54334. _this._vectors3 = {};
  54335. _this._vectors4 = {};
  54336. _this._matrices = {};
  54337. _this._matrices3x3 = {};
  54338. _this._matrices2x2 = {};
  54339. _this._vectors2Arrays = {};
  54340. _this._vectors3Arrays = {};
  54341. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54342. _this._shaderPath = shaderPath;
  54343. options.needAlphaBlending = options.needAlphaBlending || false;
  54344. options.needAlphaTesting = options.needAlphaTesting || false;
  54345. options.attributes = options.attributes || ["position", "normal", "uv"];
  54346. options.uniforms = options.uniforms || ["worldViewProjection"];
  54347. options.uniformBuffers = options.uniformBuffers || [];
  54348. options.samplers = options.samplers || [];
  54349. options.defines = options.defines || [];
  54350. _this._options = options;
  54351. return _this;
  54352. }
  54353. ShaderMaterial.prototype.getClassName = function () {
  54354. return "ShaderMaterial";
  54355. };
  54356. ShaderMaterial.prototype.needAlphaBlending = function () {
  54357. return this._options.needAlphaBlending;
  54358. };
  54359. ShaderMaterial.prototype.needAlphaTesting = function () {
  54360. return this._options.needAlphaTesting;
  54361. };
  54362. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54363. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54364. this._options.uniforms.push(uniformName);
  54365. }
  54366. };
  54367. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54368. if (this._options.samplers.indexOf(name) === -1) {
  54369. this._options.samplers.push(name);
  54370. }
  54371. this._textures[name] = texture;
  54372. return this;
  54373. };
  54374. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54375. if (this._options.samplers.indexOf(name) === -1) {
  54376. this._options.samplers.push(name);
  54377. }
  54378. this._checkUniform(name);
  54379. this._textureArrays[name] = textures;
  54380. return this;
  54381. };
  54382. ShaderMaterial.prototype.setFloat = function (name, value) {
  54383. this._checkUniform(name);
  54384. this._floats[name] = value;
  54385. return this;
  54386. };
  54387. ShaderMaterial.prototype.setInt = function (name, value) {
  54388. this._checkUniform(name);
  54389. this._ints[name] = value;
  54390. return this;
  54391. };
  54392. ShaderMaterial.prototype.setFloats = function (name, value) {
  54393. this._checkUniform(name);
  54394. this._floatsArrays[name] = value;
  54395. return this;
  54396. };
  54397. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54398. this._checkUniform(name);
  54399. this._colors3[name] = value;
  54400. return this;
  54401. };
  54402. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54403. this._checkUniform(name);
  54404. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54405. color.toArray(arr, arr.length);
  54406. return arr;
  54407. }, []);
  54408. return this;
  54409. };
  54410. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54411. this._checkUniform(name);
  54412. this._colors4[name] = value;
  54413. return this;
  54414. };
  54415. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54416. this._checkUniform(name);
  54417. this._vectors2[name] = value;
  54418. return this;
  54419. };
  54420. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54421. this._checkUniform(name);
  54422. this._vectors3[name] = value;
  54423. return this;
  54424. };
  54425. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54426. this._checkUniform(name);
  54427. this._vectors4[name] = value;
  54428. return this;
  54429. };
  54430. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54431. this._checkUniform(name);
  54432. this._matrices[name] = value;
  54433. return this;
  54434. };
  54435. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54436. this._checkUniform(name);
  54437. this._matrices3x3[name] = value;
  54438. return this;
  54439. };
  54440. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54441. this._checkUniform(name);
  54442. this._matrices2x2[name] = value;
  54443. return this;
  54444. };
  54445. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54446. this._checkUniform(name);
  54447. this._vectors2Arrays[name] = value;
  54448. return this;
  54449. };
  54450. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54451. this._checkUniform(name);
  54452. this._vectors3Arrays[name] = value;
  54453. return this;
  54454. };
  54455. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54456. if (!mesh) {
  54457. return true;
  54458. }
  54459. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54460. return false;
  54461. }
  54462. return false;
  54463. };
  54464. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54465. var scene = this.getScene();
  54466. var engine = scene.getEngine();
  54467. if (!this.checkReadyOnEveryCall) {
  54468. if (this._renderId === scene.getRenderId()) {
  54469. if (this._checkCache(scene, mesh, useInstances)) {
  54470. return true;
  54471. }
  54472. }
  54473. }
  54474. // Instances
  54475. var defines = [];
  54476. var attribs = [];
  54477. var fallbacks = new BABYLON.EffectFallbacks();
  54478. if (useInstances) {
  54479. defines.push("#define INSTANCES");
  54480. }
  54481. for (var index = 0; index < this._options.defines.length; index++) {
  54482. defines.push(this._options.defines[index]);
  54483. }
  54484. for (var index = 0; index < this._options.attributes.length; index++) {
  54485. attribs.push(this._options.attributes[index]);
  54486. }
  54487. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54489. defines.push("#define VERTEXCOLOR");
  54490. }
  54491. // Bones
  54492. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54495. if (mesh.numBoneInfluencers > 4) {
  54496. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54497. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54498. }
  54499. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54500. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54501. fallbacks.addCPUSkinningFallback(0, mesh);
  54502. if (this._options.uniforms.indexOf("mBones") === -1) {
  54503. this._options.uniforms.push("mBones");
  54504. }
  54505. }
  54506. else {
  54507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54508. }
  54509. // Textures
  54510. for (var name in this._textures) {
  54511. if (!this._textures[name].isReady()) {
  54512. return false;
  54513. }
  54514. }
  54515. // Alpha test
  54516. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54517. defines.push("#define ALPHATEST");
  54518. }
  54519. var previousEffect = this._effect;
  54520. var join = defines.join("\n");
  54521. this._effect = engine.createEffect(this._shaderPath, {
  54522. attributes: attribs,
  54523. uniformsNames: this._options.uniforms,
  54524. uniformBuffersNames: this._options.uniformBuffers,
  54525. samplers: this._options.samplers,
  54526. defines: join,
  54527. fallbacks: fallbacks,
  54528. onCompiled: this.onCompiled,
  54529. onError: this.onError
  54530. }, engine);
  54531. if (!this._effect.isReady()) {
  54532. return false;
  54533. }
  54534. if (previousEffect !== this._effect) {
  54535. scene.resetCachedMaterial();
  54536. }
  54537. this._renderId = scene.getRenderId();
  54538. return true;
  54539. };
  54540. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54541. var scene = this.getScene();
  54542. if (!this._effect) {
  54543. return;
  54544. }
  54545. if (this._options.uniforms.indexOf("world") !== -1) {
  54546. this._effect.setMatrix("world", world);
  54547. }
  54548. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54549. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54550. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54551. }
  54552. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54553. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54554. }
  54555. };
  54556. ShaderMaterial.prototype.bind = function (world, mesh) {
  54557. // Std values
  54558. this.bindOnlyWorldMatrix(world);
  54559. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54560. if (this._options.uniforms.indexOf("view") !== -1) {
  54561. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54562. }
  54563. if (this._options.uniforms.indexOf("projection") !== -1) {
  54564. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54565. }
  54566. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54567. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54568. }
  54569. // Bones
  54570. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54571. var name;
  54572. // Texture
  54573. for (name in this._textures) {
  54574. this._effect.setTexture(name, this._textures[name]);
  54575. }
  54576. // Texture arrays
  54577. for (name in this._textureArrays) {
  54578. this._effect.setTextureArray(name, this._textureArrays[name]);
  54579. }
  54580. // Int
  54581. for (name in this._ints) {
  54582. this._effect.setInt(name, this._ints[name]);
  54583. }
  54584. // Float
  54585. for (name in this._floats) {
  54586. this._effect.setFloat(name, this._floats[name]);
  54587. }
  54588. // Floats
  54589. for (name in this._floatsArrays) {
  54590. this._effect.setArray(name, this._floatsArrays[name]);
  54591. }
  54592. // Color3
  54593. for (name in this._colors3) {
  54594. this._effect.setColor3(name, this._colors3[name]);
  54595. }
  54596. for (name in this._colors3Arrays) {
  54597. this._effect.setArray3(name, this._colors3Arrays[name]);
  54598. }
  54599. // Color4
  54600. for (name in this._colors4) {
  54601. var color = this._colors4[name];
  54602. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54603. }
  54604. // Vector2
  54605. for (name in this._vectors2) {
  54606. this._effect.setVector2(name, this._vectors2[name]);
  54607. }
  54608. // Vector3
  54609. for (name in this._vectors3) {
  54610. this._effect.setVector3(name, this._vectors3[name]);
  54611. }
  54612. // Vector4
  54613. for (name in this._vectors4) {
  54614. this._effect.setVector4(name, this._vectors4[name]);
  54615. }
  54616. // Matrix
  54617. for (name in this._matrices) {
  54618. this._effect.setMatrix(name, this._matrices[name]);
  54619. }
  54620. // Matrix 3x3
  54621. for (name in this._matrices3x3) {
  54622. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54623. }
  54624. // Matrix 2x2
  54625. for (name in this._matrices2x2) {
  54626. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54627. }
  54628. // Vector2Array
  54629. for (name in this._vectors2Arrays) {
  54630. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54631. }
  54632. // Vector3Array
  54633. for (name in this._vectors3Arrays) {
  54634. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54635. }
  54636. }
  54637. this._afterBind(mesh);
  54638. };
  54639. ShaderMaterial.prototype.getActiveTextures = function () {
  54640. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54641. for (var name in this._textures) {
  54642. activeTextures.push(this._textures[name]);
  54643. }
  54644. for (var name in this._textureArrays) {
  54645. var array = this._textureArrays[name];
  54646. for (var index = 0; index < array.length; index++) {
  54647. activeTextures.push(array[index]);
  54648. }
  54649. }
  54650. return activeTextures;
  54651. };
  54652. ShaderMaterial.prototype.hasTexture = function (texture) {
  54653. if (_super.prototype.hasTexture.call(this, texture)) {
  54654. return true;
  54655. }
  54656. for (var name in this._textures) {
  54657. if (this._textures[name] === texture) {
  54658. return true;
  54659. }
  54660. }
  54661. for (var name in this._textureArrays) {
  54662. var array = this._textureArrays[name];
  54663. for (var index = 0; index < array.length; index++) {
  54664. if (array[index] === texture) {
  54665. return true;
  54666. }
  54667. }
  54668. }
  54669. return false;
  54670. };
  54671. ShaderMaterial.prototype.clone = function (name) {
  54672. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54673. return newShaderMaterial;
  54674. };
  54675. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54676. if (forceDisposeTextures) {
  54677. var name;
  54678. for (name in this._textures) {
  54679. this._textures[name].dispose();
  54680. }
  54681. for (name in this._textureArrays) {
  54682. var array = this._textureArrays[name];
  54683. for (var index = 0; index < array.length; index++) {
  54684. array[index].dispose();
  54685. }
  54686. }
  54687. }
  54688. this._textures = {};
  54689. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54690. };
  54691. ShaderMaterial.prototype.serialize = function () {
  54692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54693. serializationObject.customType = "BABYLON.ShaderMaterial";
  54694. serializationObject.options = this._options;
  54695. serializationObject.shaderPath = this._shaderPath;
  54696. var name;
  54697. // Texture
  54698. serializationObject.textures = {};
  54699. for (name in this._textures) {
  54700. serializationObject.textures[name] = this._textures[name].serialize();
  54701. }
  54702. // Texture arrays
  54703. serializationObject.textureArrays = {};
  54704. for (name in this._textureArrays) {
  54705. serializationObject.textureArrays[name] = [];
  54706. var array = this._textureArrays[name];
  54707. for (var index = 0; index < array.length; index++) {
  54708. serializationObject.textureArrays[name].push(array[index].serialize());
  54709. }
  54710. }
  54711. // Float
  54712. serializationObject.floats = {};
  54713. for (name in this._floats) {
  54714. serializationObject.floats[name] = this._floats[name];
  54715. }
  54716. // Float s
  54717. serializationObject.FloatArrays = {};
  54718. for (name in this._floatsArrays) {
  54719. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54720. }
  54721. // Color3
  54722. serializationObject.colors3 = {};
  54723. for (name in this._colors3) {
  54724. serializationObject.colors3[name] = this._colors3[name].asArray();
  54725. }
  54726. // Color3 array
  54727. serializationObject.colors3Arrays = {};
  54728. for (name in this._colors3Arrays) {
  54729. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54730. }
  54731. // Color4
  54732. serializationObject.colors4 = {};
  54733. for (name in this._colors4) {
  54734. serializationObject.colors4[name] = this._colors4[name].asArray();
  54735. }
  54736. // Vector2
  54737. serializationObject.vectors2 = {};
  54738. for (name in this._vectors2) {
  54739. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54740. }
  54741. // Vector3
  54742. serializationObject.vectors3 = {};
  54743. for (name in this._vectors3) {
  54744. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54745. }
  54746. // Vector4
  54747. serializationObject.vectors4 = {};
  54748. for (name in this._vectors4) {
  54749. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54750. }
  54751. // Matrix
  54752. serializationObject.matrices = {};
  54753. for (name in this._matrices) {
  54754. serializationObject.matrices[name] = this._matrices[name].asArray();
  54755. }
  54756. // Matrix 3x3
  54757. serializationObject.matrices3x3 = {};
  54758. for (name in this._matrices3x3) {
  54759. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54760. }
  54761. // Matrix 2x2
  54762. serializationObject.matrices2x2 = {};
  54763. for (name in this._matrices2x2) {
  54764. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54765. }
  54766. // Vector2Array
  54767. serializationObject.vectors2Arrays = {};
  54768. for (name in this._vectors2Arrays) {
  54769. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54770. }
  54771. // Vector3Array
  54772. serializationObject.vectors3Arrays = {};
  54773. for (name in this._vectors3Arrays) {
  54774. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54775. }
  54776. return serializationObject;
  54777. };
  54778. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54779. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54780. var name;
  54781. // Texture
  54782. for (name in source.textures) {
  54783. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54784. }
  54785. // Texture arrays
  54786. for (name in source.textureArrays) {
  54787. var array = source.textureArrays[name];
  54788. var textureArray = new Array();
  54789. for (var index = 0; index < array.length; index++) {
  54790. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54791. }
  54792. material.setTextureArray(name, textureArray);
  54793. }
  54794. // Float
  54795. for (name in source.floats) {
  54796. material.setFloat(name, source.floats[name]);
  54797. }
  54798. // Float s
  54799. for (name in source.floatsArrays) {
  54800. material.setFloats(name, source.floatsArrays[name]);
  54801. }
  54802. // Color3
  54803. for (name in source.colors3) {
  54804. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54805. }
  54806. // Color3 arrays
  54807. for (name in source.colors3Arrays) {
  54808. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54809. if (i % 3 === 0) {
  54810. arr.push([num]);
  54811. }
  54812. else {
  54813. arr[arr.length - 1].push(num);
  54814. }
  54815. return arr;
  54816. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54817. material.setColor3Array(name, colors);
  54818. }
  54819. // Color4
  54820. for (name in source.colors4) {
  54821. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54822. }
  54823. // Vector2
  54824. for (name in source.vectors2) {
  54825. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54826. }
  54827. // Vector3
  54828. for (name in source.vectors3) {
  54829. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54830. }
  54831. // Vector4
  54832. for (name in source.vectors4) {
  54833. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54834. }
  54835. // Matrix
  54836. for (name in source.matrices) {
  54837. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54838. }
  54839. // Matrix 3x3
  54840. for (name in source.matrices3x3) {
  54841. material.setMatrix3x3(name, source.matrices3x3[name]);
  54842. }
  54843. // Matrix 2x2
  54844. for (name in source.matrices2x2) {
  54845. material.setMatrix2x2(name, source.matrices2x2[name]);
  54846. }
  54847. // Vector2Array
  54848. for (name in source.vectors2Arrays) {
  54849. material.setArray2(name, source.vectors2Arrays[name]);
  54850. }
  54851. // Vector3Array
  54852. for (name in source.vectors3Arrays) {
  54853. material.setArray3(name, source.vectors3Arrays[name]);
  54854. }
  54855. return material;
  54856. };
  54857. return ShaderMaterial;
  54858. }(BABYLON.Material));
  54859. BABYLON.ShaderMaterial = ShaderMaterial;
  54860. })(BABYLON || (BABYLON = {}));
  54861. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54862. var BABYLON;
  54863. (function (BABYLON) {
  54864. var GroundMesh = /** @class */ (function (_super) {
  54865. __extends(GroundMesh, _super);
  54866. function GroundMesh(name, scene) {
  54867. var _this = _super.call(this, name, scene) || this;
  54868. _this.generateOctree = false;
  54869. return _this;
  54870. }
  54871. GroundMesh.prototype.getClassName = function () {
  54872. return "GroundMesh";
  54873. };
  54874. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54875. get: function () {
  54876. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54877. },
  54878. enumerable: true,
  54879. configurable: true
  54880. });
  54881. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54882. get: function () {
  54883. return this._subdivisionsX;
  54884. },
  54885. enumerable: true,
  54886. configurable: true
  54887. });
  54888. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54889. get: function () {
  54890. return this._subdivisionsY;
  54891. },
  54892. enumerable: true,
  54893. configurable: true
  54894. });
  54895. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54896. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54897. this._subdivisionsX = chunksCount;
  54898. this._subdivisionsY = chunksCount;
  54899. this.subdivide(chunksCount);
  54900. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54901. };
  54902. /**
  54903. * Returns a height (y) value in the Worl system :
  54904. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54905. * Returns the ground y position if (x, z) are outside the ground surface.
  54906. */
  54907. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54908. var world = this.getWorldMatrix();
  54909. var invMat = BABYLON.Tmp.Matrix[5];
  54910. world.invertToRef(invMat);
  54911. var tmpVect = BABYLON.Tmp.Vector3[8];
  54912. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54913. x = tmpVect.x;
  54914. z = tmpVect.z;
  54915. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54916. return this.position.y;
  54917. }
  54918. if (!this._heightQuads || this._heightQuads.length == 0) {
  54919. this._initHeightQuads();
  54920. this._computeHeightQuads();
  54921. }
  54922. var facet = this._getFacetAt(x, z);
  54923. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54924. // return y in the World system
  54925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54926. return tmpVect.y;
  54927. };
  54928. /**
  54929. * Returns a normalized vector (Vector3) orthogonal to the ground
  54930. * at the ground coordinates (x, z) expressed in the World system.
  54931. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54932. */
  54933. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54934. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54935. this.getNormalAtCoordinatesToRef(x, z, normal);
  54936. return normal;
  54937. };
  54938. /**
  54939. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54940. * at the ground coordinates (x, z) expressed in the World system.
  54941. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54942. * Returns the GroundMesh.
  54943. */
  54944. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54945. var world = this.getWorldMatrix();
  54946. var tmpMat = BABYLON.Tmp.Matrix[5];
  54947. world.invertToRef(tmpMat);
  54948. var tmpVect = BABYLON.Tmp.Vector3[8];
  54949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54950. x = tmpVect.x;
  54951. z = tmpVect.z;
  54952. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54953. return this;
  54954. }
  54955. if (!this._heightQuads || this._heightQuads.length == 0) {
  54956. this._initHeightQuads();
  54957. this._computeHeightQuads();
  54958. }
  54959. var facet = this._getFacetAt(x, z);
  54960. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54961. return this;
  54962. };
  54963. /**
  54964. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54965. * if the ground has been updated.
  54966. * This can be used in the render loop.
  54967. * Returns the GroundMesh.
  54968. */
  54969. GroundMesh.prototype.updateCoordinateHeights = function () {
  54970. if (!this._heightQuads || this._heightQuads.length == 0) {
  54971. this._initHeightQuads();
  54972. }
  54973. this._computeHeightQuads();
  54974. return this;
  54975. };
  54976. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54977. GroundMesh.prototype._getFacetAt = function (x, z) {
  54978. // retrieve col and row from x, z coordinates in the ground local system
  54979. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54980. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54981. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54982. var facet;
  54983. if (z < quad.slope.x * x + quad.slope.y) {
  54984. facet = quad.facet1;
  54985. }
  54986. else {
  54987. facet = quad.facet2;
  54988. }
  54989. return facet;
  54990. };
  54991. // Creates and populates the heightMap array with "facet" elements :
  54992. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54993. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54994. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54995. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54996. // Returns the GroundMesh.
  54997. GroundMesh.prototype._initHeightQuads = function () {
  54998. var subdivisionsX = this._subdivisionsX;
  54999. var subdivisionsY = this._subdivisionsY;
  55000. this._heightQuads = new Array();
  55001. for (var row = 0; row < subdivisionsY; row++) {
  55002. for (var col = 0; col < subdivisionsX; col++) {
  55003. 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) };
  55004. this._heightQuads[row * subdivisionsX + col] = quad;
  55005. }
  55006. }
  55007. return this;
  55008. };
  55009. // Compute each quad element values and update the the heightMap array :
  55010. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55011. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55012. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55013. // Returns the GroundMesh.
  55014. GroundMesh.prototype._computeHeightQuads = function () {
  55015. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55016. if (!positions) {
  55017. return this;
  55018. }
  55019. var v1 = BABYLON.Tmp.Vector3[3];
  55020. var v2 = BABYLON.Tmp.Vector3[2];
  55021. var v3 = BABYLON.Tmp.Vector3[1];
  55022. var v4 = BABYLON.Tmp.Vector3[0];
  55023. var v1v2 = BABYLON.Tmp.Vector3[4];
  55024. var v1v3 = BABYLON.Tmp.Vector3[5];
  55025. var v1v4 = BABYLON.Tmp.Vector3[6];
  55026. var norm1 = BABYLON.Tmp.Vector3[7];
  55027. var norm2 = BABYLON.Tmp.Vector3[8];
  55028. var i = 0;
  55029. var j = 0;
  55030. var k = 0;
  55031. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55032. var h = 0;
  55033. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55034. var d2 = 0;
  55035. var subdivisionsX = this._subdivisionsX;
  55036. var subdivisionsY = this._subdivisionsY;
  55037. for (var row = 0; row < subdivisionsY; row++) {
  55038. for (var col = 0; col < subdivisionsX; col++) {
  55039. i = col * 3;
  55040. j = row * (subdivisionsX + 1) * 3;
  55041. k = (row + 1) * (subdivisionsX + 1) * 3;
  55042. v1.x = positions[j + i];
  55043. v1.y = positions[j + i + 1];
  55044. v1.z = positions[j + i + 2];
  55045. v2.x = positions[j + i + 3];
  55046. v2.y = positions[j + i + 4];
  55047. v2.z = positions[j + i + 5];
  55048. v3.x = positions[k + i];
  55049. v3.y = positions[k + i + 1];
  55050. v3.z = positions[k + i + 2];
  55051. v4.x = positions[k + i + 3];
  55052. v4.y = positions[k + i + 4];
  55053. v4.z = positions[k + i + 5];
  55054. // 2D slope V1V4
  55055. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55056. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55057. // facet equations :
  55058. // we compute each facet normal vector
  55059. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55060. // we compute the value d by applying the equation to v1 which belongs to the plane
  55061. // then we store the facet equation in a Vector4
  55062. v2.subtractToRef(v1, v1v2);
  55063. v3.subtractToRef(v1, v1v3);
  55064. v4.subtractToRef(v1, v1v4);
  55065. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55066. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55067. norm1.normalize();
  55068. norm2.normalize();
  55069. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55070. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55071. var quad = this._heightQuads[row * subdivisionsX + col];
  55072. quad.slope.copyFromFloats(cd, h);
  55073. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55074. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55075. }
  55076. }
  55077. return this;
  55078. };
  55079. GroundMesh.prototype.serialize = function (serializationObject) {
  55080. _super.prototype.serialize.call(this, serializationObject);
  55081. serializationObject.subdivisionsX = this._subdivisionsX;
  55082. serializationObject.subdivisionsY = this._subdivisionsY;
  55083. serializationObject.minX = this._minX;
  55084. serializationObject.maxX = this._maxX;
  55085. serializationObject.minZ = this._minZ;
  55086. serializationObject.maxZ = this._maxZ;
  55087. serializationObject.width = this._width;
  55088. serializationObject.height = this._height;
  55089. };
  55090. GroundMesh.Parse = function (parsedMesh, scene) {
  55091. var result = new GroundMesh(parsedMesh.name, scene);
  55092. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55093. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55094. result._minX = parsedMesh.minX;
  55095. result._maxX = parsedMesh.maxX;
  55096. result._minZ = parsedMesh.minZ;
  55097. result._maxZ = parsedMesh.maxZ;
  55098. result._width = parsedMesh.width;
  55099. result._height = parsedMesh.height;
  55100. return result;
  55101. };
  55102. return GroundMesh;
  55103. }(BABYLON.Mesh));
  55104. BABYLON.GroundMesh = GroundMesh;
  55105. })(BABYLON || (BABYLON = {}));
  55106. //# sourceMappingURL=babylon.groundMesh.js.map
  55107. var BABYLON;
  55108. (function (BABYLON) {
  55109. /**
  55110. * Creates an instance based on a source mesh.
  55111. */
  55112. var InstancedMesh = /** @class */ (function (_super) {
  55113. __extends(InstancedMesh, _super);
  55114. function InstancedMesh(name, source) {
  55115. var _this = _super.call(this, name, source.getScene()) || this;
  55116. source.instances.push(_this);
  55117. _this._sourceMesh = source;
  55118. _this.position.copyFrom(source.position);
  55119. _this.rotation.copyFrom(source.rotation);
  55120. _this.scaling.copyFrom(source.scaling);
  55121. if (source.rotationQuaternion) {
  55122. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55123. }
  55124. _this.infiniteDistance = source.infiniteDistance;
  55125. _this.setPivotMatrix(source.getPivotMatrix());
  55126. _this.refreshBoundingInfo();
  55127. _this._syncSubMeshes();
  55128. return _this;
  55129. }
  55130. /**
  55131. * Returns the string "InstancedMesh".
  55132. */
  55133. InstancedMesh.prototype.getClassName = function () {
  55134. return "InstancedMesh";
  55135. };
  55136. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55137. // Methods
  55138. get: function () {
  55139. return this._sourceMesh.receiveShadows;
  55140. },
  55141. enumerable: true,
  55142. configurable: true
  55143. });
  55144. Object.defineProperty(InstancedMesh.prototype, "material", {
  55145. get: function () {
  55146. return this._sourceMesh.material;
  55147. },
  55148. enumerable: true,
  55149. configurable: true
  55150. });
  55151. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55152. get: function () {
  55153. return this._sourceMesh.visibility;
  55154. },
  55155. enumerable: true,
  55156. configurable: true
  55157. });
  55158. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55159. get: function () {
  55160. return this._sourceMesh.skeleton;
  55161. },
  55162. enumerable: true,
  55163. configurable: true
  55164. });
  55165. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55166. get: function () {
  55167. return this._sourceMesh.renderingGroupId;
  55168. },
  55169. enumerable: true,
  55170. configurable: true
  55171. });
  55172. /**
  55173. * Returns the total number of vertices (integer).
  55174. */
  55175. InstancedMesh.prototype.getTotalVertices = function () {
  55176. return this._sourceMesh.getTotalVertices();
  55177. };
  55178. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55179. get: function () {
  55180. return this._sourceMesh;
  55181. },
  55182. enumerable: true,
  55183. configurable: true
  55184. });
  55185. /**
  55186. * Is this node ready to be used/rendered
  55187. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55188. * @return {boolean} is it ready
  55189. */
  55190. InstancedMesh.prototype.isReady = function (completeCheck) {
  55191. if (completeCheck === void 0) { completeCheck = false; }
  55192. return this._sourceMesh.isReady(completeCheck, true);
  55193. };
  55194. /**
  55195. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55196. */
  55197. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55198. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55199. };
  55200. /**
  55201. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55202. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55203. * The `data` are either a numeric array either a Float32Array.
  55204. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55205. * 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).
  55206. * Note that a new underlying VertexBuffer object is created each call.
  55207. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55208. *
  55209. * Possible `kind` values :
  55210. * - BABYLON.VertexBuffer.PositionKind
  55211. * - BABYLON.VertexBuffer.UVKind
  55212. * - BABYLON.VertexBuffer.UV2Kind
  55213. * - BABYLON.VertexBuffer.UV3Kind
  55214. * - BABYLON.VertexBuffer.UV4Kind
  55215. * - BABYLON.VertexBuffer.UV5Kind
  55216. * - BABYLON.VertexBuffer.UV6Kind
  55217. * - BABYLON.VertexBuffer.ColorKind
  55218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55222. *
  55223. * Returns the Mesh.
  55224. */
  55225. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55226. if (this.sourceMesh) {
  55227. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55228. }
  55229. return this.sourceMesh;
  55230. };
  55231. /**
  55232. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55233. * If the mesh has no geometry, it is simply returned as it is.
  55234. * The `data` are either a numeric array either a Float32Array.
  55235. * No new underlying VertexBuffer object is created.
  55236. * 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.
  55237. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55238. *
  55239. * Possible `kind` values :
  55240. * - BABYLON.VertexBuffer.PositionKind
  55241. * - BABYLON.VertexBuffer.UVKind
  55242. * - BABYLON.VertexBuffer.UV2Kind
  55243. * - BABYLON.VertexBuffer.UV3Kind
  55244. * - BABYLON.VertexBuffer.UV4Kind
  55245. * - BABYLON.VertexBuffer.UV5Kind
  55246. * - BABYLON.VertexBuffer.UV6Kind
  55247. * - BABYLON.VertexBuffer.ColorKind
  55248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55252. *
  55253. * Returns the Mesh.
  55254. */
  55255. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55256. if (this.sourceMesh) {
  55257. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55258. }
  55259. return this.sourceMesh;
  55260. };
  55261. /**
  55262. * Sets the mesh indices.
  55263. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55264. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55265. * This method creates a new index buffer each call.
  55266. * Returns the Mesh.
  55267. */
  55268. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55269. if (totalVertices === void 0) { totalVertices = null; }
  55270. if (this.sourceMesh) {
  55271. this.sourceMesh.setIndices(indices, totalVertices);
  55272. }
  55273. return this.sourceMesh;
  55274. };
  55275. /**
  55276. * Boolean : True if the mesh owns the requested kind of data.
  55277. */
  55278. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55279. return this._sourceMesh.isVerticesDataPresent(kind);
  55280. };
  55281. /**
  55282. * Returns an array of indices (IndicesArray).
  55283. */
  55284. InstancedMesh.prototype.getIndices = function () {
  55285. return this._sourceMesh.getIndices();
  55286. };
  55287. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55288. get: function () {
  55289. return this._sourceMesh._positions;
  55290. },
  55291. enumerable: true,
  55292. configurable: true
  55293. });
  55294. /**
  55295. * Sets a new updated BoundingInfo to the mesh.
  55296. * Returns the mesh.
  55297. */
  55298. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55299. var meshBB = this._sourceMesh.getBoundingInfo();
  55300. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55301. this._updateBoundingInfo();
  55302. return this;
  55303. };
  55304. InstancedMesh.prototype._preActivate = function () {
  55305. if (this._currentLOD) {
  55306. this._currentLOD._preActivate();
  55307. }
  55308. return this;
  55309. };
  55310. InstancedMesh.prototype._activate = function (renderId) {
  55311. if (this._currentLOD) {
  55312. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55313. }
  55314. return this;
  55315. };
  55316. /**
  55317. * Returns the current associated LOD AbstractMesh.
  55318. */
  55319. InstancedMesh.prototype.getLOD = function (camera) {
  55320. if (!camera) {
  55321. return this;
  55322. }
  55323. var boundingInfo = this.getBoundingInfo();
  55324. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55325. if (this._currentLOD === this.sourceMesh) {
  55326. return this;
  55327. }
  55328. return this._currentLOD;
  55329. };
  55330. InstancedMesh.prototype._syncSubMeshes = function () {
  55331. this.releaseSubMeshes();
  55332. if (this._sourceMesh.subMeshes) {
  55333. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55334. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55335. }
  55336. }
  55337. return this;
  55338. };
  55339. InstancedMesh.prototype._generatePointsArray = function () {
  55340. return this._sourceMesh._generatePointsArray();
  55341. };
  55342. /**
  55343. * Creates a new InstancedMesh from the current mesh.
  55344. * - name (string) : the cloned mesh name
  55345. * - newParent (optional Node) : the optional Node to parent the clone to.
  55346. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55347. *
  55348. * Returns the clone.
  55349. */
  55350. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55351. var result = this._sourceMesh.createInstance(name);
  55352. // Deep copy
  55353. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55354. // Bounding info
  55355. this.refreshBoundingInfo();
  55356. // Parent
  55357. if (newParent) {
  55358. result.parent = newParent;
  55359. }
  55360. if (!doNotCloneChildren) {
  55361. // Children
  55362. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55363. var mesh = this.getScene().meshes[index];
  55364. if (mesh.parent === this) {
  55365. mesh.clone(mesh.name, result);
  55366. }
  55367. }
  55368. }
  55369. result.computeWorldMatrix(true);
  55370. return result;
  55371. };
  55372. /**
  55373. * Disposes the InstancedMesh.
  55374. * Returns nothing.
  55375. */
  55376. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55377. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55378. // Remove from mesh
  55379. var index = this._sourceMesh.instances.indexOf(this);
  55380. this._sourceMesh.instances.splice(index, 1);
  55381. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55382. };
  55383. return InstancedMesh;
  55384. }(BABYLON.AbstractMesh));
  55385. BABYLON.InstancedMesh = InstancedMesh;
  55386. })(BABYLON || (BABYLON = {}));
  55387. //# sourceMappingURL=babylon.instancedMesh.js.map
  55388. var BABYLON;
  55389. (function (BABYLON) {
  55390. var LinesMesh = /** @class */ (function (_super) {
  55391. __extends(LinesMesh, _super);
  55392. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55393. if (scene === void 0) { scene = null; }
  55394. if (parent === void 0) { parent = null; }
  55395. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55396. _this.useVertexColor = useVertexColor;
  55397. _this.useVertexAlpha = useVertexAlpha;
  55398. _this.color = new BABYLON.Color3(1, 1, 1);
  55399. _this.alpha = 1;
  55400. if (source) {
  55401. _this.color = source.color.clone();
  55402. _this.alpha = source.alpha;
  55403. _this.useVertexColor = source.useVertexColor;
  55404. _this.useVertexAlpha = source.useVertexAlpha;
  55405. }
  55406. _this._intersectionThreshold = 0.1;
  55407. var defines = [];
  55408. var options = {
  55409. attributes: [BABYLON.VertexBuffer.PositionKind],
  55410. uniforms: ["world", "viewProjection"],
  55411. needAlphaBlending: true,
  55412. defines: defines
  55413. };
  55414. if (useVertexAlpha === false) {
  55415. options.needAlphaBlending = false;
  55416. }
  55417. if (!useVertexColor) {
  55418. options.uniforms.push("color");
  55419. }
  55420. else {
  55421. options.defines.push("#define VERTEXCOLOR");
  55422. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55423. }
  55424. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55425. return _this;
  55426. }
  55427. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55428. /**
  55429. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55430. * This margin is expressed in world space coordinates, so its value may vary.
  55431. * Default value is 0.1
  55432. * @returns the intersection Threshold value.
  55433. */
  55434. get: function () {
  55435. return this._intersectionThreshold;
  55436. },
  55437. /**
  55438. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55439. * This margin is expressed in world space coordinates, so its value may vary.
  55440. * @param value the new threshold to apply
  55441. */
  55442. set: function (value) {
  55443. if (this._intersectionThreshold === value) {
  55444. return;
  55445. }
  55446. this._intersectionThreshold = value;
  55447. if (this.geometry) {
  55448. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55449. }
  55450. },
  55451. enumerable: true,
  55452. configurable: true
  55453. });
  55454. /**
  55455. * Returns the string "LineMesh"
  55456. */
  55457. LinesMesh.prototype.getClassName = function () {
  55458. return "LinesMesh";
  55459. };
  55460. Object.defineProperty(LinesMesh.prototype, "material", {
  55461. get: function () {
  55462. return this._colorShader;
  55463. },
  55464. set: function (value) {
  55465. // Do nothing
  55466. },
  55467. enumerable: true,
  55468. configurable: true
  55469. });
  55470. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55471. get: function () {
  55472. return false;
  55473. },
  55474. enumerable: true,
  55475. configurable: true
  55476. });
  55477. LinesMesh.prototype.createInstance = function (name) {
  55478. throw new Error("LinesMeshes do not support createInstance.");
  55479. };
  55480. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55481. if (!this._geometry) {
  55482. return this;
  55483. }
  55484. // VBOs
  55485. this._geometry._bind(this._colorShader.getEffect());
  55486. // Color
  55487. if (!this.useVertexColor) {
  55488. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55489. }
  55490. return this;
  55491. };
  55492. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55493. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55494. return this;
  55495. }
  55496. var engine = this.getScene().getEngine();
  55497. // Draw order
  55498. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55499. return this;
  55500. };
  55501. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55502. this._colorShader.dispose();
  55503. _super.prototype.dispose.call(this, doNotRecurse);
  55504. };
  55505. /**
  55506. * Returns a new LineMesh object cloned from the current one.
  55507. */
  55508. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55509. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55510. };
  55511. return LinesMesh;
  55512. }(BABYLON.Mesh));
  55513. BABYLON.LinesMesh = LinesMesh;
  55514. })(BABYLON || (BABYLON = {}));
  55515. //# sourceMappingURL=babylon.linesMesh.js.map
  55516. var BABYLON;
  55517. (function (BABYLON) {
  55518. var MeshBuilder = /** @class */ (function () {
  55519. function MeshBuilder() {
  55520. }
  55521. MeshBuilder.updateSideOrientation = function (orientation) {
  55522. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55523. return BABYLON.Mesh.DOUBLESIDE;
  55524. }
  55525. if (orientation === undefined || orientation === null) {
  55526. return BABYLON.Mesh.FRONTSIDE;
  55527. }
  55528. return orientation;
  55529. };
  55530. /**
  55531. * Creates a box mesh.
  55532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55533. * The parameter `size` sets the size (float) of each box side (default 1).
  55534. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55535. * 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).
  55536. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55538. * 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).
  55539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55541. */
  55542. MeshBuilder.CreateBox = function (name, options, scene) {
  55543. if (scene === void 0) { scene = null; }
  55544. var box = new BABYLON.Mesh(name, scene);
  55545. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55546. box._originalBuilderSideOrientation = options.sideOrientation;
  55547. var vertexData = BABYLON.VertexData.CreateBox(options);
  55548. vertexData.applyToMesh(box, options.updatable);
  55549. return box;
  55550. };
  55551. /**
  55552. * Creates a sphere mesh.
  55553. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55554. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55555. * 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`).
  55556. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55557. * 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
  55558. * 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).
  55559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55560. * 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).
  55561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55563. */
  55564. MeshBuilder.CreateSphere = function (name, options, scene) {
  55565. var sphere = new BABYLON.Mesh(name, scene);
  55566. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55567. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55568. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55569. vertexData.applyToMesh(sphere, options.updatable);
  55570. return sphere;
  55571. };
  55572. /**
  55573. * Creates a plane polygonal mesh. By default, this is a disc.
  55574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55575. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55576. * 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.
  55577. * 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
  55578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55579. * 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).
  55580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55582. */
  55583. MeshBuilder.CreateDisc = function (name, options, scene) {
  55584. if (scene === void 0) { scene = null; }
  55585. var disc = new BABYLON.Mesh(name, scene);
  55586. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55587. disc._originalBuilderSideOrientation = options.sideOrientation;
  55588. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55589. vertexData.applyToMesh(disc, options.updatable);
  55590. return disc;
  55591. };
  55592. /**
  55593. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55595. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55596. * 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`).
  55597. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55598. * 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.
  55599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55600. * 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).
  55601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55603. */
  55604. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55605. var sphere = new BABYLON.Mesh(name, scene);
  55606. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55607. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55608. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55609. vertexData.applyToMesh(sphere, options.updatable);
  55610. return sphere;
  55611. };
  55612. ;
  55613. /**
  55614. * Creates a ribbon mesh.
  55615. * 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.
  55616. *
  55617. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55618. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55619. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55620. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55621. * 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.
  55622. * 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.
  55623. * 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
  55624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55625. * 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).
  55626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55627. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55628. * 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.
  55629. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55630. * 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
  55631. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55632. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55634. */
  55635. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55636. if (scene === void 0) { scene = null; }
  55637. var pathArray = options.pathArray;
  55638. var closeArray = options.closeArray;
  55639. var closePath = options.closePath;
  55640. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55641. var instance = options.instance;
  55642. var updatable = options.updatable;
  55643. if (instance) {
  55644. // positionFunction : ribbon case
  55645. // only pathArray and sideOrientation parameters are taken into account for positions update
  55646. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55647. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55648. var positionFunction = function (positions) {
  55649. var minlg = pathArray[0].length;
  55650. var i = 0;
  55651. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55652. for (var si = 1; si <= ns; si++) {
  55653. for (var p = 0; p < pathArray.length; p++) {
  55654. var path = pathArray[p];
  55655. var l = path.length;
  55656. minlg = (minlg < l) ? minlg : l;
  55657. var j = 0;
  55658. while (j < minlg) {
  55659. positions[i] = path[j].x;
  55660. positions[i + 1] = path[j].y;
  55661. positions[i + 2] = path[j].z;
  55662. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55663. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55664. }
  55665. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55666. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55667. }
  55668. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55669. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55670. }
  55671. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55672. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55673. }
  55674. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55675. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55676. }
  55677. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55678. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55679. }
  55680. j++;
  55681. i += 3;
  55682. }
  55683. if (instance._closePath) {
  55684. positions[i] = path[0].x;
  55685. positions[i + 1] = path[0].y;
  55686. positions[i + 2] = path[0].z;
  55687. i += 3;
  55688. }
  55689. }
  55690. }
  55691. };
  55692. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55693. positionFunction(positions);
  55694. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55695. instance._boundingInfo.update(instance._worldMatrix);
  55696. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55697. if (options.colors) {
  55698. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55699. for (var c = 0; c < options.colors.length; c++) {
  55700. colors[c * 4] = options.colors[c].r;
  55701. colors[c * 4 + 1] = options.colors[c].g;
  55702. colors[c * 4 + 2] = options.colors[c].b;
  55703. colors[c * 4 + 3] = options.colors[c].a;
  55704. }
  55705. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55706. }
  55707. if (options.uvs) {
  55708. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55709. for (var i = 0; i < options.uvs.length; i++) {
  55710. uvs[i * 2] = options.uvs[i].x;
  55711. uvs[i * 2 + 1] = options.uvs[i].y;
  55712. }
  55713. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55714. }
  55715. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55716. var indices = instance.getIndices();
  55717. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55718. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55719. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55720. if (instance._closePath) {
  55721. var indexFirst = 0;
  55722. var indexLast = 0;
  55723. for (var p = 0; p < pathArray.length; p++) {
  55724. indexFirst = instance._idx[p] * 3;
  55725. if (p + 1 < pathArray.length) {
  55726. indexLast = (instance._idx[p + 1] - 1) * 3;
  55727. }
  55728. else {
  55729. indexLast = normals.length - 3;
  55730. }
  55731. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55732. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55733. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55734. normals[indexLast] = normals[indexFirst];
  55735. normals[indexLast + 1] = normals[indexFirst + 1];
  55736. normals[indexLast + 2] = normals[indexFirst + 2];
  55737. }
  55738. }
  55739. if (!(instance.areNormalsFrozen)) {
  55740. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55741. }
  55742. }
  55743. return instance;
  55744. }
  55745. else {
  55746. var ribbon = new BABYLON.Mesh(name, scene);
  55747. ribbon._originalBuilderSideOrientation = sideOrientation;
  55748. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55749. if (closePath) {
  55750. ribbon._idx = vertexData._idx;
  55751. }
  55752. ribbon._closePath = closePath;
  55753. ribbon._closeArray = closeArray;
  55754. vertexData.applyToMesh(ribbon, updatable);
  55755. return ribbon;
  55756. }
  55757. };
  55758. /**
  55759. * Creates a cylinder or a cone mesh.
  55760. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55761. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55762. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55763. * 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.
  55764. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55765. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55766. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55767. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55768. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55769. * 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).
  55770. * 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
  55771. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55772. * 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
  55773. * 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.
  55774. * If `enclose` is false, a ring surface is one element.
  55775. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55776. * 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
  55777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55778. * 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).
  55779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55781. */
  55782. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55783. var cylinder = new BABYLON.Mesh(name, scene);
  55784. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55785. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55786. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55787. vertexData.applyToMesh(cylinder, options.updatable);
  55788. return cylinder;
  55789. };
  55790. /**
  55791. * Creates a torus mesh.
  55792. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55793. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55794. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55795. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55797. * 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).
  55798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55800. */
  55801. MeshBuilder.CreateTorus = function (name, options, scene) {
  55802. var torus = new BABYLON.Mesh(name, scene);
  55803. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55804. torus._originalBuilderSideOrientation = options.sideOrientation;
  55805. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55806. vertexData.applyToMesh(torus, options.updatable);
  55807. return torus;
  55808. };
  55809. /**
  55810. * Creates a torus knot mesh.
  55811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55812. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55813. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55814. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55815. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55817. * 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).
  55818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55820. */
  55821. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55822. var torusKnot = new BABYLON.Mesh(name, scene);
  55823. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55824. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55825. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55826. vertexData.applyToMesh(torusKnot, options.updatable);
  55827. return torusKnot;
  55828. };
  55829. /**
  55830. * Creates a line system mesh.
  55831. * A line system is a pool of many lines gathered in a single mesh.
  55832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55833. * 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.
  55834. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55835. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55836. * 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
  55837. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55838. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55839. * 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
  55840. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55842. */
  55843. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55844. var instance = options.instance;
  55845. var lines = options.lines;
  55846. var colors = options.colors;
  55847. if (instance) {
  55848. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55849. var vertexColor;
  55850. var lineColors;
  55851. if (colors) {
  55852. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55853. }
  55854. var i = 0;
  55855. var c = 0;
  55856. for (var l = 0; l < lines.length; l++) {
  55857. var points = lines[l];
  55858. for (var p = 0; p < points.length; p++) {
  55859. positions[i] = points[p].x;
  55860. positions[i + 1] = points[p].y;
  55861. positions[i + 2] = points[p].z;
  55862. if (colors && vertexColor) {
  55863. lineColors = colors[l];
  55864. vertexColor[c] = lineColors[p].r;
  55865. vertexColor[c + 1] = lineColors[p].g;
  55866. vertexColor[c + 2] = lineColors[p].b;
  55867. vertexColor[c + 3] = lineColors[p].a;
  55868. c += 4;
  55869. }
  55870. i += 3;
  55871. }
  55872. }
  55873. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55874. if (colors && vertexColor) {
  55875. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55876. }
  55877. return instance;
  55878. }
  55879. // line system creation
  55880. var useVertexColor = (colors) ? true : false;
  55881. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55882. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55883. vertexData.applyToMesh(lineSystem, options.updatable);
  55884. return lineSystem;
  55885. };
  55886. /**
  55887. * Creates a line mesh.
  55888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55889. * 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.
  55890. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55891. * The parameter `points` is an array successive Vector3.
  55892. * 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
  55893. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55894. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55895. * When updating an instance, remember that only point positions can change, not the number of points.
  55896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55897. */
  55898. MeshBuilder.CreateLines = function (name, options, scene) {
  55899. if (scene === void 0) { scene = null; }
  55900. var colors = (options.colors) ? [options.colors] : null;
  55901. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55902. return lines;
  55903. };
  55904. /**
  55905. * Creates a dashed line mesh.
  55906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55907. * 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.
  55908. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55909. * The parameter `points` is an array successive Vector3.
  55910. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55911. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55912. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55913. * 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
  55914. * When updating an instance, remember that only point positions can change, not the number of points.
  55915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55916. */
  55917. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55918. if (scene === void 0) { scene = null; }
  55919. var points = options.points;
  55920. var instance = options.instance;
  55921. var gapSize = options.gapSize || 1;
  55922. var dashSize = options.dashSize || 3;
  55923. if (instance) {
  55924. var positionFunction = function (positions) {
  55925. var curvect = BABYLON.Vector3.Zero();
  55926. var nbSeg = positions.length / 6;
  55927. var lg = 0;
  55928. var nb = 0;
  55929. var shft = 0;
  55930. var dashshft = 0;
  55931. var curshft = 0;
  55932. var p = 0;
  55933. var i = 0;
  55934. var j = 0;
  55935. for (i = 0; i < points.length - 1; i++) {
  55936. points[i + 1].subtractToRef(points[i], curvect);
  55937. lg += curvect.length();
  55938. }
  55939. shft = lg / nbSeg;
  55940. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55941. for (i = 0; i < points.length - 1; i++) {
  55942. points[i + 1].subtractToRef(points[i], curvect);
  55943. nb = Math.floor(curvect.length() / shft);
  55944. curvect.normalize();
  55945. j = 0;
  55946. while (j < nb && p < positions.length) {
  55947. curshft = shft * j;
  55948. positions[p] = points[i].x + curshft * curvect.x;
  55949. positions[p + 1] = points[i].y + curshft * curvect.y;
  55950. positions[p + 2] = points[i].z + curshft * curvect.z;
  55951. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55952. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55953. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55954. p += 6;
  55955. j++;
  55956. }
  55957. }
  55958. while (p < positions.length) {
  55959. positions[p] = points[i].x;
  55960. positions[p + 1] = points[i].y;
  55961. positions[p + 2] = points[i].z;
  55962. p += 3;
  55963. }
  55964. };
  55965. instance.updateMeshPositions(positionFunction, false);
  55966. return instance;
  55967. }
  55968. // dashed lines creation
  55969. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55970. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55971. vertexData.applyToMesh(dashedLines, options.updatable);
  55972. dashedLines.dashSize = dashSize;
  55973. dashedLines.gapSize = gapSize;
  55974. return dashedLines;
  55975. };
  55976. /**
  55977. * Creates an extruded shape mesh.
  55978. * 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.
  55979. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55980. *
  55981. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55982. * 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
  55983. * extruded along the Z axis.
  55984. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55985. * 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.
  55986. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55987. * 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
  55988. * 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
  55989. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55991. * 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).
  55992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55993. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55995. */
  55996. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55997. if (scene === void 0) { scene = null; }
  55998. var path = options.path;
  55999. var shape = options.shape;
  56000. var scale = options.scale || 1;
  56001. var rotation = options.rotation || 0;
  56002. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56003. var updatable = options.updatable;
  56004. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56005. var instance = options.instance || null;
  56006. var invertUV = options.invertUV || false;
  56007. 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);
  56008. };
  56009. /**
  56010. * Creates an custom extruded shape mesh.
  56011. * 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.
  56012. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56013. *
  56014. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56015. * 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
  56016. * extruded along the Z axis.
  56017. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56018. * 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
  56019. * and the distance of this point from the begining of the path :
  56020. * ```javascript
  56021. * var rotationFunction = function(i, distance) {
  56022. * // do things
  56023. * return rotationValue; }
  56024. * ```
  56025. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56026. * 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
  56027. * and the distance of this point from the begining of the path :
  56028. * ```javascript
  56029. * var scaleFunction = function(i, distance) {
  56030. * // do things
  56031. * return scaleValue;}
  56032. * ```
  56033. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56034. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56035. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56036. * 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
  56037. * 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
  56038. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56040. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56041. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56042. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56044. */
  56045. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56046. var path = options.path;
  56047. var shape = options.shape;
  56048. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56049. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56050. var ribbonCloseArray = options.ribbonCloseArray || false;
  56051. var ribbonClosePath = options.ribbonClosePath || false;
  56052. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56053. var updatable = options.updatable;
  56054. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56055. var instance = options.instance;
  56056. var invertUV = options.invertUV || false;
  56057. 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);
  56058. };
  56059. /**
  56060. * Creates lathe mesh.
  56061. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56062. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56063. *
  56064. * 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
  56065. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56066. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56067. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56068. * 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.
  56069. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56070. * 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
  56071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56072. * 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).
  56073. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56074. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56076. */
  56077. MeshBuilder.CreateLathe = function (name, options, scene) {
  56078. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56079. var closed = (options.closed === undefined) ? true : options.closed;
  56080. var shape = options.shape;
  56081. var radius = options.radius || 1;
  56082. var tessellation = options.tessellation || 64;
  56083. var updatable = options.updatable;
  56084. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56085. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56086. var pi2 = Math.PI * 2;
  56087. var paths = new Array();
  56088. var invertUV = options.invertUV || false;
  56089. var i = 0;
  56090. var p = 0;
  56091. var step = pi2 / tessellation * arc;
  56092. var rotated;
  56093. var path = new Array();
  56094. ;
  56095. for (i = 0; i <= tessellation; i++) {
  56096. var path = [];
  56097. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56098. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56099. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56100. }
  56101. for (p = 0; p < shape.length; p++) {
  56102. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56103. path.push(rotated);
  56104. }
  56105. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56106. 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));
  56107. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56108. }
  56109. paths.push(path);
  56110. }
  56111. // lathe ribbon
  56112. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56113. return lathe;
  56114. };
  56115. /**
  56116. * Creates a plane mesh.
  56117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56118. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56119. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56120. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56121. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56122. * 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).
  56123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56125. */
  56126. MeshBuilder.CreatePlane = function (name, options, scene) {
  56127. var plane = new BABYLON.Mesh(name, scene);
  56128. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56129. plane._originalBuilderSideOrientation = options.sideOrientation;
  56130. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56131. vertexData.applyToMesh(plane, options.updatable);
  56132. if (options.sourcePlane) {
  56133. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56134. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56135. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56136. plane.rotate(vectorProduct, product);
  56137. }
  56138. return plane;
  56139. };
  56140. /**
  56141. * Creates a ground mesh.
  56142. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56143. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56144. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56146. */
  56147. MeshBuilder.CreateGround = function (name, options, scene) {
  56148. var ground = new BABYLON.GroundMesh(name, scene);
  56149. ground._setReady(false);
  56150. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56151. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56152. ground._width = options.width || 1;
  56153. ground._height = options.height || 1;
  56154. ground._maxX = ground._width / 2;
  56155. ground._maxZ = ground._height / 2;
  56156. ground._minX = -ground._maxX;
  56157. ground._minZ = -ground._maxZ;
  56158. var vertexData = BABYLON.VertexData.CreateGround(options);
  56159. vertexData.applyToMesh(ground, options.updatable);
  56160. ground._setReady(true);
  56161. return ground;
  56162. };
  56163. /**
  56164. * Creates a tiled ground mesh.
  56165. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56166. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56167. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56168. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56169. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56170. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56171. * numbers of subdivisions on the ground width and height of each tile.
  56172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56173. */
  56174. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56175. var tiledGround = new BABYLON.Mesh(name, scene);
  56176. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56177. vertexData.applyToMesh(tiledGround, options.updatable);
  56178. return tiledGround;
  56179. };
  56180. /**
  56181. * Creates a ground mesh from a height map.
  56182. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56184. * The parameter `url` sets the URL of the height map image resource.
  56185. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56186. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56187. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56188. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56189. * 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.
  56190. * 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).
  56191. * This function is passed the newly built mesh :
  56192. * ```javascript
  56193. * function(mesh) { // do things
  56194. * return; }
  56195. * ```
  56196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56197. */
  56198. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56199. var width = options.width || 10.0;
  56200. var height = options.height || 10.0;
  56201. var subdivisions = options.subdivisions || 1 | 0;
  56202. var minHeight = options.minHeight || 0.0;
  56203. var maxHeight = options.maxHeight || 1.0;
  56204. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56205. var updatable = options.updatable;
  56206. var onReady = options.onReady;
  56207. var ground = new BABYLON.GroundMesh(name, scene);
  56208. ground._subdivisionsX = subdivisions;
  56209. ground._subdivisionsY = subdivisions;
  56210. ground._width = width;
  56211. ground._height = height;
  56212. ground._maxX = ground._width / 2.0;
  56213. ground._maxZ = ground._height / 2.0;
  56214. ground._minX = -ground._maxX;
  56215. ground._minZ = -ground._maxZ;
  56216. ground._setReady(false);
  56217. var onload = function (img) {
  56218. // Getting height map data
  56219. var canvas = document.createElement("canvas");
  56220. var context = canvas.getContext("2d");
  56221. if (!context) {
  56222. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56223. }
  56224. if (scene.isDisposed) {
  56225. return;
  56226. }
  56227. var bufferWidth = img.width;
  56228. var bufferHeight = img.height;
  56229. canvas.width = bufferWidth;
  56230. canvas.height = bufferHeight;
  56231. context.drawImage(img, 0, 0);
  56232. // Create VertexData from map data
  56233. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56234. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56235. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56236. width: width, height: height,
  56237. subdivisions: subdivisions,
  56238. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56239. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56240. });
  56241. vertexData.applyToMesh(ground, updatable);
  56242. ground._setReady(true);
  56243. //execute ready callback, if set
  56244. if (onReady) {
  56245. onReady(ground);
  56246. }
  56247. };
  56248. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56249. return ground;
  56250. };
  56251. /**
  56252. * Creates a polygon mesh.
  56253. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56254. * 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.
  56255. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56257. * 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).
  56258. * Remember you can only change the shape positions, not their number when updating a polygon.
  56259. */
  56260. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56261. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56262. var shape = options.shape;
  56263. var holes = options.holes || [];
  56264. var depth = options.depth || 0;
  56265. var contours = [];
  56266. var hole = [];
  56267. for (var i = 0; i < shape.length; i++) {
  56268. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56269. }
  56270. var epsilon = 0.00000001;
  56271. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56272. contours.pop();
  56273. }
  56274. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56275. for (var hNb = 0; hNb < holes.length; hNb++) {
  56276. hole = [];
  56277. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56278. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56279. }
  56280. polygonTriangulation.addHole(hole);
  56281. }
  56282. var polygon = polygonTriangulation.build(options.updatable, depth);
  56283. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56284. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56285. vertexData.applyToMesh(polygon, options.updatable);
  56286. return polygon;
  56287. };
  56288. ;
  56289. /**
  56290. * Creates an extruded polygon mesh, with depth in the Y direction.
  56291. * 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).
  56292. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56293. */
  56294. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56295. return MeshBuilder.CreatePolygon(name, options, scene);
  56296. };
  56297. ;
  56298. /**
  56299. * Creates a tube mesh.
  56300. * 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.
  56301. *
  56302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56303. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56304. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56305. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56306. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56307. * 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.
  56308. * It must return a radius value (positive float) :
  56309. * ```javascript
  56310. * var radiusFunction = function(i, distance) {
  56311. * // do things
  56312. * return radius; }
  56313. * ```
  56314. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56315. * 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
  56316. * 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
  56317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56318. * 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).
  56319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56320. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56322. */
  56323. MeshBuilder.CreateTube = function (name, options, scene) {
  56324. var path = options.path;
  56325. var instance = options.instance;
  56326. var radius = 1.0;
  56327. if (instance) {
  56328. radius = instance.radius;
  56329. }
  56330. if (options.radius !== undefined) {
  56331. radius = options.radius;
  56332. }
  56333. ;
  56334. var tessellation = options.tessellation || 64 | 0;
  56335. var radiusFunction = options.radiusFunction || null;
  56336. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56337. var invertUV = options.invertUV || false;
  56338. var updatable = options.updatable;
  56339. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56340. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56341. // tube geometry
  56342. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56343. var tangents = path3D.getTangents();
  56344. var normals = path3D.getNormals();
  56345. var distances = path3D.getDistances();
  56346. var pi2 = Math.PI * 2;
  56347. var step = pi2 / tessellation * arc;
  56348. var returnRadius = function () { return radius; };
  56349. var radiusFunctionFinal = radiusFunction || returnRadius;
  56350. var circlePath;
  56351. var rad;
  56352. var normal;
  56353. var rotated;
  56354. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56355. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56356. for (var i = 0; i < path.length; i++) {
  56357. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56358. circlePath = Array(); // current circle array
  56359. normal = normals[i]; // current normal
  56360. for (var t = 0; t < tessellation; t++) {
  56361. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56362. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56363. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56364. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56365. circlePath[t] = rotated;
  56366. }
  56367. circlePaths[index] = circlePath;
  56368. index++;
  56369. }
  56370. // cap
  56371. var capPath = function (nbPoints, pathIndex) {
  56372. var pointCap = Array();
  56373. for (var i = 0; i < nbPoints; i++) {
  56374. pointCap.push(path[pathIndex]);
  56375. }
  56376. return pointCap;
  56377. };
  56378. switch (cap) {
  56379. case BABYLON.Mesh.NO_CAP:
  56380. break;
  56381. case BABYLON.Mesh.CAP_START:
  56382. circlePaths[0] = capPath(tessellation, 0);
  56383. circlePaths[1] = circlePaths[2].slice(0);
  56384. break;
  56385. case BABYLON.Mesh.CAP_END:
  56386. circlePaths[index] = circlePaths[index - 1].slice(0);
  56387. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56388. break;
  56389. case BABYLON.Mesh.CAP_ALL:
  56390. circlePaths[0] = capPath(tessellation, 0);
  56391. circlePaths[1] = circlePaths[2].slice(0);
  56392. circlePaths[index] = circlePaths[index - 1].slice(0);
  56393. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56394. break;
  56395. default:
  56396. break;
  56397. }
  56398. return circlePaths;
  56399. };
  56400. var path3D;
  56401. var pathArray;
  56402. if (instance) {
  56403. var arc = options.arc || instance.arc;
  56404. path3D = (instance.path3D).update(path);
  56405. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56406. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56407. instance.path3D = path3D;
  56408. instance.pathArray = pathArray;
  56409. instance.arc = arc;
  56410. instance.radius = radius;
  56411. return instance;
  56412. }
  56413. // tube creation
  56414. path3D = new BABYLON.Path3D(path);
  56415. var newPathArray = new Array();
  56416. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56417. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56418. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56419. tube.pathArray = pathArray;
  56420. tube.path3D = path3D;
  56421. tube.tessellation = tessellation;
  56422. tube.cap = cap;
  56423. tube.arc = options.arc;
  56424. tube.radius = radius;
  56425. return tube;
  56426. };
  56427. /**
  56428. * Creates a polyhedron mesh.
  56429. *
  56430. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56431. * 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
  56432. * to choose the wanted type.
  56433. * The parameter `size` (positive float, default 1) sets the polygon size.
  56434. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56435. * 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`.
  56436. * 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
  56437. * 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)`).
  56438. * 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
  56439. * 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.
  56440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56441. * 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).
  56442. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56444. */
  56445. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56446. var polyhedron = new BABYLON.Mesh(name, scene);
  56447. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56448. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56449. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56450. vertexData.applyToMesh(polyhedron, options.updatable);
  56451. return polyhedron;
  56452. };
  56453. /**
  56454. * Creates a decal mesh.
  56455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56456. * 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.
  56457. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56458. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56459. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56460. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56461. */
  56462. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56463. var indices = sourceMesh.getIndices();
  56464. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56465. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56466. var position = options.position || BABYLON.Vector3.Zero();
  56467. var normal = options.normal || BABYLON.Vector3.Up();
  56468. var size = options.size || BABYLON.Vector3.One();
  56469. var angle = options.angle || 0;
  56470. // Getting correct rotation
  56471. if (!normal) {
  56472. var target = new BABYLON.Vector3(0, 0, 1);
  56473. var camera = sourceMesh.getScene().activeCamera;
  56474. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56475. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56476. }
  56477. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56478. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56479. var pitch = Math.atan2(normal.y, len);
  56480. // Matrix
  56481. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56482. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56483. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56484. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56485. var vertexData = new BABYLON.VertexData();
  56486. vertexData.indices = [];
  56487. vertexData.positions = [];
  56488. vertexData.normals = [];
  56489. vertexData.uvs = [];
  56490. var currentVertexDataIndex = 0;
  56491. var extractDecalVector3 = function (indexId) {
  56492. var result = new BABYLON.PositionNormalVertex();
  56493. if (!indices || !positions || !normals) {
  56494. return result;
  56495. }
  56496. var vertexId = indices[indexId];
  56497. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56498. // Send vector to decal local world
  56499. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56500. // Get normal
  56501. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56502. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56503. return result;
  56504. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56505. var clip = function (vertices, axis) {
  56506. if (vertices.length === 0) {
  56507. return vertices;
  56508. }
  56509. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56510. var clipVertices = function (v0, v1) {
  56511. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56512. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56513. };
  56514. var result = new Array();
  56515. for (var index = 0; index < vertices.length; index += 3) {
  56516. var v1Out;
  56517. var v2Out;
  56518. var v3Out;
  56519. var total = 0;
  56520. var nV1 = null;
  56521. var nV2 = null;
  56522. var nV3 = null;
  56523. var nV4 = null;
  56524. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56525. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56526. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56527. v1Out = d1 > 0;
  56528. v2Out = d2 > 0;
  56529. v3Out = d3 > 0;
  56530. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56531. switch (total) {
  56532. case 0:
  56533. result.push(vertices[index]);
  56534. result.push(vertices[index + 1]);
  56535. result.push(vertices[index + 2]);
  56536. break;
  56537. case 1:
  56538. if (v1Out) {
  56539. nV1 = vertices[index + 1];
  56540. nV2 = vertices[index + 2];
  56541. nV3 = clipVertices(vertices[index], nV1);
  56542. nV4 = clipVertices(vertices[index], nV2);
  56543. }
  56544. if (v2Out) {
  56545. nV1 = vertices[index];
  56546. nV2 = vertices[index + 2];
  56547. nV3 = clipVertices(vertices[index + 1], nV1);
  56548. nV4 = clipVertices(vertices[index + 1], nV2);
  56549. result.push(nV3);
  56550. result.push(nV2.clone());
  56551. result.push(nV1.clone());
  56552. result.push(nV2.clone());
  56553. result.push(nV3.clone());
  56554. result.push(nV4);
  56555. break;
  56556. }
  56557. if (v3Out) {
  56558. nV1 = vertices[index];
  56559. nV2 = vertices[index + 1];
  56560. nV3 = clipVertices(vertices[index + 2], nV1);
  56561. nV4 = clipVertices(vertices[index + 2], nV2);
  56562. }
  56563. if (nV1 && nV2 && nV3 && nV4) {
  56564. result.push(nV1.clone());
  56565. result.push(nV2.clone());
  56566. result.push(nV3);
  56567. result.push(nV4);
  56568. result.push(nV3.clone());
  56569. result.push(nV2.clone());
  56570. }
  56571. break;
  56572. case 2:
  56573. if (!v1Out) {
  56574. nV1 = vertices[index].clone();
  56575. nV2 = clipVertices(nV1, vertices[index + 1]);
  56576. nV3 = clipVertices(nV1, vertices[index + 2]);
  56577. result.push(nV1);
  56578. result.push(nV2);
  56579. result.push(nV3);
  56580. }
  56581. if (!v2Out) {
  56582. nV1 = vertices[index + 1].clone();
  56583. nV2 = clipVertices(nV1, vertices[index + 2]);
  56584. nV3 = clipVertices(nV1, vertices[index]);
  56585. result.push(nV1);
  56586. result.push(nV2);
  56587. result.push(nV3);
  56588. }
  56589. if (!v3Out) {
  56590. nV1 = vertices[index + 2].clone();
  56591. nV2 = clipVertices(nV1, vertices[index]);
  56592. nV3 = clipVertices(nV1, vertices[index + 1]);
  56593. result.push(nV1);
  56594. result.push(nV2);
  56595. result.push(nV3);
  56596. }
  56597. break;
  56598. case 3:
  56599. break;
  56600. }
  56601. }
  56602. return result;
  56603. };
  56604. for (var index = 0; index < indices.length; index += 3) {
  56605. var faceVertices = new Array();
  56606. faceVertices.push(extractDecalVector3(index));
  56607. faceVertices.push(extractDecalVector3(index + 1));
  56608. faceVertices.push(extractDecalVector3(index + 2));
  56609. // Clip
  56610. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56611. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56612. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56616. if (faceVertices.length === 0) {
  56617. continue;
  56618. }
  56619. // Add UVs and get back to world
  56620. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56621. var vertex = faceVertices[vIndex];
  56622. //TODO check for Int32Array | Uint32Array | Uint16Array
  56623. vertexData.indices.push(currentVertexDataIndex);
  56624. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56625. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56626. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56627. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56628. currentVertexDataIndex++;
  56629. }
  56630. }
  56631. // Return mesh
  56632. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56633. vertexData.applyToMesh(decal);
  56634. decal.position = position.clone();
  56635. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56636. return decal;
  56637. };
  56638. // Privates
  56639. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56640. // extrusion geometry
  56641. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56642. var tangents = path3D.getTangents();
  56643. var normals = path3D.getNormals();
  56644. var binormals = path3D.getBinormals();
  56645. var distances = path3D.getDistances();
  56646. var angle = 0;
  56647. var returnScale = function () { return scale !== null ? scale : 1; };
  56648. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56649. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56650. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56651. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56652. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56653. for (var i = 0; i < curve.length; i++) {
  56654. var shapePath = new Array();
  56655. var angleStep = rotate(i, distances[i]);
  56656. var scaleRatio = scl(i, distances[i]);
  56657. for (var p = 0; p < shape.length; p++) {
  56658. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56659. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56660. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56661. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56662. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56663. shapePath[p] = rotated;
  56664. }
  56665. shapePaths[index] = shapePath;
  56666. angle += angleStep;
  56667. index++;
  56668. }
  56669. // cap
  56670. var capPath = function (shapePath) {
  56671. var pointCap = Array();
  56672. var barycenter = BABYLON.Vector3.Zero();
  56673. var i;
  56674. for (i = 0; i < shapePath.length; i++) {
  56675. barycenter.addInPlace(shapePath[i]);
  56676. }
  56677. barycenter.scaleInPlace(1.0 / shapePath.length);
  56678. for (i = 0; i < shapePath.length; i++) {
  56679. pointCap.push(barycenter);
  56680. }
  56681. return pointCap;
  56682. };
  56683. switch (cap) {
  56684. case BABYLON.Mesh.NO_CAP:
  56685. break;
  56686. case BABYLON.Mesh.CAP_START:
  56687. shapePaths[0] = capPath(shapePaths[2]);
  56688. shapePaths[1] = shapePaths[2];
  56689. break;
  56690. case BABYLON.Mesh.CAP_END:
  56691. shapePaths[index] = shapePaths[index - 1];
  56692. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56693. break;
  56694. case BABYLON.Mesh.CAP_ALL:
  56695. shapePaths[0] = capPath(shapePaths[2]);
  56696. shapePaths[1] = shapePaths[2];
  56697. shapePaths[index] = shapePaths[index - 1];
  56698. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56699. break;
  56700. default:
  56701. break;
  56702. }
  56703. return shapePaths;
  56704. };
  56705. var path3D;
  56706. var pathArray;
  56707. if (instance) {
  56708. path3D = (instance.path3D).update(curve);
  56709. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56710. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56711. return instance;
  56712. }
  56713. // extruded shape creation
  56714. path3D = new BABYLON.Path3D(curve);
  56715. var newShapePaths = new Array();
  56716. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56717. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56718. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56719. extrudedGeneric.pathArray = pathArray;
  56720. extrudedGeneric.path3D = path3D;
  56721. extrudedGeneric.cap = cap;
  56722. return extrudedGeneric;
  56723. };
  56724. return MeshBuilder;
  56725. }());
  56726. BABYLON.MeshBuilder = MeshBuilder;
  56727. })(BABYLON || (BABYLON = {}));
  56728. //# sourceMappingURL=babylon.meshBuilder.js.map
  56729. var BABYLON;
  56730. (function (BABYLON) {
  56731. /**
  56732. * Draco compression (https://google.github.io/draco/)
  56733. */
  56734. var DracoCompression = /** @class */ (function () {
  56735. /**
  56736. * Constructor
  56737. * @param numWorkers The number of workers for async operations
  56738. */
  56739. function DracoCompression(numWorkers) {
  56740. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56741. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56742. if (!workerBlobUrl || !Worker) {
  56743. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56744. return;
  56745. }
  56746. var workers = new Array(numWorkers);
  56747. for (var i = 0; i < workers.length; i++) {
  56748. var worker = new Worker(workerBlobUrl);
  56749. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56750. workers[i] = worker;
  56751. }
  56752. this._workerPool = new BABYLON.WorkerPool(workers);
  56753. }
  56754. /**
  56755. * Stop all async operations and release resources.
  56756. */
  56757. DracoCompression.prototype.dispose = function () {
  56758. this._workerPool.dispose();
  56759. delete this._workerPool;
  56760. };
  56761. /**
  56762. * Decode Draco compressed mesh data to vertex data.
  56763. * @param data The array buffer view for the Draco compression data
  56764. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56765. * @returns A promise that resolves with the decoded vertex data
  56766. */
  56767. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56768. var _this = this;
  56769. return new Promise(function (resolve, reject) {
  56770. _this._workerPool.push(function (worker, onComplete) {
  56771. var vertexData = new BABYLON.VertexData();
  56772. var onError = function (error) {
  56773. worker.removeEventListener("error", onError);
  56774. worker.removeEventListener("message", onMessage);
  56775. reject(error);
  56776. onComplete();
  56777. };
  56778. var onMessage = function (message) {
  56779. if (message.data === "done") {
  56780. worker.removeEventListener("error", onError);
  56781. worker.removeEventListener("message", onMessage);
  56782. resolve(vertexData);
  56783. onComplete();
  56784. }
  56785. else if (message.data.id === "indices") {
  56786. vertexData.indices = message.data.value;
  56787. }
  56788. else {
  56789. vertexData.set(message.data.value, message.data.id);
  56790. }
  56791. };
  56792. worker.addEventListener("error", onError);
  56793. worker.addEventListener("message", onMessage);
  56794. var dataCopy = new Uint8Array(data.byteLength);
  56795. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56796. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56797. });
  56798. });
  56799. };
  56800. /**
  56801. * The worker function that gets converted to a blob url to pass into a worker.
  56802. */
  56803. DracoCompression._Worker = function () {
  56804. // self is actually a DedicatedWorkerGlobalScope
  56805. var _self = self;
  56806. var decodeMesh = function (data, attributes) {
  56807. var dracoModule = new DracoDecoderModule();
  56808. var buffer = new dracoModule.DecoderBuffer();
  56809. buffer.Init(data, data.byteLength);
  56810. var decoder = new dracoModule.Decoder();
  56811. var geometry;
  56812. var status;
  56813. try {
  56814. var type = decoder.GetEncodedGeometryType(buffer);
  56815. switch (type) {
  56816. case dracoModule.TRIANGULAR_MESH:
  56817. geometry = new dracoModule.Mesh();
  56818. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56819. break;
  56820. case dracoModule.POINT_CLOUD:
  56821. geometry = new dracoModule.PointCloud();
  56822. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56823. break;
  56824. default:
  56825. throw new Error("Invalid geometry type " + type);
  56826. }
  56827. if (!status.ok() || !geometry.ptr) {
  56828. throw new Error(status.error_msg());
  56829. }
  56830. var numPoints = geometry.num_points();
  56831. if (type === dracoModule.TRIANGULAR_MESH) {
  56832. var numFaces = geometry.num_faces();
  56833. var faceIndices = new dracoModule.DracoInt32Array();
  56834. try {
  56835. var indices = new Uint32Array(numFaces * 3);
  56836. for (var i = 0; i < numFaces; i++) {
  56837. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56838. var offset = i * 3;
  56839. indices[offset + 0] = faceIndices.GetValue(0);
  56840. indices[offset + 1] = faceIndices.GetValue(1);
  56841. indices[offset + 2] = faceIndices.GetValue(2);
  56842. }
  56843. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56844. }
  56845. finally {
  56846. dracoModule.destroy(faceIndices);
  56847. }
  56848. }
  56849. for (var kind in attributes) {
  56850. var uniqueId = attributes[kind];
  56851. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56852. var dracoData = new dracoModule.DracoFloat32Array();
  56853. try {
  56854. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56855. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56856. for (var i = 0; i < babylonData.length; i++) {
  56857. babylonData[i] = dracoData.GetValue(i);
  56858. }
  56859. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56860. }
  56861. finally {
  56862. dracoModule.destroy(dracoData);
  56863. }
  56864. }
  56865. }
  56866. finally {
  56867. if (geometry) {
  56868. dracoModule.destroy(geometry);
  56869. }
  56870. dracoModule.destroy(decoder);
  56871. dracoModule.destroy(buffer);
  56872. }
  56873. _self.postMessage("done");
  56874. };
  56875. _self.onmessage = function (event) {
  56876. switch (event.data.id) {
  56877. case "initDecoder": {
  56878. importScripts(event.data.url);
  56879. break;
  56880. }
  56881. case "decodeMesh": {
  56882. decodeMesh(event.data.data, event.data.attributes);
  56883. break;
  56884. }
  56885. }
  56886. };
  56887. };
  56888. DracoCompression._GetDefaultDecoderUrl = function () {
  56889. if (!BABYLON.Tools.IsWindowObjectExist) {
  56890. return null;
  56891. }
  56892. for (var i = 0; i < document.scripts.length; i++) {
  56893. if (document.scripts[i].type === "text/x-draco-decoder") {
  56894. return document.scripts[i].src;
  56895. }
  56896. }
  56897. return null;
  56898. };
  56899. /**
  56900. * Gets the url to the draco decoder if available.
  56901. */
  56902. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56903. return DracoCompression;
  56904. }());
  56905. BABYLON.DracoCompression = DracoCompression;
  56906. })(BABYLON || (BABYLON = {}));
  56907. //# sourceMappingURL=babylon.dracoCompression.js.map
  56908. var BABYLON;
  56909. (function (BABYLON) {
  56910. var AudioEngine = /** @class */ (function () {
  56911. function AudioEngine() {
  56912. this._audioContext = null;
  56913. this._audioContextInitialized = false;
  56914. this.canUseWebAudio = false;
  56915. this.WarnedWebAudioUnsupported = false;
  56916. this.unlocked = false;
  56917. this.isMP3supported = false;
  56918. this.isOGGsupported = false;
  56919. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56920. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56921. this.canUseWebAudio = true;
  56922. }
  56923. var audioElem = document.createElement('audio');
  56924. try {
  56925. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56926. this.isMP3supported = true;
  56927. }
  56928. }
  56929. catch (e) {
  56930. // protect error during capability check.
  56931. }
  56932. try {
  56933. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56934. this.isOGGsupported = true;
  56935. }
  56936. }
  56937. catch (e) {
  56938. // protect error during capability check.
  56939. }
  56940. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56941. this._unlockiOSaudio();
  56942. }
  56943. else {
  56944. this.unlocked = true;
  56945. }
  56946. }
  56947. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56948. get: function () {
  56949. if (!this._audioContextInitialized) {
  56950. this._initializeAudioContext();
  56951. }
  56952. return this._audioContext;
  56953. },
  56954. enumerable: true,
  56955. configurable: true
  56956. });
  56957. AudioEngine.prototype._unlockiOSaudio = function () {
  56958. var _this = this;
  56959. var unlockaudio = function () {
  56960. if (!_this.audioContext) {
  56961. return;
  56962. }
  56963. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56964. var source = _this.audioContext.createBufferSource();
  56965. source.buffer = buffer;
  56966. source.connect(_this.audioContext.destination);
  56967. source.start(0);
  56968. setTimeout(function () {
  56969. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56970. _this.unlocked = true;
  56971. window.removeEventListener('touchend', unlockaudio, false);
  56972. if (_this.onAudioUnlocked) {
  56973. _this.onAudioUnlocked();
  56974. }
  56975. }
  56976. }, 0);
  56977. };
  56978. window.addEventListener('touchend', unlockaudio, false);
  56979. };
  56980. AudioEngine.prototype._initializeAudioContext = function () {
  56981. try {
  56982. if (this.canUseWebAudio) {
  56983. this._audioContext = new AudioContext();
  56984. // create a global volume gain node
  56985. this.masterGain = this._audioContext.createGain();
  56986. this.masterGain.gain.value = 1;
  56987. this.masterGain.connect(this._audioContext.destination);
  56988. this._audioContextInitialized = true;
  56989. }
  56990. }
  56991. catch (e) {
  56992. this.canUseWebAudio = false;
  56993. BABYLON.Tools.Error("Web Audio: " + e.message);
  56994. }
  56995. };
  56996. AudioEngine.prototype.dispose = function () {
  56997. if (this.canUseWebAudio && this._audioContextInitialized) {
  56998. if (this._connectedAnalyser && this._audioContext) {
  56999. this._connectedAnalyser.stopDebugCanvas();
  57000. this._connectedAnalyser.dispose();
  57001. this.masterGain.disconnect();
  57002. this.masterGain.connect(this._audioContext.destination);
  57003. this._connectedAnalyser = null;
  57004. }
  57005. this.masterGain.gain.value = 1;
  57006. }
  57007. this.WarnedWebAudioUnsupported = false;
  57008. };
  57009. AudioEngine.prototype.getGlobalVolume = function () {
  57010. if (this.canUseWebAudio && this._audioContextInitialized) {
  57011. return this.masterGain.gain.value;
  57012. }
  57013. else {
  57014. return -1;
  57015. }
  57016. };
  57017. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57018. if (this.canUseWebAudio && this._audioContextInitialized) {
  57019. this.masterGain.gain.value = newVolume;
  57020. }
  57021. };
  57022. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57023. if (this._connectedAnalyser) {
  57024. this._connectedAnalyser.stopDebugCanvas();
  57025. }
  57026. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57027. this._connectedAnalyser = analyser;
  57028. this.masterGain.disconnect();
  57029. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57030. }
  57031. };
  57032. return AudioEngine;
  57033. }());
  57034. BABYLON.AudioEngine = AudioEngine;
  57035. })(BABYLON || (BABYLON = {}));
  57036. //# sourceMappingURL=babylon.audioEngine.js.map
  57037. var BABYLON;
  57038. (function (BABYLON) {
  57039. var Sound = /** @class */ (function () {
  57040. /**
  57041. * Create a sound and attach it to a scene
  57042. * @param name Name of your sound
  57043. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57044. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57045. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57046. */
  57047. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57048. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57049. var _this = this;
  57050. this.autoplay = false;
  57051. this.loop = false;
  57052. this.useCustomAttenuation = false;
  57053. this.spatialSound = false;
  57054. this.refDistance = 1;
  57055. this.rolloffFactor = 1;
  57056. this.maxDistance = 100;
  57057. this.distanceModel = "linear";
  57058. this._panningModel = "equalpower";
  57059. this._playbackRate = 1;
  57060. this._streaming = false;
  57061. this._startTime = 0;
  57062. this._startOffset = 0;
  57063. this._position = BABYLON.Vector3.Zero();
  57064. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57065. this._volume = 1;
  57066. this._isReadyToPlay = false;
  57067. this.isPlaying = false;
  57068. this.isPaused = false;
  57069. this._isDirectional = false;
  57070. // Used if you'd like to create a directional sound.
  57071. // If not set, the sound will be omnidirectional
  57072. this._coneInnerAngle = 360;
  57073. this._coneOuterAngle = 360;
  57074. this._coneOuterGain = 0;
  57075. this._isOutputConnected = false;
  57076. this._urlType = "Unknown";
  57077. this.name = name;
  57078. this._scene = scene;
  57079. this._readyToPlayCallback = readyToPlayCallback;
  57080. // Default custom attenuation function is a linear attenuation
  57081. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57082. if (currentDistance < maxDistance) {
  57083. return currentVolume * (1 - currentDistance / maxDistance);
  57084. }
  57085. else {
  57086. return 0;
  57087. }
  57088. };
  57089. if (options) {
  57090. this.autoplay = options.autoplay || false;
  57091. this.loop = options.loop || false;
  57092. // if volume === 0, we need another way to check this option
  57093. if (options.volume !== undefined) {
  57094. this._volume = options.volume;
  57095. }
  57096. this.spatialSound = options.spatialSound || false;
  57097. this.maxDistance = options.maxDistance || 100;
  57098. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57099. this.rolloffFactor = options.rolloffFactor || 1;
  57100. this.refDistance = options.refDistance || 1;
  57101. this.distanceModel = options.distanceModel || "linear";
  57102. this._playbackRate = options.playbackRate || 1;
  57103. this._streaming = options.streaming || false;
  57104. }
  57105. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57106. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57107. this._soundGain.gain.value = this._volume;
  57108. this._inputAudioNode = this._soundGain;
  57109. this._ouputAudioNode = this._soundGain;
  57110. if (this.spatialSound) {
  57111. this._createSpatialParameters();
  57112. }
  57113. this._scene.mainSoundTrack.AddSound(this);
  57114. var validParameter = true;
  57115. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57116. if (urlOrArrayBuffer) {
  57117. if (typeof (urlOrArrayBuffer) === "string")
  57118. this._urlType = "String";
  57119. if (Array.isArray(urlOrArrayBuffer))
  57120. this._urlType = "Array";
  57121. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57122. this._urlType = "ArrayBuffer";
  57123. var urls = [];
  57124. var codecSupportedFound = false;
  57125. switch (this._urlType) {
  57126. case "ArrayBuffer":
  57127. if (urlOrArrayBuffer.byteLength > 0) {
  57128. codecSupportedFound = true;
  57129. this._soundLoaded(urlOrArrayBuffer);
  57130. }
  57131. break;
  57132. case "String":
  57133. urls.push(urlOrArrayBuffer);
  57134. case "Array":
  57135. if (urls.length === 0)
  57136. urls = urlOrArrayBuffer;
  57137. // If we found a supported format, we load it immediately and stop the loop
  57138. for (var i = 0; i < urls.length; i++) {
  57139. var url = urls[i];
  57140. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57141. codecSupportedFound = true;
  57142. }
  57143. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57144. codecSupportedFound = true;
  57145. }
  57146. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57147. codecSupportedFound = true;
  57148. }
  57149. if (url.indexOf("blob:") !== -1) {
  57150. codecSupportedFound = true;
  57151. }
  57152. if (codecSupportedFound) {
  57153. // Loading sound using XHR2
  57154. if (!this._streaming) {
  57155. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57156. }
  57157. else {
  57158. this._htmlAudioElement = new Audio(url);
  57159. this._htmlAudioElement.controls = false;
  57160. this._htmlAudioElement.loop = this.loop;
  57161. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57162. this._htmlAudioElement.preload = "auto";
  57163. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57164. _this._isReadyToPlay = true;
  57165. if (_this.autoplay) {
  57166. _this.play();
  57167. }
  57168. if (_this._readyToPlayCallback) {
  57169. _this._readyToPlayCallback();
  57170. }
  57171. });
  57172. document.body.appendChild(this._htmlAudioElement);
  57173. }
  57174. break;
  57175. }
  57176. }
  57177. break;
  57178. default:
  57179. validParameter = false;
  57180. break;
  57181. }
  57182. if (!validParameter) {
  57183. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57184. }
  57185. else {
  57186. if (!codecSupportedFound) {
  57187. this._isReadyToPlay = true;
  57188. // Simulating a ready to play event to avoid breaking code path
  57189. if (this._readyToPlayCallback) {
  57190. window.setTimeout(function () {
  57191. if (_this._readyToPlayCallback) {
  57192. _this._readyToPlayCallback();
  57193. }
  57194. }, 1000);
  57195. }
  57196. }
  57197. }
  57198. }
  57199. }
  57200. else {
  57201. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57202. this._scene.mainSoundTrack.AddSound(this);
  57203. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57204. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57205. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57206. }
  57207. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57208. if (this._readyToPlayCallback) {
  57209. window.setTimeout(function () {
  57210. if (_this._readyToPlayCallback) {
  57211. _this._readyToPlayCallback();
  57212. }
  57213. }, 1000);
  57214. }
  57215. }
  57216. }
  57217. Sound.prototype.dispose = function () {
  57218. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57219. if (this.isPlaying) {
  57220. this.stop();
  57221. }
  57222. this._isReadyToPlay = false;
  57223. if (this.soundTrackId === -1) {
  57224. this._scene.mainSoundTrack.RemoveSound(this);
  57225. }
  57226. else {
  57227. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57228. }
  57229. if (this._soundGain) {
  57230. this._soundGain.disconnect();
  57231. this._soundGain = null;
  57232. }
  57233. if (this._soundPanner) {
  57234. this._soundPanner.disconnect();
  57235. this._soundPanner = null;
  57236. }
  57237. if (this._soundSource) {
  57238. this._soundSource.disconnect();
  57239. this._soundSource = null;
  57240. }
  57241. this._audioBuffer = null;
  57242. if (this._htmlAudioElement) {
  57243. this._htmlAudioElement.pause();
  57244. this._htmlAudioElement.src = "";
  57245. document.body.removeChild(this._htmlAudioElement);
  57246. }
  57247. if (this._connectedMesh && this._registerFunc) {
  57248. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57249. this._connectedMesh = null;
  57250. }
  57251. }
  57252. };
  57253. Sound.prototype.isReady = function () {
  57254. return this._isReadyToPlay;
  57255. };
  57256. Sound.prototype._soundLoaded = function (audioData) {
  57257. var _this = this;
  57258. if (!BABYLON.Engine.audioEngine.audioContext) {
  57259. return;
  57260. }
  57261. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57262. _this._audioBuffer = buffer;
  57263. _this._isReadyToPlay = true;
  57264. if (_this.autoplay) {
  57265. _this.play();
  57266. }
  57267. if (_this._readyToPlayCallback) {
  57268. _this._readyToPlayCallback();
  57269. }
  57270. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57271. };
  57272. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57273. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57274. this._audioBuffer = audioBuffer;
  57275. this._isReadyToPlay = true;
  57276. }
  57277. };
  57278. Sound.prototype.updateOptions = function (options) {
  57279. if (options) {
  57280. this.loop = options.loop || this.loop;
  57281. this.maxDistance = options.maxDistance || this.maxDistance;
  57282. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57283. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57284. this.refDistance = options.refDistance || this.refDistance;
  57285. this.distanceModel = options.distanceModel || this.distanceModel;
  57286. this._playbackRate = options.playbackRate || this._playbackRate;
  57287. this._updateSpatialParameters();
  57288. if (this.isPlaying) {
  57289. if (this._streaming) {
  57290. this._htmlAudioElement.playbackRate = this._playbackRate;
  57291. }
  57292. else {
  57293. if (this._soundSource) {
  57294. this._soundSource.playbackRate.value = this._playbackRate;
  57295. }
  57296. }
  57297. }
  57298. }
  57299. };
  57300. Sound.prototype._createSpatialParameters = function () {
  57301. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57302. if (this._scene.headphone) {
  57303. this._panningModel = "HRTF";
  57304. }
  57305. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57306. this._updateSpatialParameters();
  57307. this._soundPanner.connect(this._ouputAudioNode);
  57308. this._inputAudioNode = this._soundPanner;
  57309. }
  57310. };
  57311. Sound.prototype._updateSpatialParameters = function () {
  57312. if (this.spatialSound && this._soundPanner) {
  57313. if (this.useCustomAttenuation) {
  57314. // Tricks to disable in a way embedded Web Audio attenuation
  57315. this._soundPanner.distanceModel = "linear";
  57316. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57317. this._soundPanner.refDistance = 1;
  57318. this._soundPanner.rolloffFactor = 1;
  57319. this._soundPanner.panningModel = this._panningModel;
  57320. }
  57321. else {
  57322. this._soundPanner.distanceModel = this.distanceModel;
  57323. this._soundPanner.maxDistance = this.maxDistance;
  57324. this._soundPanner.refDistance = this.refDistance;
  57325. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57326. this._soundPanner.panningModel = this._panningModel;
  57327. }
  57328. }
  57329. };
  57330. Sound.prototype.switchPanningModelToHRTF = function () {
  57331. this._panningModel = "HRTF";
  57332. this._switchPanningModel();
  57333. };
  57334. Sound.prototype.switchPanningModelToEqualPower = function () {
  57335. this._panningModel = "equalpower";
  57336. this._switchPanningModel();
  57337. };
  57338. Sound.prototype._switchPanningModel = function () {
  57339. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57340. this._soundPanner.panningModel = this._panningModel;
  57341. }
  57342. };
  57343. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57344. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57345. if (this._isOutputConnected) {
  57346. this._ouputAudioNode.disconnect();
  57347. }
  57348. this._ouputAudioNode.connect(soundTrackAudioNode);
  57349. this._isOutputConnected = true;
  57350. }
  57351. };
  57352. /**
  57353. * Transform this sound into a directional source
  57354. * @param coneInnerAngle Size of the inner cone in degree
  57355. * @param coneOuterAngle Size of the outer cone in degree
  57356. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57357. */
  57358. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57359. if (coneOuterAngle < coneInnerAngle) {
  57360. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57361. return;
  57362. }
  57363. this._coneInnerAngle = coneInnerAngle;
  57364. this._coneOuterAngle = coneOuterAngle;
  57365. this._coneOuterGain = coneOuterGain;
  57366. this._isDirectional = true;
  57367. if (this.isPlaying && this.loop) {
  57368. this.stop();
  57369. this.play();
  57370. }
  57371. };
  57372. Sound.prototype.setPosition = function (newPosition) {
  57373. this._position = newPosition;
  57374. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57375. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57376. }
  57377. };
  57378. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57379. this._localDirection = newLocalDirection;
  57380. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57381. this._updateDirection();
  57382. }
  57383. };
  57384. Sound.prototype._updateDirection = function () {
  57385. if (!this._connectedMesh || !this._soundPanner) {
  57386. return;
  57387. }
  57388. var mat = this._connectedMesh.getWorldMatrix();
  57389. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57390. direction.normalize();
  57391. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57392. };
  57393. Sound.prototype.updateDistanceFromListener = function () {
  57394. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57395. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57396. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57397. }
  57398. };
  57399. Sound.prototype.setAttenuationFunction = function (callback) {
  57400. this._customAttenuationFunction = callback;
  57401. };
  57402. /**
  57403. * Play the sound
  57404. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57405. * @param offset (optional) Start the sound setting it at a specific time
  57406. */
  57407. Sound.prototype.play = function (time, offset) {
  57408. var _this = this;
  57409. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57410. try {
  57411. if (this._startOffset < 0) {
  57412. time = -this._startOffset;
  57413. this._startOffset = 0;
  57414. }
  57415. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57416. if (!this._soundSource || !this._streamingSource) {
  57417. if (this.spatialSound && this._soundPanner) {
  57418. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57419. if (this._isDirectional) {
  57420. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57421. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57422. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57423. if (this._connectedMesh) {
  57424. this._updateDirection();
  57425. }
  57426. else {
  57427. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57428. }
  57429. }
  57430. }
  57431. }
  57432. if (this._streaming) {
  57433. if (!this._streamingSource) {
  57434. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57435. this._htmlAudioElement.onended = function () { _this._onended(); };
  57436. this._htmlAudioElement.playbackRate = this._playbackRate;
  57437. }
  57438. this._streamingSource.disconnect();
  57439. this._streamingSource.connect(this._inputAudioNode);
  57440. this._htmlAudioElement.play();
  57441. }
  57442. else {
  57443. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57444. this._soundSource.buffer = this._audioBuffer;
  57445. this._soundSource.connect(this._inputAudioNode);
  57446. this._soundSource.loop = this.loop;
  57447. this._soundSource.playbackRate.value = this._playbackRate;
  57448. this._soundSource.onended = function () { _this._onended(); };
  57449. if (this._soundSource.buffer) {
  57450. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57451. }
  57452. }
  57453. this._startTime = startTime;
  57454. this.isPlaying = true;
  57455. this.isPaused = false;
  57456. }
  57457. catch (ex) {
  57458. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57459. }
  57460. }
  57461. };
  57462. Sound.prototype._onended = function () {
  57463. this.isPlaying = false;
  57464. if (this.onended) {
  57465. this.onended();
  57466. }
  57467. };
  57468. /**
  57469. * Stop the sound
  57470. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57471. */
  57472. Sound.prototype.stop = function (time) {
  57473. if (this.isPlaying) {
  57474. if (this._streaming) {
  57475. this._htmlAudioElement.pause();
  57476. // Test needed for Firefox or it will generate an Invalid State Error
  57477. if (this._htmlAudioElement.currentTime > 0) {
  57478. this._htmlAudioElement.currentTime = 0;
  57479. }
  57480. }
  57481. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57482. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57483. this._soundSource.stop(stopTime);
  57484. this._soundSource.onended = function () { };
  57485. if (!this.isPaused) {
  57486. this._startOffset = 0;
  57487. }
  57488. }
  57489. this.isPlaying = false;
  57490. }
  57491. };
  57492. Sound.prototype.pause = function () {
  57493. if (this.isPlaying) {
  57494. this.isPaused = true;
  57495. if (this._streaming) {
  57496. this._htmlAudioElement.pause();
  57497. }
  57498. else if (BABYLON.Engine.audioEngine.audioContext) {
  57499. this.stop(0);
  57500. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57501. }
  57502. }
  57503. };
  57504. Sound.prototype.setVolume = function (newVolume, time) {
  57505. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57506. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57507. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57508. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57509. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57510. }
  57511. else {
  57512. this._soundGain.gain.value = newVolume;
  57513. }
  57514. }
  57515. this._volume = newVolume;
  57516. };
  57517. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57518. this._playbackRate = newPlaybackRate;
  57519. if (this.isPlaying) {
  57520. if (this._streaming) {
  57521. this._htmlAudioElement.playbackRate = this._playbackRate;
  57522. }
  57523. else if (this._soundSource) {
  57524. this._soundSource.playbackRate.value = this._playbackRate;
  57525. }
  57526. }
  57527. };
  57528. Sound.prototype.getVolume = function () {
  57529. return this._volume;
  57530. };
  57531. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57532. var _this = this;
  57533. if (this._connectedMesh && this._registerFunc) {
  57534. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57535. this._registerFunc = null;
  57536. }
  57537. this._connectedMesh = meshToConnectTo;
  57538. if (!this.spatialSound) {
  57539. this.spatialSound = true;
  57540. this._createSpatialParameters();
  57541. if (this.isPlaying && this.loop) {
  57542. this.stop();
  57543. this.play();
  57544. }
  57545. }
  57546. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57547. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57548. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57549. };
  57550. Sound.prototype.detachFromMesh = function () {
  57551. if (this._connectedMesh && this._registerFunc) {
  57552. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57553. this._registerFunc = null;
  57554. this._connectedMesh = null;
  57555. }
  57556. };
  57557. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57558. if (!node.getBoundingInfo) {
  57559. return;
  57560. }
  57561. var mesh = node;
  57562. var boundingInfo = mesh.getBoundingInfo();
  57563. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57564. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57565. this._updateDirection();
  57566. }
  57567. };
  57568. Sound.prototype.clone = function () {
  57569. var _this = this;
  57570. if (!this._streaming) {
  57571. var setBufferAndRun = function () {
  57572. if (_this._isReadyToPlay) {
  57573. clonedSound._audioBuffer = _this.getAudioBuffer();
  57574. clonedSound._isReadyToPlay = true;
  57575. if (clonedSound.autoplay) {
  57576. clonedSound.play();
  57577. }
  57578. }
  57579. else {
  57580. window.setTimeout(setBufferAndRun, 300);
  57581. }
  57582. };
  57583. var currentOptions = {
  57584. autoplay: this.autoplay, loop: this.loop,
  57585. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57586. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57587. refDistance: this.refDistance, distanceModel: this.distanceModel
  57588. };
  57589. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57590. if (this.useCustomAttenuation) {
  57591. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57592. }
  57593. clonedSound.setPosition(this._position);
  57594. clonedSound.setPlaybackRate(this._playbackRate);
  57595. setBufferAndRun();
  57596. return clonedSound;
  57597. }
  57598. else {
  57599. return null;
  57600. }
  57601. };
  57602. Sound.prototype.getAudioBuffer = function () {
  57603. return this._audioBuffer;
  57604. };
  57605. Sound.prototype.serialize = function () {
  57606. var serializationObject = {
  57607. name: this.name,
  57608. url: this.name,
  57609. autoplay: this.autoplay,
  57610. loop: this.loop,
  57611. volume: this._volume,
  57612. spatialSound: this.spatialSound,
  57613. maxDistance: this.maxDistance,
  57614. rolloffFactor: this.rolloffFactor,
  57615. refDistance: this.refDistance,
  57616. distanceModel: this.distanceModel,
  57617. playbackRate: this._playbackRate,
  57618. panningModel: this._panningModel,
  57619. soundTrackId: this.soundTrackId
  57620. };
  57621. if (this.spatialSound) {
  57622. if (this._connectedMesh)
  57623. serializationObject.connectedMeshId = this._connectedMesh.id;
  57624. serializationObject.position = this._position.asArray();
  57625. serializationObject.refDistance = this.refDistance;
  57626. serializationObject.distanceModel = this.distanceModel;
  57627. serializationObject.isDirectional = this._isDirectional;
  57628. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57629. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57630. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57631. serializationObject.coneOuterGain = this._coneOuterGain;
  57632. }
  57633. return serializationObject;
  57634. };
  57635. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57636. var soundName = parsedSound.name;
  57637. var soundUrl;
  57638. if (parsedSound.url) {
  57639. soundUrl = rootUrl + parsedSound.url;
  57640. }
  57641. else {
  57642. soundUrl = rootUrl + soundName;
  57643. }
  57644. var options = {
  57645. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57646. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57647. rolloffFactor: parsedSound.rolloffFactor,
  57648. refDistance: parsedSound.refDistance,
  57649. distanceModel: parsedSound.distanceModel,
  57650. playbackRate: parsedSound.playbackRate
  57651. };
  57652. var newSound;
  57653. if (!sourceSound) {
  57654. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57655. scene._addPendingData(newSound);
  57656. }
  57657. else {
  57658. var setBufferAndRun = function () {
  57659. if (sourceSound._isReadyToPlay) {
  57660. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57661. newSound._isReadyToPlay = true;
  57662. if (newSound.autoplay) {
  57663. newSound.play();
  57664. }
  57665. }
  57666. else {
  57667. window.setTimeout(setBufferAndRun, 300);
  57668. }
  57669. };
  57670. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57671. setBufferAndRun();
  57672. }
  57673. if (parsedSound.position) {
  57674. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57675. newSound.setPosition(soundPosition);
  57676. }
  57677. if (parsedSound.isDirectional) {
  57678. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57679. if (parsedSound.localDirectionToMesh) {
  57680. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57681. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57682. }
  57683. }
  57684. if (parsedSound.connectedMeshId) {
  57685. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57686. if (connectedMesh) {
  57687. newSound.attachToMesh(connectedMesh);
  57688. }
  57689. }
  57690. return newSound;
  57691. };
  57692. return Sound;
  57693. }());
  57694. BABYLON.Sound = Sound;
  57695. })(BABYLON || (BABYLON = {}));
  57696. //# sourceMappingURL=babylon.sound.js.map
  57697. var BABYLON;
  57698. (function (BABYLON) {
  57699. var SoundTrack = /** @class */ (function () {
  57700. function SoundTrack(scene, options) {
  57701. this.id = -1;
  57702. this._isMainTrack = false;
  57703. this._isInitialized = false;
  57704. this._scene = scene;
  57705. this.soundCollection = new Array();
  57706. this._options = options;
  57707. if (!this._isMainTrack) {
  57708. this._scene.soundTracks.push(this);
  57709. this.id = this._scene.soundTracks.length - 1;
  57710. }
  57711. }
  57712. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57713. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57714. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57715. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57716. if (this._options) {
  57717. if (this._options.volume) {
  57718. this._outputAudioNode.gain.value = this._options.volume;
  57719. }
  57720. if (this._options.mainTrack) {
  57721. this._isMainTrack = this._options.mainTrack;
  57722. }
  57723. }
  57724. this._isInitialized = true;
  57725. }
  57726. };
  57727. SoundTrack.prototype.dispose = function () {
  57728. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57729. if (this._connectedAnalyser) {
  57730. this._connectedAnalyser.stopDebugCanvas();
  57731. }
  57732. while (this.soundCollection.length) {
  57733. this.soundCollection[0].dispose();
  57734. }
  57735. if (this._outputAudioNode) {
  57736. this._outputAudioNode.disconnect();
  57737. }
  57738. this._outputAudioNode = null;
  57739. }
  57740. };
  57741. SoundTrack.prototype.AddSound = function (sound) {
  57742. if (!this._isInitialized) {
  57743. this._initializeSoundTrackAudioGraph();
  57744. }
  57745. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57746. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57747. }
  57748. if (sound.soundTrackId) {
  57749. if (sound.soundTrackId === -1) {
  57750. this._scene.mainSoundTrack.RemoveSound(sound);
  57751. }
  57752. else {
  57753. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57754. }
  57755. }
  57756. this.soundCollection.push(sound);
  57757. sound.soundTrackId = this.id;
  57758. };
  57759. SoundTrack.prototype.RemoveSound = function (sound) {
  57760. var index = this.soundCollection.indexOf(sound);
  57761. if (index !== -1) {
  57762. this.soundCollection.splice(index, 1);
  57763. }
  57764. };
  57765. SoundTrack.prototype.setVolume = function (newVolume) {
  57766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57767. this._outputAudioNode.gain.value = newVolume;
  57768. }
  57769. };
  57770. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57772. for (var i = 0; i < this.soundCollection.length; i++) {
  57773. this.soundCollection[i].switchPanningModelToHRTF();
  57774. }
  57775. }
  57776. };
  57777. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57779. for (var i = 0; i < this.soundCollection.length; i++) {
  57780. this.soundCollection[i].switchPanningModelToEqualPower();
  57781. }
  57782. }
  57783. };
  57784. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57785. if (this._connectedAnalyser) {
  57786. this._connectedAnalyser.stopDebugCanvas();
  57787. }
  57788. this._connectedAnalyser = analyser;
  57789. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57790. this._outputAudioNode.disconnect();
  57791. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57792. }
  57793. };
  57794. return SoundTrack;
  57795. }());
  57796. BABYLON.SoundTrack = SoundTrack;
  57797. })(BABYLON || (BABYLON = {}));
  57798. //# sourceMappingURL=babylon.soundtrack.js.map
  57799. var BABYLON;
  57800. (function (BABYLON) {
  57801. var Analyser = /** @class */ (function () {
  57802. function Analyser(scene) {
  57803. this.SMOOTHING = 0.75;
  57804. this.FFT_SIZE = 512;
  57805. this.BARGRAPHAMPLITUDE = 256;
  57806. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57807. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57808. this._scene = scene;
  57809. this._audioEngine = BABYLON.Engine.audioEngine;
  57810. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57811. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57812. this._webAudioAnalyser.minDecibels = -140;
  57813. this._webAudioAnalyser.maxDecibels = 0;
  57814. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57815. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57816. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57817. }
  57818. }
  57819. Analyser.prototype.getFrequencyBinCount = function () {
  57820. if (this._audioEngine.canUseWebAudio) {
  57821. return this._webAudioAnalyser.frequencyBinCount;
  57822. }
  57823. else {
  57824. return 0;
  57825. }
  57826. };
  57827. Analyser.prototype.getByteFrequencyData = function () {
  57828. if (this._audioEngine.canUseWebAudio) {
  57829. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57830. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57831. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57832. }
  57833. return this._byteFreqs;
  57834. };
  57835. Analyser.prototype.getByteTimeDomainData = function () {
  57836. if (this._audioEngine.canUseWebAudio) {
  57837. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57838. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57839. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57840. }
  57841. return this._byteTime;
  57842. };
  57843. Analyser.prototype.getFloatFrequencyData = function () {
  57844. if (this._audioEngine.canUseWebAudio) {
  57845. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57846. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57847. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57848. }
  57849. return this._floatFreqs;
  57850. };
  57851. Analyser.prototype.drawDebugCanvas = function () {
  57852. var _this = this;
  57853. if (this._audioEngine.canUseWebAudio) {
  57854. if (!this._debugCanvas) {
  57855. this._debugCanvas = document.createElement("canvas");
  57856. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57857. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57858. this._debugCanvas.style.position = "absolute";
  57859. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57860. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57861. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57862. document.body.appendChild(this._debugCanvas);
  57863. this._registerFunc = function () {
  57864. _this.drawDebugCanvas();
  57865. };
  57866. this._scene.registerBeforeRender(this._registerFunc);
  57867. }
  57868. if (this._registerFunc && this._debugCanvasContext) {
  57869. var workingArray = this.getByteFrequencyData();
  57870. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57871. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57872. // Draw the frequency domain chart.
  57873. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57874. var value = workingArray[i];
  57875. var percent = value / this.BARGRAPHAMPLITUDE;
  57876. var height = this.DEBUGCANVASSIZE.height * percent;
  57877. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57878. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57879. var hue = i / this.getFrequencyBinCount() * 360;
  57880. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57881. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57882. }
  57883. }
  57884. }
  57885. };
  57886. Analyser.prototype.stopDebugCanvas = function () {
  57887. if (this._debugCanvas) {
  57888. if (this._registerFunc) {
  57889. this._scene.unregisterBeforeRender(this._registerFunc);
  57890. this._registerFunc = null;
  57891. }
  57892. document.body.removeChild(this._debugCanvas);
  57893. this._debugCanvas = null;
  57894. this._debugCanvasContext = null;
  57895. }
  57896. };
  57897. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57898. if (this._audioEngine.canUseWebAudio) {
  57899. inputAudioNode.connect(this._webAudioAnalyser);
  57900. this._webAudioAnalyser.connect(outputAudioNode);
  57901. }
  57902. };
  57903. Analyser.prototype.dispose = function () {
  57904. if (this._audioEngine.canUseWebAudio) {
  57905. this._webAudioAnalyser.disconnect();
  57906. }
  57907. };
  57908. return Analyser;
  57909. }());
  57910. BABYLON.Analyser = Analyser;
  57911. })(BABYLON || (BABYLON = {}));
  57912. //# sourceMappingURL=babylon.analyser.js.map
  57913. var BABYLON;
  57914. (function (BABYLON) {
  57915. var CubeTexture = /** @class */ (function (_super) {
  57916. __extends(CubeTexture, _super);
  57917. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57918. if (extensions === void 0) { extensions = null; }
  57919. if (noMipmap === void 0) { noMipmap = false; }
  57920. if (files === void 0) { files = null; }
  57921. if (onLoad === void 0) { onLoad = null; }
  57922. if (onError === void 0) { onError = null; }
  57923. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57924. if (prefiltered === void 0) { prefiltered = false; }
  57925. if (forcedExtension === void 0) { forcedExtension = null; }
  57926. var _this = _super.call(this, scene) || this;
  57927. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57928. /**
  57929. * Gets or sets the center of the bounding box associated with the cube texture
  57930. * It must define where the camera used to render the texture was set
  57931. */
  57932. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57933. _this.name = rootUrl;
  57934. _this.url = rootUrl;
  57935. _this._noMipmap = noMipmap;
  57936. _this.hasAlpha = false;
  57937. _this._format = format;
  57938. _this._prefiltered = prefiltered;
  57939. _this.isCube = true;
  57940. _this._textureMatrix = BABYLON.Matrix.Identity();
  57941. if (prefiltered) {
  57942. _this.gammaSpace = false;
  57943. }
  57944. if (!rootUrl && !files) {
  57945. return _this;
  57946. }
  57947. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57948. var lastDot = rootUrl.lastIndexOf(".");
  57949. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57950. var isDDS = (extension === ".dds");
  57951. if (!files) {
  57952. if (!isDDS && !extensions) {
  57953. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57954. }
  57955. files = [];
  57956. if (extensions) {
  57957. for (var index = 0; index < extensions.length; index++) {
  57958. files.push(rootUrl + extensions[index]);
  57959. }
  57960. }
  57961. }
  57962. _this._files = files;
  57963. if (!_this._texture) {
  57964. if (!scene.useDelayedTextureLoading) {
  57965. if (prefiltered) {
  57966. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57967. }
  57968. else {
  57969. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57970. }
  57971. }
  57972. else {
  57973. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57974. }
  57975. }
  57976. else if (onLoad) {
  57977. if (_this._texture.isReady) {
  57978. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57979. }
  57980. else {
  57981. _this._texture.onLoadedObservable.add(onLoad);
  57982. }
  57983. }
  57984. return _this;
  57985. }
  57986. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57987. get: function () {
  57988. return this._boundingBoxSize;
  57989. },
  57990. /**
  57991. * Gets or sets the size of the bounding box associated with the cube texture
  57992. * When defined, the cubemap will switch to local mode
  57993. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57994. * @example https://www.babylonjs-playground.com/#RNASML
  57995. */
  57996. set: function (value) {
  57997. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57998. return;
  57999. }
  58000. this._boundingBoxSize = value;
  58001. var scene = this.getScene();
  58002. if (scene) {
  58003. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58004. }
  58005. },
  58006. enumerable: true,
  58007. configurable: true
  58008. });
  58009. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58010. var rootUrlKey = "";
  58011. files.forEach(function (url) { return rootUrlKey += url; });
  58012. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58013. };
  58014. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58015. if (forcedExtension === void 0) { forcedExtension = null; }
  58016. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58017. };
  58018. // Methods
  58019. CubeTexture.prototype.delayLoad = function () {
  58020. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58021. return;
  58022. }
  58023. var scene = this.getScene();
  58024. if (!scene) {
  58025. return;
  58026. }
  58027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58028. this._texture = this._getFromCache(this.url, this._noMipmap);
  58029. if (!this._texture) {
  58030. if (this._prefiltered) {
  58031. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58032. }
  58033. else {
  58034. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58035. }
  58036. }
  58037. };
  58038. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58039. return this._textureMatrix;
  58040. };
  58041. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58042. this._textureMatrix = value;
  58043. };
  58044. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58045. var texture = BABYLON.SerializationHelper.Parse(function () {
  58046. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58047. }, parsedTexture, scene);
  58048. // Local Cubemaps
  58049. if (parsedTexture.boundingBoxPosition) {
  58050. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58051. }
  58052. if (parsedTexture.boundingBoxSize) {
  58053. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58054. }
  58055. // Animations
  58056. if (parsedTexture.animations) {
  58057. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58058. var parsedAnimation = parsedTexture.animations[animationIndex];
  58059. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58060. }
  58061. }
  58062. return texture;
  58063. };
  58064. CubeTexture.prototype.clone = function () {
  58065. var _this = this;
  58066. return BABYLON.SerializationHelper.Clone(function () {
  58067. var scene = _this.getScene();
  58068. if (!scene) {
  58069. return _this;
  58070. }
  58071. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58072. }, this);
  58073. };
  58074. return CubeTexture;
  58075. }(BABYLON.BaseTexture));
  58076. BABYLON.CubeTexture = CubeTexture;
  58077. })(BABYLON || (BABYLON = {}));
  58078. //# sourceMappingURL=babylon.cubeTexture.js.map
  58079. var BABYLON;
  58080. (function (BABYLON) {
  58081. var RenderTargetTexture = /** @class */ (function (_super) {
  58082. __extends(RenderTargetTexture, _super);
  58083. /**
  58084. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58085. * or used a shadow, depth texture...
  58086. * @param name The friendly name of the texture
  58087. * @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)
  58088. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58089. * @param generateMipMaps True if mip maps need to be generated after render.
  58090. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58091. * @param type The type of the buffer in the RTT (int, half float, float...)
  58092. * @param isCube True if a cube texture needs to be created
  58093. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58094. * @param generateDepthBuffer True to generate a depth buffer
  58095. * @param generateStencilBuffer True to generate a stencil buffer
  58096. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58097. */
  58098. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58099. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58100. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58101. if (isCube === void 0) { isCube = false; }
  58102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58103. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58104. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58105. if (isMulti === void 0) { isMulti = false; }
  58106. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58107. _this.isCube = isCube;
  58108. /**
  58109. * Use this list to define the list of mesh you want to render.
  58110. */
  58111. _this.renderList = new Array();
  58112. _this.renderParticles = true;
  58113. _this.renderSprites = false;
  58114. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58115. _this.ignoreCameraViewport = false;
  58116. // Events
  58117. /**
  58118. * An event triggered when the texture is unbind.
  58119. * @type {BABYLON.Observable}
  58120. */
  58121. _this.onBeforeBindObservable = new BABYLON.Observable();
  58122. /**
  58123. * An event triggered when the texture is unbind.
  58124. * @type {BABYLON.Observable}
  58125. */
  58126. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58127. /**
  58128. * An event triggered before rendering the texture
  58129. * @type {BABYLON.Observable}
  58130. */
  58131. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58132. /**
  58133. * An event triggered after rendering the texture
  58134. * @type {BABYLON.Observable}
  58135. */
  58136. _this.onAfterRenderObservable = new BABYLON.Observable();
  58137. /**
  58138. * An event triggered after the texture clear
  58139. * @type {BABYLON.Observable}
  58140. */
  58141. _this.onClearObservable = new BABYLON.Observable();
  58142. _this._currentRefreshId = -1;
  58143. _this._refreshRate = 1;
  58144. _this._samples = 1;
  58145. /**
  58146. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58147. * It must define where the camera used to render the texture is set
  58148. */
  58149. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58150. scene = _this.getScene();
  58151. if (!scene) {
  58152. return _this;
  58153. }
  58154. _this._engine = scene.getEngine();
  58155. _this.name = name;
  58156. _this.isRenderTarget = true;
  58157. _this._initialSizeParameter = size;
  58158. _this._processSizeParameter(size);
  58159. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58160. });
  58161. _this._generateMipMaps = generateMipMaps ? true : false;
  58162. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58163. // Rendering groups
  58164. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58165. if (isMulti) {
  58166. return _this;
  58167. }
  58168. _this._renderTargetOptions = {
  58169. generateMipMaps: generateMipMaps,
  58170. type: type,
  58171. samplingMode: samplingMode,
  58172. generateDepthBuffer: generateDepthBuffer,
  58173. generateStencilBuffer: generateStencilBuffer
  58174. };
  58175. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58176. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58177. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58178. }
  58179. if (isCube) {
  58180. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58181. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58182. _this._textureMatrix = BABYLON.Matrix.Identity();
  58183. }
  58184. else {
  58185. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58186. }
  58187. return _this;
  58188. }
  58189. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58190. get: function () {
  58191. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58192. },
  58193. enumerable: true,
  58194. configurable: true
  58195. });
  58196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58197. get: function () {
  58198. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58199. },
  58200. enumerable: true,
  58201. configurable: true
  58202. });
  58203. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58204. get: function () {
  58205. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58206. },
  58207. enumerable: true,
  58208. configurable: true
  58209. });
  58210. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58211. set: function (callback) {
  58212. if (this._onAfterUnbindObserver) {
  58213. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58214. }
  58215. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58216. },
  58217. enumerable: true,
  58218. configurable: true
  58219. });
  58220. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58221. set: function (callback) {
  58222. if (this._onBeforeRenderObserver) {
  58223. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58224. }
  58225. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58226. },
  58227. enumerable: true,
  58228. configurable: true
  58229. });
  58230. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58231. set: function (callback) {
  58232. if (this._onAfterRenderObserver) {
  58233. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58234. }
  58235. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58236. },
  58237. enumerable: true,
  58238. configurable: true
  58239. });
  58240. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58241. set: function (callback) {
  58242. if (this._onClearObserver) {
  58243. this.onClearObservable.remove(this._onClearObserver);
  58244. }
  58245. this._onClearObserver = this.onClearObservable.add(callback);
  58246. },
  58247. enumerable: true,
  58248. configurable: true
  58249. });
  58250. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58251. get: function () {
  58252. return this._renderTargetOptions;
  58253. },
  58254. enumerable: true,
  58255. configurable: true
  58256. });
  58257. RenderTargetTexture.prototype._onRatioRescale = function () {
  58258. if (this._sizeRatio) {
  58259. this.resize(this._initialSizeParameter);
  58260. }
  58261. };
  58262. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58263. get: function () {
  58264. return this._boundingBoxSize;
  58265. },
  58266. /**
  58267. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58268. * When defined, the cubemap will switch to local mode
  58269. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58270. * @example https://www.babylonjs-playground.com/#RNASML
  58271. */
  58272. set: function (value) {
  58273. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58274. return;
  58275. }
  58276. this._boundingBoxSize = value;
  58277. var scene = this.getScene();
  58278. if (scene) {
  58279. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58280. }
  58281. },
  58282. enumerable: true,
  58283. configurable: true
  58284. });
  58285. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58286. if (size.ratio) {
  58287. this._sizeRatio = size.ratio;
  58288. this._size = {
  58289. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58290. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58291. };
  58292. }
  58293. else {
  58294. this._size = size;
  58295. }
  58296. };
  58297. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58298. get: function () {
  58299. return this._samples;
  58300. },
  58301. set: function (value) {
  58302. if (this._samples === value) {
  58303. return;
  58304. }
  58305. var scene = this.getScene();
  58306. if (!scene) {
  58307. return;
  58308. }
  58309. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58310. },
  58311. enumerable: true,
  58312. configurable: true
  58313. });
  58314. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58315. this._currentRefreshId = -1;
  58316. };
  58317. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58318. get: function () {
  58319. return this._refreshRate;
  58320. },
  58321. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58322. set: function (value) {
  58323. this._refreshRate = value;
  58324. this.resetRefreshCounter();
  58325. },
  58326. enumerable: true,
  58327. configurable: true
  58328. });
  58329. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58330. if (!this._postProcessManager) {
  58331. var scene = this.getScene();
  58332. if (!scene) {
  58333. return;
  58334. }
  58335. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58336. this._postProcesses = new Array();
  58337. }
  58338. this._postProcesses.push(postProcess);
  58339. this._postProcesses[0].autoClear = false;
  58340. };
  58341. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58342. if (!this._postProcesses) {
  58343. return;
  58344. }
  58345. if (dispose) {
  58346. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58347. var postProcess = _a[_i];
  58348. postProcess.dispose();
  58349. }
  58350. }
  58351. this._postProcesses = [];
  58352. };
  58353. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58354. if (!this._postProcesses) {
  58355. return;
  58356. }
  58357. var index = this._postProcesses.indexOf(postProcess);
  58358. if (index === -1) {
  58359. return;
  58360. }
  58361. this._postProcesses.splice(index, 1);
  58362. if (this._postProcesses.length > 0) {
  58363. this._postProcesses[0].autoClear = false;
  58364. }
  58365. };
  58366. RenderTargetTexture.prototype._shouldRender = function () {
  58367. if (this._currentRefreshId === -1) {
  58368. this._currentRefreshId = 1;
  58369. return true;
  58370. }
  58371. if (this.refreshRate === this._currentRefreshId) {
  58372. this._currentRefreshId = 1;
  58373. return true;
  58374. }
  58375. this._currentRefreshId++;
  58376. return false;
  58377. };
  58378. RenderTargetTexture.prototype.getRenderSize = function () {
  58379. if (this._size.width) {
  58380. return this._size.width;
  58381. }
  58382. return this._size;
  58383. };
  58384. RenderTargetTexture.prototype.getRenderWidth = function () {
  58385. if (this._size.width) {
  58386. return this._size.width;
  58387. }
  58388. return this._size;
  58389. };
  58390. RenderTargetTexture.prototype.getRenderHeight = function () {
  58391. if (this._size.width) {
  58392. return this._size.height;
  58393. }
  58394. return this._size;
  58395. };
  58396. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58397. get: function () {
  58398. return true;
  58399. },
  58400. enumerable: true,
  58401. configurable: true
  58402. });
  58403. RenderTargetTexture.prototype.scale = function (ratio) {
  58404. var newSize = this.getRenderSize() * ratio;
  58405. this.resize(newSize);
  58406. };
  58407. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58408. if (this.isCube) {
  58409. return this._textureMatrix;
  58410. }
  58411. return _super.prototype.getReflectionTextureMatrix.call(this);
  58412. };
  58413. RenderTargetTexture.prototype.resize = function (size) {
  58414. this.releaseInternalTexture();
  58415. var scene = this.getScene();
  58416. if (!scene) {
  58417. return;
  58418. }
  58419. this._processSizeParameter(size);
  58420. if (this.isCube) {
  58421. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58422. }
  58423. else {
  58424. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58425. }
  58426. };
  58427. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58428. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58429. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58430. var scene = this.getScene();
  58431. if (!scene) {
  58432. return;
  58433. }
  58434. var engine = scene.getEngine();
  58435. if (this.useCameraPostProcesses !== undefined) {
  58436. useCameraPostProcess = this.useCameraPostProcesses;
  58437. }
  58438. if (this._waitingRenderList) {
  58439. this.renderList = [];
  58440. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58441. var id = this._waitingRenderList[index];
  58442. var mesh_1 = scene.getMeshByID(id);
  58443. if (mesh_1) {
  58444. this.renderList.push(mesh_1);
  58445. }
  58446. }
  58447. delete this._waitingRenderList;
  58448. }
  58449. // Is predicate defined?
  58450. if (this.renderListPredicate) {
  58451. if (this.renderList) {
  58452. this.renderList.splice(0); // Clear previous renderList
  58453. }
  58454. else {
  58455. this.renderList = [];
  58456. }
  58457. var scene = this.getScene();
  58458. if (!scene) {
  58459. return;
  58460. }
  58461. var sceneMeshes = scene.meshes;
  58462. for (var index = 0; index < sceneMeshes.length; index++) {
  58463. var mesh = sceneMeshes[index];
  58464. if (this.renderListPredicate(mesh)) {
  58465. this.renderList.push(mesh);
  58466. }
  58467. }
  58468. }
  58469. this.onBeforeBindObservable.notifyObservers(this);
  58470. // Set custom projection.
  58471. // Needs to be before binding to prevent changing the aspect ratio.
  58472. var camera;
  58473. if (this.activeCamera) {
  58474. camera = this.activeCamera;
  58475. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58476. if (this.activeCamera !== scene.activeCamera) {
  58477. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58478. }
  58479. }
  58480. else {
  58481. camera = scene.activeCamera;
  58482. if (camera) {
  58483. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58484. }
  58485. }
  58486. // Prepare renderingManager
  58487. this._renderingManager.reset();
  58488. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58489. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58490. var sceneRenderId = scene.getRenderId();
  58491. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58492. var mesh = currentRenderList[meshIndex];
  58493. if (mesh) {
  58494. if (!mesh.isReady()) {
  58495. // Reset _currentRefreshId
  58496. this.resetRefreshCounter();
  58497. continue;
  58498. }
  58499. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58500. var isMasked = void 0;
  58501. if (!this.renderList && camera) {
  58502. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58503. }
  58504. else {
  58505. isMasked = false;
  58506. }
  58507. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58508. mesh._activate(sceneRenderId);
  58509. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58510. var subMesh = mesh.subMeshes[subIndex];
  58511. scene._activeIndices.addCount(subMesh.indexCount, false);
  58512. this._renderingManager.dispatch(subMesh, mesh);
  58513. }
  58514. }
  58515. }
  58516. }
  58517. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58518. var particleSystem = scene.particleSystems[particleIndex];
  58519. var emitter = particleSystem.emitter;
  58520. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58521. continue;
  58522. }
  58523. if (currentRenderList.indexOf(emitter) >= 0) {
  58524. this._renderingManager.dispatchParticles(particleSystem);
  58525. }
  58526. }
  58527. if (this.isCube) {
  58528. for (var face = 0; face < 6; face++) {
  58529. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58530. scene.incrementRenderId();
  58531. scene.resetCachedMaterial();
  58532. }
  58533. }
  58534. else {
  58535. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58536. }
  58537. this.onAfterUnbindObservable.notifyObservers(this);
  58538. if (scene.activeCamera) {
  58539. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58540. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58541. }
  58542. engine.setViewport(scene.activeCamera.viewport);
  58543. }
  58544. scene.resetCachedMaterial();
  58545. };
  58546. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58547. var minimum = 128;
  58548. var x = renderDimension * scale;
  58549. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58550. // Ensure we don't exceed the render dimension (while staying POT)
  58551. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58552. };
  58553. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58554. var _this = this;
  58555. if (!this._texture) {
  58556. return;
  58557. }
  58558. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58559. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58560. });
  58561. };
  58562. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58563. var scene = this.getScene();
  58564. if (!scene) {
  58565. return;
  58566. }
  58567. var engine = scene.getEngine();
  58568. if (!this._texture) {
  58569. return;
  58570. }
  58571. // Bind
  58572. if (this._postProcessManager) {
  58573. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58574. }
  58575. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58576. if (this._texture) {
  58577. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58578. }
  58579. }
  58580. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58581. // Clear
  58582. if (this.onClearObservable.hasObservers()) {
  58583. this.onClearObservable.notifyObservers(engine);
  58584. }
  58585. else {
  58586. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58587. }
  58588. if (!this._doNotChangeAspectRatio) {
  58589. scene.updateTransformMatrix(true);
  58590. }
  58591. // Render
  58592. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58593. if (this._postProcessManager) {
  58594. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58595. }
  58596. else if (useCameraPostProcess) {
  58597. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58598. }
  58599. if (!this._doNotChangeAspectRatio) {
  58600. scene.updateTransformMatrix(true);
  58601. }
  58602. // Dump ?
  58603. if (dumpForDebug) {
  58604. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58605. }
  58606. // Unbind
  58607. if (!this.isCube || faceIndex === 5) {
  58608. if (this.isCube) {
  58609. if (faceIndex === 5) {
  58610. engine.generateMipMapsForCubemap(this._texture);
  58611. }
  58612. }
  58613. this.unbindFrameBuffer(engine, faceIndex);
  58614. }
  58615. else {
  58616. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58617. }
  58618. };
  58619. /**
  58620. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58621. * This allowed control for front to back rendering or reversly depending of the special needs.
  58622. *
  58623. * @param renderingGroupId The rendering group id corresponding to its index
  58624. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58625. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58626. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58627. */
  58628. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58629. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58630. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58631. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58632. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58633. };
  58634. /**
  58635. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58636. *
  58637. * @param renderingGroupId The rendering group id corresponding to its index
  58638. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58639. */
  58640. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58641. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58642. };
  58643. RenderTargetTexture.prototype.clone = function () {
  58644. var textureSize = this.getSize();
  58645. 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);
  58646. // Base texture
  58647. newTexture.hasAlpha = this.hasAlpha;
  58648. newTexture.level = this.level;
  58649. // RenderTarget Texture
  58650. newTexture.coordinatesMode = this.coordinatesMode;
  58651. if (this.renderList) {
  58652. newTexture.renderList = this.renderList.slice(0);
  58653. }
  58654. return newTexture;
  58655. };
  58656. RenderTargetTexture.prototype.serialize = function () {
  58657. if (!this.name) {
  58658. return null;
  58659. }
  58660. var serializationObject = _super.prototype.serialize.call(this);
  58661. serializationObject.renderTargetSize = this.getRenderSize();
  58662. serializationObject.renderList = [];
  58663. if (this.renderList) {
  58664. for (var index = 0; index < this.renderList.length; index++) {
  58665. serializationObject.renderList.push(this.renderList[index].id);
  58666. }
  58667. }
  58668. return serializationObject;
  58669. };
  58670. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58671. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58672. var objBuffer = this.getInternalTexture();
  58673. var scene = this.getScene();
  58674. if (objBuffer && scene) {
  58675. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58676. }
  58677. };
  58678. RenderTargetTexture.prototype.dispose = function () {
  58679. if (this._postProcessManager) {
  58680. this._postProcessManager.dispose();
  58681. this._postProcessManager = null;
  58682. }
  58683. this.clearPostProcesses(true);
  58684. if (this._resizeObserver) {
  58685. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58686. this._resizeObserver = null;
  58687. }
  58688. this.renderList = null;
  58689. // Remove from custom render targets
  58690. var scene = this.getScene();
  58691. if (!scene) {
  58692. return;
  58693. }
  58694. var index = scene.customRenderTargets.indexOf(this);
  58695. if (index >= 0) {
  58696. scene.customRenderTargets.splice(index, 1);
  58697. }
  58698. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58699. var camera = _a[_i];
  58700. index = camera.customRenderTargets.indexOf(this);
  58701. if (index >= 0) {
  58702. camera.customRenderTargets.splice(index, 1);
  58703. }
  58704. }
  58705. _super.prototype.dispose.call(this);
  58706. };
  58707. RenderTargetTexture.prototype._rebuild = function () {
  58708. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58709. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58710. }
  58711. if (this._postProcessManager) {
  58712. this._postProcessManager._rebuild();
  58713. }
  58714. };
  58715. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58716. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58717. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58718. return RenderTargetTexture;
  58719. }(BABYLON.Texture));
  58720. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58721. })(BABYLON || (BABYLON = {}));
  58722. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58723. var BABYLON;
  58724. (function (BABYLON) {
  58725. ;
  58726. var MultiRenderTarget = /** @class */ (function (_super) {
  58727. __extends(MultiRenderTarget, _super);
  58728. function MultiRenderTarget(name, size, count, scene, options) {
  58729. var _this = this;
  58730. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58731. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58732. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58733. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58734. _this._engine = scene.getEngine();
  58735. if (!_this.isSupported) {
  58736. _this.dispose();
  58737. return;
  58738. }
  58739. var types = [];
  58740. var samplingModes = [];
  58741. for (var i = 0; i < count; i++) {
  58742. if (options && options.types && options.types[i] !== undefined) {
  58743. types.push(options.types[i]);
  58744. }
  58745. else {
  58746. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58747. }
  58748. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58749. samplingModes.push(options.samplingModes[i]);
  58750. }
  58751. else {
  58752. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58753. }
  58754. }
  58755. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58756. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58757. _this._size = size;
  58758. _this._multiRenderTargetOptions = {
  58759. samplingModes: samplingModes,
  58760. generateMipMaps: generateMipMaps,
  58761. generateDepthBuffer: generateDepthBuffer,
  58762. generateStencilBuffer: generateStencilBuffer,
  58763. generateDepthTexture: generateDepthTexture,
  58764. types: types,
  58765. textureCount: count
  58766. };
  58767. _this._createInternalTextures();
  58768. _this._createTextures();
  58769. return _this;
  58770. }
  58771. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58772. get: function () {
  58773. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58774. },
  58775. enumerable: true,
  58776. configurable: true
  58777. });
  58778. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58779. get: function () {
  58780. return this._textures;
  58781. },
  58782. enumerable: true,
  58783. configurable: true
  58784. });
  58785. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58786. get: function () {
  58787. return this._textures[this._textures.length - 1];
  58788. },
  58789. enumerable: true,
  58790. configurable: true
  58791. });
  58792. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58793. set: function (wrap) {
  58794. if (this._textures) {
  58795. for (var i = 0; i < this._textures.length; i++) {
  58796. this._textures[i].wrapU = wrap;
  58797. }
  58798. }
  58799. },
  58800. enumerable: true,
  58801. configurable: true
  58802. });
  58803. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58804. set: function (wrap) {
  58805. if (this._textures) {
  58806. for (var i = 0; i < this._textures.length; i++) {
  58807. this._textures[i].wrapV = wrap;
  58808. }
  58809. }
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. MultiRenderTarget.prototype._rebuild = function () {
  58815. this.releaseInternalTextures();
  58816. this._createInternalTextures();
  58817. for (var i = 0; i < this._internalTextures.length; i++) {
  58818. var texture = this._textures[i];
  58819. texture._texture = this._internalTextures[i];
  58820. }
  58821. // Keeps references to frame buffer and stencil/depth buffer
  58822. this._texture = this._internalTextures[0];
  58823. };
  58824. MultiRenderTarget.prototype._createInternalTextures = function () {
  58825. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58826. };
  58827. MultiRenderTarget.prototype._createTextures = function () {
  58828. this._textures = [];
  58829. for (var i = 0; i < this._internalTextures.length; i++) {
  58830. var texture = new BABYLON.Texture(null, this.getScene());
  58831. texture._texture = this._internalTextures[i];
  58832. this._textures.push(texture);
  58833. }
  58834. // Keeps references to frame buffer and stencil/depth buffer
  58835. this._texture = this._internalTextures[0];
  58836. };
  58837. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58838. get: function () {
  58839. return this._samples;
  58840. },
  58841. set: function (value) {
  58842. if (this._samples === value) {
  58843. return;
  58844. }
  58845. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. MultiRenderTarget.prototype.resize = function (size) {
  58851. this.releaseInternalTextures();
  58852. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58853. this._createInternalTextures();
  58854. };
  58855. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58856. var _this = this;
  58857. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58858. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58859. });
  58860. };
  58861. MultiRenderTarget.prototype.dispose = function () {
  58862. this.releaseInternalTextures();
  58863. _super.prototype.dispose.call(this);
  58864. };
  58865. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58866. if (!this._internalTextures) {
  58867. return;
  58868. }
  58869. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58870. if (this._internalTextures[i] !== undefined) {
  58871. this._internalTextures[i].dispose();
  58872. this._internalTextures.splice(i, 1);
  58873. }
  58874. }
  58875. };
  58876. return MultiRenderTarget;
  58877. }(BABYLON.RenderTargetTexture));
  58878. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58879. })(BABYLON || (BABYLON = {}));
  58880. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58881. var BABYLON;
  58882. (function (BABYLON) {
  58883. var MirrorTexture = /** @class */ (function (_super) {
  58884. __extends(MirrorTexture, _super);
  58885. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58888. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58889. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58890. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58891. _this._transformMatrix = BABYLON.Matrix.Zero();
  58892. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58893. _this._adaptiveBlurKernel = 0;
  58894. _this._blurKernelX = 0;
  58895. _this._blurKernelY = 0;
  58896. _this._blurRatio = 1.0;
  58897. _this.ignoreCameraViewport = true;
  58898. _this.onBeforeRenderObservable.add(function () {
  58899. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58900. _this._savedViewMatrix = scene.getViewMatrix();
  58901. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58902. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58903. scene.clipPlane = _this.mirrorPlane;
  58904. scene.getEngine().cullBackFaces = false;
  58905. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58906. });
  58907. _this.onAfterRenderObservable.add(function () {
  58908. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58909. scene.getEngine().cullBackFaces = true;
  58910. scene._mirroredCameraPosition = null;
  58911. delete scene.clipPlane;
  58912. });
  58913. return _this;
  58914. }
  58915. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58916. get: function () {
  58917. return this._blurRatio;
  58918. },
  58919. set: function (value) {
  58920. if (this._blurRatio === value) {
  58921. return;
  58922. }
  58923. this._blurRatio = value;
  58924. this._preparePostProcesses();
  58925. },
  58926. enumerable: true,
  58927. configurable: true
  58928. });
  58929. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58930. set: function (value) {
  58931. this._adaptiveBlurKernel = value;
  58932. this._autoComputeBlurKernel();
  58933. },
  58934. enumerable: true,
  58935. configurable: true
  58936. });
  58937. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58938. set: function (value) {
  58939. this.blurKernelX = value;
  58940. this.blurKernelY = value;
  58941. },
  58942. enumerable: true,
  58943. configurable: true
  58944. });
  58945. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58946. get: function () {
  58947. return this._blurKernelX;
  58948. },
  58949. set: function (value) {
  58950. if (this._blurKernelX === value) {
  58951. return;
  58952. }
  58953. this._blurKernelX = value;
  58954. this._preparePostProcesses();
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58960. get: function () {
  58961. return this._blurKernelY;
  58962. },
  58963. set: function (value) {
  58964. if (this._blurKernelY === value) {
  58965. return;
  58966. }
  58967. this._blurKernelY = value;
  58968. this._preparePostProcesses();
  58969. },
  58970. enumerable: true,
  58971. configurable: true
  58972. });
  58973. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58974. var engine = this.getScene().getEngine();
  58975. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58976. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58977. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58978. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58979. };
  58980. MirrorTexture.prototype._onRatioRescale = function () {
  58981. if (this._sizeRatio) {
  58982. this.resize(this._initialSizeParameter);
  58983. if (!this._adaptiveBlurKernel) {
  58984. this._preparePostProcesses();
  58985. }
  58986. }
  58987. if (this._adaptiveBlurKernel) {
  58988. this._autoComputeBlurKernel();
  58989. }
  58990. };
  58991. MirrorTexture.prototype._preparePostProcesses = function () {
  58992. this.clearPostProcesses(true);
  58993. if (this._blurKernelX && this._blurKernelY) {
  58994. var engine = this.getScene().getEngine();
  58995. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58996. 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);
  58997. this._blurX.autoClear = false;
  58998. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58999. this._blurX.inputTexture = this._texture;
  59000. }
  59001. else {
  59002. this._blurX.alwaysForcePOT = true;
  59003. }
  59004. 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);
  59005. this._blurY.autoClear = false;
  59006. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59007. this.addPostProcess(this._blurX);
  59008. this.addPostProcess(this._blurY);
  59009. }
  59010. else {
  59011. if (this._blurY) {
  59012. this.removePostProcess(this._blurY);
  59013. this._blurY.dispose();
  59014. this._blurY = null;
  59015. }
  59016. if (this._blurX) {
  59017. this.removePostProcess(this._blurX);
  59018. this._blurX.dispose();
  59019. this._blurX = null;
  59020. }
  59021. }
  59022. };
  59023. MirrorTexture.prototype.clone = function () {
  59024. var scene = this.getScene();
  59025. if (!scene) {
  59026. return this;
  59027. }
  59028. var textureSize = this.getSize();
  59029. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59030. // Base texture
  59031. newTexture.hasAlpha = this.hasAlpha;
  59032. newTexture.level = this.level;
  59033. // Mirror Texture
  59034. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59035. if (this.renderList) {
  59036. newTexture.renderList = this.renderList.slice(0);
  59037. }
  59038. return newTexture;
  59039. };
  59040. MirrorTexture.prototype.serialize = function () {
  59041. if (!this.name) {
  59042. return null;
  59043. }
  59044. var serializationObject = _super.prototype.serialize.call(this);
  59045. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59046. return serializationObject;
  59047. };
  59048. return MirrorTexture;
  59049. }(BABYLON.RenderTargetTexture));
  59050. BABYLON.MirrorTexture = MirrorTexture;
  59051. })(BABYLON || (BABYLON = {}));
  59052. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59053. var BABYLON;
  59054. (function (BABYLON) {
  59055. /**
  59056. * Creates a refraction texture used by refraction channel of the standard material.
  59057. * @param name the texture name
  59058. * @param size size of the underlying texture
  59059. * @param scene root scene
  59060. */
  59061. var RefractionTexture = /** @class */ (function (_super) {
  59062. __extends(RefractionTexture, _super);
  59063. function RefractionTexture(name, size, scene, generateMipMaps) {
  59064. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59065. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59066. _this.depth = 2.0;
  59067. _this.onBeforeRenderObservable.add(function () {
  59068. scene.clipPlane = _this.refractionPlane;
  59069. });
  59070. _this.onAfterRenderObservable.add(function () {
  59071. delete scene.clipPlane;
  59072. });
  59073. return _this;
  59074. }
  59075. RefractionTexture.prototype.clone = function () {
  59076. var scene = this.getScene();
  59077. if (!scene) {
  59078. return this;
  59079. }
  59080. var textureSize = this.getSize();
  59081. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59082. // Base texture
  59083. newTexture.hasAlpha = this.hasAlpha;
  59084. newTexture.level = this.level;
  59085. // Refraction Texture
  59086. newTexture.refractionPlane = this.refractionPlane.clone();
  59087. if (this.renderList) {
  59088. newTexture.renderList = this.renderList.slice(0);
  59089. }
  59090. newTexture.depth = this.depth;
  59091. return newTexture;
  59092. };
  59093. RefractionTexture.prototype.serialize = function () {
  59094. if (!this.name) {
  59095. return null;
  59096. }
  59097. var serializationObject = _super.prototype.serialize.call(this);
  59098. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59099. serializationObject.depth = this.depth;
  59100. return serializationObject;
  59101. };
  59102. return RefractionTexture;
  59103. }(BABYLON.RenderTargetTexture));
  59104. BABYLON.RefractionTexture = RefractionTexture;
  59105. })(BABYLON || (BABYLON = {}));
  59106. //# sourceMappingURL=babylon.refractionTexture.js.map
  59107. var BABYLON;
  59108. (function (BABYLON) {
  59109. var DynamicTexture = /** @class */ (function (_super) {
  59110. __extends(DynamicTexture, _super);
  59111. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59112. if (scene === void 0) { scene = null; }
  59113. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59114. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59115. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59116. _this.name = name;
  59117. _this._engine = _this.getScene().getEngine();
  59118. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59119. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59120. _this._generateMipMaps = generateMipMaps;
  59121. if (options.getContext) {
  59122. _this._canvas = options;
  59123. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59124. }
  59125. else {
  59126. _this._canvas = document.createElement("canvas");
  59127. if (options.width) {
  59128. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59129. }
  59130. else {
  59131. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59132. }
  59133. }
  59134. var textureSize = _this.getSize();
  59135. _this._canvas.width = textureSize.width;
  59136. _this._canvas.height = textureSize.height;
  59137. _this._context = _this._canvas.getContext("2d");
  59138. return _this;
  59139. }
  59140. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59141. get: function () {
  59142. return true;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. DynamicTexture.prototype._recreate = function (textureSize) {
  59148. this._canvas.width = textureSize.width;
  59149. this._canvas.height = textureSize.height;
  59150. this.releaseInternalTexture();
  59151. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59152. };
  59153. DynamicTexture.prototype.scale = function (ratio) {
  59154. var textureSize = this.getSize();
  59155. textureSize.width *= ratio;
  59156. textureSize.height *= ratio;
  59157. this._recreate(textureSize);
  59158. };
  59159. DynamicTexture.prototype.scaleTo = function (width, height) {
  59160. var textureSize = this.getSize();
  59161. textureSize.width = width;
  59162. textureSize.height = height;
  59163. this._recreate(textureSize);
  59164. };
  59165. DynamicTexture.prototype.getContext = function () {
  59166. return this._context;
  59167. };
  59168. DynamicTexture.prototype.clear = function () {
  59169. var size = this.getSize();
  59170. this._context.fillRect(0, 0, size.width, size.height);
  59171. };
  59172. DynamicTexture.prototype.update = function (invertY) {
  59173. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59174. };
  59175. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59176. if (update === void 0) { update = true; }
  59177. var size = this.getSize();
  59178. if (clearColor) {
  59179. this._context.fillStyle = clearColor;
  59180. this._context.fillRect(0, 0, size.width, size.height);
  59181. }
  59182. this._context.font = font;
  59183. if (x === null || x === undefined) {
  59184. var textSize = this._context.measureText(text);
  59185. x = (size.width - textSize.width) / 2;
  59186. }
  59187. if (y === null || y === undefined) {
  59188. var fontSize = parseInt((font.replace(/\D/g, '')));
  59189. ;
  59190. y = (size.height / 2) + (fontSize / 3.65);
  59191. }
  59192. this._context.fillStyle = color;
  59193. this._context.fillText(text, x, y);
  59194. if (update) {
  59195. this.update(invertY);
  59196. }
  59197. };
  59198. DynamicTexture.prototype.clone = function () {
  59199. var scene = this.getScene();
  59200. if (!scene) {
  59201. return this;
  59202. }
  59203. var textureSize = this.getSize();
  59204. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59205. // Base texture
  59206. newTexture.hasAlpha = this.hasAlpha;
  59207. newTexture.level = this.level;
  59208. // Dynamic Texture
  59209. newTexture.wrapU = this.wrapU;
  59210. newTexture.wrapV = this.wrapV;
  59211. return newTexture;
  59212. };
  59213. DynamicTexture.prototype._rebuild = function () {
  59214. this.update();
  59215. };
  59216. return DynamicTexture;
  59217. }(BABYLON.Texture));
  59218. BABYLON.DynamicTexture = DynamicTexture;
  59219. })(BABYLON || (BABYLON = {}));
  59220. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59221. var BABYLON;
  59222. (function (BABYLON) {
  59223. var VideoTexture = /** @class */ (function (_super) {
  59224. __extends(VideoTexture, _super);
  59225. /**
  59226. * Creates a video texture.
  59227. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59228. * @param {string | null} name optional name, will detect from video source, if not defined
  59229. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59230. * @param {BABYLON.Scene} scene is obviously the current scene.
  59231. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59232. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59233. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59234. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59235. */
  59236. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59237. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59238. if (invertY === void 0) { invertY = false; }
  59239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59240. if (settings === void 0) { settings = {
  59241. autoPlay: true,
  59242. loop: true,
  59243. autoUpdateTexture: true,
  59244. }; }
  59245. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59246. _this._createInternalTexture = function () {
  59247. if (_this._texture != null) {
  59248. return;
  59249. }
  59250. if (!_this._engine.needPOTTextures ||
  59251. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59252. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59253. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59254. }
  59255. else {
  59256. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59257. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59258. _this._generateMipMaps = false;
  59259. }
  59260. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59261. _this._texture.isReady = true;
  59262. _this._updateInternalTexture();
  59263. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59264. _this.onLoadObservable.notifyObservers(_this);
  59265. }
  59266. };
  59267. _this.reset = function () {
  59268. if (_this._texture == null) {
  59269. return;
  59270. }
  59271. _this._texture.dispose();
  59272. _this._texture = null;
  59273. };
  59274. _this._updateInternalTexture = function (e) {
  59275. if (_this._texture == null || !_this._texture.isReady) {
  59276. return;
  59277. }
  59278. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59279. return;
  59280. }
  59281. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59282. };
  59283. _this._engine = _this.getScene().getEngine();
  59284. _this._generateMipMaps = generateMipMaps;
  59285. _this._samplingMode = samplingMode;
  59286. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59287. _this.name = name || _this._getName(src);
  59288. _this.video = _this._getVideo(src);
  59289. if (settings.autoPlay !== undefined) {
  59290. _this.video.autoplay = settings.autoPlay;
  59291. }
  59292. if (settings.loop !== undefined) {
  59293. _this.video.loop = settings.loop;
  59294. }
  59295. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59296. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59297. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59298. _this.video.addEventListener("emptied", _this.reset);
  59299. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59300. _this._createInternalTexture();
  59301. }
  59302. return _this;
  59303. }
  59304. VideoTexture.prototype._getName = function (src) {
  59305. if (src instanceof HTMLVideoElement) {
  59306. return src.currentSrc;
  59307. }
  59308. if (typeof src === "object") {
  59309. return src.toString();
  59310. }
  59311. return src;
  59312. };
  59313. ;
  59314. VideoTexture.prototype._getVideo = function (src) {
  59315. if (src instanceof HTMLVideoElement) {
  59316. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59317. return src;
  59318. }
  59319. var video = document.createElement("video");
  59320. if (typeof src === "string") {
  59321. BABYLON.Tools.SetCorsBehavior(src, video);
  59322. video.src = src;
  59323. }
  59324. else {
  59325. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59326. src.forEach(function (url) {
  59327. var source = document.createElement("source");
  59328. source.src = url;
  59329. video.appendChild(source);
  59330. });
  59331. }
  59332. return video;
  59333. };
  59334. ;
  59335. /**
  59336. * Internal method to initiate `update`.
  59337. */
  59338. VideoTexture.prototype._rebuild = function () {
  59339. this.update();
  59340. };
  59341. /**
  59342. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59343. */
  59344. VideoTexture.prototype.update = function () {
  59345. if (!this.autoUpdateTexture) {
  59346. // Expecting user to call `updateTexture` manually
  59347. return;
  59348. }
  59349. this.updateTexture(true);
  59350. };
  59351. /**
  59352. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59353. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59354. */
  59355. VideoTexture.prototype.updateTexture = function (isVisible) {
  59356. if (!isVisible) {
  59357. return;
  59358. }
  59359. if (this.video.paused) {
  59360. return;
  59361. }
  59362. this._updateInternalTexture();
  59363. };
  59364. /**
  59365. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59366. * @param url New url.
  59367. */
  59368. VideoTexture.prototype.updateURL = function (url) {
  59369. this.video.src = url;
  59370. };
  59371. VideoTexture.prototype.dispose = function () {
  59372. _super.prototype.dispose.call(this);
  59373. this.video.removeEventListener("canplay", this._createInternalTexture);
  59374. this.video.removeEventListener("paused", this._updateInternalTexture);
  59375. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59376. this.video.removeEventListener("emptied", this.reset);
  59377. this.video.pause();
  59378. };
  59379. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59380. var video = document.createElement("video");
  59381. var constraintsDeviceId;
  59382. if (constraints && constraints.deviceId) {
  59383. constraintsDeviceId = {
  59384. exact: constraints.deviceId,
  59385. };
  59386. }
  59387. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59388. if (navigator.mediaDevices) {
  59389. navigator.mediaDevices.getUserMedia({ video: constraints })
  59390. .then(function (stream) {
  59391. if (video.mozSrcObject !== undefined) {
  59392. // hack for Firefox < 19
  59393. video.mozSrcObject = stream;
  59394. }
  59395. else {
  59396. video.srcObject = stream;
  59397. }
  59398. var onPlaying = function () {
  59399. if (onReady) {
  59400. onReady(new VideoTexture("video", video, scene, true, true));
  59401. }
  59402. video.removeEventListener("playing", onPlaying);
  59403. };
  59404. video.addEventListener("playing", onPlaying);
  59405. video.play();
  59406. })
  59407. .catch(function (err) {
  59408. BABYLON.Tools.Error(err.name);
  59409. });
  59410. }
  59411. else {
  59412. navigator.getUserMedia =
  59413. navigator.getUserMedia ||
  59414. navigator.webkitGetUserMedia ||
  59415. navigator.mozGetUserMedia ||
  59416. navigator.msGetUserMedia;
  59417. if (navigator.getUserMedia) {
  59418. navigator.getUserMedia({
  59419. video: {
  59420. deviceId: constraintsDeviceId,
  59421. width: {
  59422. min: (constraints && constraints.minWidth) || 256,
  59423. max: (constraints && constraints.maxWidth) || 640,
  59424. },
  59425. height: {
  59426. min: (constraints && constraints.minHeight) || 256,
  59427. max: (constraints && constraints.maxHeight) || 480,
  59428. },
  59429. },
  59430. }, function (stream) {
  59431. if (video.mozSrcObject !== undefined) {
  59432. // hack for Firefox < 19
  59433. video.mozSrcObject = stream;
  59434. }
  59435. else {
  59436. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59437. }
  59438. video.play();
  59439. if (onReady) {
  59440. onReady(new VideoTexture("video", video, scene, true, true));
  59441. }
  59442. }, function (e) {
  59443. BABYLON.Tools.Error(e.name);
  59444. });
  59445. }
  59446. }
  59447. };
  59448. return VideoTexture;
  59449. }(BABYLON.Texture));
  59450. BABYLON.VideoTexture = VideoTexture;
  59451. })(BABYLON || (BABYLON = {}));
  59452. //# sourceMappingURL=babylon.videoTexture.js.map
  59453. var BABYLON;
  59454. (function (BABYLON) {
  59455. var RawTexture = /** @class */ (function (_super) {
  59456. __extends(RawTexture, _super);
  59457. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59458. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59459. if (invertY === void 0) { invertY = false; }
  59460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59461. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59462. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59463. _this.format = format;
  59464. _this._engine = scene.getEngine();
  59465. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59466. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59467. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59468. return _this;
  59469. }
  59470. RawTexture.prototype.update = function (data) {
  59471. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59472. };
  59473. // Statics
  59474. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59476. if (invertY === void 0) { invertY = false; }
  59477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59478. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59479. };
  59480. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59481. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59482. if (invertY === void 0) { invertY = false; }
  59483. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59484. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59485. };
  59486. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59487. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59488. if (invertY === void 0) { invertY = false; }
  59489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59490. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59491. };
  59492. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59493. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59494. if (invertY === void 0) { invertY = false; }
  59495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59496. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59497. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59498. };
  59499. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59500. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59501. if (invertY === void 0) { invertY = false; }
  59502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59503. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59504. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59505. };
  59506. return RawTexture;
  59507. }(BABYLON.Texture));
  59508. BABYLON.RawTexture = RawTexture;
  59509. })(BABYLON || (BABYLON = {}));
  59510. //# sourceMappingURL=babylon.rawTexture.js.map
  59511. var BABYLON;
  59512. (function (BABYLON) {
  59513. /**
  59514. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59515. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59516. */
  59517. var PostProcess = /** @class */ (function () {
  59518. /**
  59519. * Creates a new instance of @see PostProcess
  59520. * @param name The name of the PostProcess.
  59521. * @param fragmentUrl The url of the fragment shader to be used.
  59522. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59523. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59524. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59525. * @param camera The camera to apply the render pass to.
  59526. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59527. * @param engine The engine which the post process will be applied. (default: current engine)
  59528. * @param reusable If the post process can be reused on the same frame. (default: false)
  59529. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59530. * @param textureType Type of textures used when performing the post process. (default: 0)
  59531. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59532. * @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
  59533. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59534. */
  59535. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59537. if (defines === void 0) { defines = null; }
  59538. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59539. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59540. if (blockCompilation === void 0) { blockCompilation = false; }
  59541. this.name = name;
  59542. /**
  59543. * Width of the texture to apply the post process on
  59544. */
  59545. this.width = -1;
  59546. /**
  59547. * Height of the texture to apply the post process on
  59548. */
  59549. this.height = -1;
  59550. /**
  59551. * If the buffer needs to be cleared before applying the post process. (default: true)
  59552. * Should be set to false if shader will overwrite all previous pixels.
  59553. */
  59554. this.autoClear = true;
  59555. /**
  59556. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59557. */
  59558. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59559. /**
  59560. * Animations to be used for the post processing
  59561. */
  59562. this.animations = new Array();
  59563. /**
  59564. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59565. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59566. */
  59567. this.enablePixelPerfectMode = false;
  59568. /**
  59569. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59570. */
  59571. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59572. /**
  59573. * Force textures to be a power of two (default: false)
  59574. */
  59575. this.alwaysForcePOT = false;
  59576. /**
  59577. * Number of sample textures (default: 1)
  59578. */
  59579. this.samples = 1;
  59580. /**
  59581. * Modify the scale of the post process to be the same as the viewport (default: false)
  59582. */
  59583. this.adaptScaleToCurrentViewport = false;
  59584. this._reusable = false;
  59585. /**
  59586. * Smart array of input and output textures for the post process.
  59587. */
  59588. this._textures = new BABYLON.SmartArray(2);
  59589. /**
  59590. * The index in _textures that corresponds to the output texture.
  59591. */
  59592. this._currentRenderTextureInd = 0;
  59593. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59594. this._texelSize = BABYLON.Vector2.Zero();
  59595. // Events
  59596. /**
  59597. * An event triggered when the postprocess is activated.
  59598. * @type {BABYLON.Observable}
  59599. */
  59600. this.onActivateObservable = new BABYLON.Observable();
  59601. /**
  59602. * An event triggered when the postprocess changes its size.
  59603. * @type {BABYLON.Observable}
  59604. */
  59605. this.onSizeChangedObservable = new BABYLON.Observable();
  59606. /**
  59607. * An event triggered when the postprocess applies its effect.
  59608. * @type {BABYLON.Observable}
  59609. */
  59610. this.onApplyObservable = new BABYLON.Observable();
  59611. /**
  59612. * An event triggered before rendering the postprocess
  59613. * @type {BABYLON.Observable}
  59614. */
  59615. this.onBeforeRenderObservable = new BABYLON.Observable();
  59616. /**
  59617. * An event triggered after rendering the postprocess
  59618. * @type {BABYLON.Observable}
  59619. */
  59620. this.onAfterRenderObservable = new BABYLON.Observable();
  59621. if (camera != null) {
  59622. this._camera = camera;
  59623. this._scene = camera.getScene();
  59624. camera.attachPostProcess(this);
  59625. this._engine = this._scene.getEngine();
  59626. this._scene.postProcesses.push(this);
  59627. }
  59628. else if (engine) {
  59629. this._engine = engine;
  59630. this._engine.postProcesses.push(this);
  59631. }
  59632. this._options = options;
  59633. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59634. this._reusable = reusable || false;
  59635. this._textureType = textureType;
  59636. this._samplers = samplers || [];
  59637. this._samplers.push("textureSampler");
  59638. this._fragmentUrl = fragmentUrl;
  59639. this._vertexUrl = vertexUrl;
  59640. this._parameters = parameters || [];
  59641. this._parameters.push("scale");
  59642. this._indexParameters = indexParameters;
  59643. if (!blockCompilation) {
  59644. this.updateEffect(defines);
  59645. }
  59646. }
  59647. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59648. /**
  59649. * A function that is added to the onActivateObservable
  59650. */
  59651. set: function (callback) {
  59652. if (this._onActivateObserver) {
  59653. this.onActivateObservable.remove(this._onActivateObserver);
  59654. }
  59655. if (callback) {
  59656. this._onActivateObserver = this.onActivateObservable.add(callback);
  59657. }
  59658. },
  59659. enumerable: true,
  59660. configurable: true
  59661. });
  59662. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59663. /**
  59664. * A function that is added to the onSizeChangedObservable
  59665. */
  59666. set: function (callback) {
  59667. if (this._onSizeChangedObserver) {
  59668. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59669. }
  59670. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(PostProcess.prototype, "onApply", {
  59676. /**
  59677. * A function that is added to the onApplyObservable
  59678. */
  59679. set: function (callback) {
  59680. if (this._onApplyObserver) {
  59681. this.onApplyObservable.remove(this._onApplyObserver);
  59682. }
  59683. this._onApplyObserver = this.onApplyObservable.add(callback);
  59684. },
  59685. enumerable: true,
  59686. configurable: true
  59687. });
  59688. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59689. /**
  59690. * A function that is added to the onBeforeRenderObservable
  59691. */
  59692. set: function (callback) {
  59693. if (this._onBeforeRenderObserver) {
  59694. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59695. }
  59696. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59697. },
  59698. enumerable: true,
  59699. configurable: true
  59700. });
  59701. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59702. /**
  59703. * A function that is added to the onAfterRenderObservable
  59704. */
  59705. set: function (callback) {
  59706. if (this._onAfterRenderObserver) {
  59707. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59708. }
  59709. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59715. /**
  59716. * 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
  59717. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59718. */
  59719. get: function () {
  59720. return this._textures.data[this._currentRenderTextureInd];
  59721. },
  59722. set: function (value) {
  59723. this._forcedOutputTexture = value;
  59724. },
  59725. enumerable: true,
  59726. configurable: true
  59727. });
  59728. /**
  59729. * Gets the camera which post process is applied to.
  59730. * @returns The camera the post process is applied to.
  59731. */
  59732. PostProcess.prototype.getCamera = function () {
  59733. return this._camera;
  59734. };
  59735. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59736. /**
  59737. * Gets the texel size of the postprocess.
  59738. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59739. */
  59740. get: function () {
  59741. if (this._shareOutputWithPostProcess) {
  59742. return this._shareOutputWithPostProcess.texelSize;
  59743. }
  59744. if (this._forcedOutputTexture) {
  59745. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59746. }
  59747. return this._texelSize;
  59748. },
  59749. enumerable: true,
  59750. configurable: true
  59751. });
  59752. /**
  59753. * Gets the engine which this post process belongs to.
  59754. * @returns The engine the post process was enabled with.
  59755. */
  59756. PostProcess.prototype.getEngine = function () {
  59757. return this._engine;
  59758. };
  59759. /**
  59760. * The effect that is created when initializing the post process.
  59761. * @returns The created effect corrisponding the the postprocess.
  59762. */
  59763. PostProcess.prototype.getEffect = function () {
  59764. return this._effect;
  59765. };
  59766. /**
  59767. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59768. * @param postProcess The post process to share the output with.
  59769. * @returns This post process.
  59770. */
  59771. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59772. this._disposeTextures();
  59773. this._shareOutputWithPostProcess = postProcess;
  59774. return this;
  59775. };
  59776. /**
  59777. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59778. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59779. */
  59780. PostProcess.prototype.useOwnOutput = function () {
  59781. if (this._textures.length == 0) {
  59782. this._textures = new BABYLON.SmartArray(2);
  59783. }
  59784. this._shareOutputWithPostProcess = null;
  59785. };
  59786. /**
  59787. * Updates the effect with the current post process compile time values and recompiles the shader.
  59788. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59789. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59790. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59791. * @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
  59792. * @param onCompiled Called when the shader has been compiled.
  59793. * @param onError Called if there is an error when compiling a shader.
  59794. */
  59795. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59796. if (defines === void 0) { defines = null; }
  59797. if (uniforms === void 0) { uniforms = null; }
  59798. if (samplers === void 0) { samplers = null; }
  59799. 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);
  59800. };
  59801. /**
  59802. * The post process is reusable if it can be used multiple times within one frame.
  59803. * @returns If the post process is reusable
  59804. */
  59805. PostProcess.prototype.isReusable = function () {
  59806. return this._reusable;
  59807. };
  59808. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59809. PostProcess.prototype.markTextureDirty = function () {
  59810. this.width = -1;
  59811. };
  59812. /**
  59813. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59814. * 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.
  59815. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59816. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59817. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59818. */
  59819. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59820. var _this = this;
  59821. if (sourceTexture === void 0) { sourceTexture = null; }
  59822. camera = camera || this._camera;
  59823. var scene = camera.getScene();
  59824. var engine = scene.getEngine();
  59825. var maxSize = engine.getCaps().maxTextureSize;
  59826. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59827. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59828. // 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
  59829. var webVRCamera = camera.parent;
  59830. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59831. requiredWidth /= 2;
  59832. }
  59833. var desiredWidth = (this._options.width || requiredWidth);
  59834. var desiredHeight = this._options.height || requiredHeight;
  59835. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59836. if (this.adaptScaleToCurrentViewport) {
  59837. var currentViewport = engine.currentViewport;
  59838. if (currentViewport) {
  59839. desiredWidth *= currentViewport.width;
  59840. desiredHeight *= currentViewport.height;
  59841. }
  59842. }
  59843. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59844. if (!this._options.width) {
  59845. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59846. }
  59847. if (!this._options.height) {
  59848. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59849. }
  59850. }
  59851. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59852. if (this._textures.length > 0) {
  59853. for (var i = 0; i < this._textures.length; i++) {
  59854. this._engine._releaseTexture(this._textures.data[i]);
  59855. }
  59856. this._textures.reset();
  59857. }
  59858. this.width = desiredWidth;
  59859. this.height = desiredHeight;
  59860. var textureSize = { width: this.width, height: this.height };
  59861. var textureOptions = {
  59862. generateMipMaps: false,
  59863. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59864. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59865. samplingMode: this.renderTargetSamplingMode,
  59866. type: this._textureType
  59867. };
  59868. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59869. if (this._reusable) {
  59870. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59871. }
  59872. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59873. this.onSizeChangedObservable.notifyObservers(this);
  59874. }
  59875. this._textures.forEach(function (texture) {
  59876. if (texture.samples !== _this.samples) {
  59877. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59878. }
  59879. });
  59880. }
  59881. var target;
  59882. if (this._shareOutputWithPostProcess) {
  59883. target = this._shareOutputWithPostProcess.inputTexture;
  59884. }
  59885. else if (this._forcedOutputTexture) {
  59886. target = this._forcedOutputTexture;
  59887. this.width = this._forcedOutputTexture.width;
  59888. this.height = this._forcedOutputTexture.height;
  59889. }
  59890. else {
  59891. target = this.inputTexture;
  59892. }
  59893. // Bind the input of this post process to be used as the output of the previous post process.
  59894. if (this.enablePixelPerfectMode) {
  59895. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59896. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59897. }
  59898. else {
  59899. this._scaleRatio.copyFromFloats(1, 1);
  59900. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59901. }
  59902. this.onActivateObservable.notifyObservers(camera);
  59903. // Clear
  59904. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59905. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59906. }
  59907. if (this._reusable) {
  59908. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59909. }
  59910. };
  59911. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59912. /**
  59913. * If the post process is supported.
  59914. */
  59915. get: function () {
  59916. return this._effect.isSupported;
  59917. },
  59918. enumerable: true,
  59919. configurable: true
  59920. });
  59921. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59922. /**
  59923. * The aspect ratio of the output texture.
  59924. */
  59925. get: function () {
  59926. if (this._shareOutputWithPostProcess) {
  59927. return this._shareOutputWithPostProcess.aspectRatio;
  59928. }
  59929. if (this._forcedOutputTexture) {
  59930. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59931. }
  59932. return this.width / this.height;
  59933. },
  59934. enumerable: true,
  59935. configurable: true
  59936. });
  59937. /**
  59938. * Get a value indicating if the post-process is ready to be used
  59939. * @returns true if the post-process is ready (shader is compiled)
  59940. */
  59941. PostProcess.prototype.isReady = function () {
  59942. return this._effect && this._effect.isReady();
  59943. };
  59944. /**
  59945. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59946. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59947. */
  59948. PostProcess.prototype.apply = function () {
  59949. // Check
  59950. if (!this._effect || !this._effect.isReady())
  59951. return null;
  59952. // States
  59953. this._engine.enableEffect(this._effect);
  59954. this._engine.setState(false);
  59955. this._engine.setDepthBuffer(false);
  59956. this._engine.setDepthWrite(false);
  59957. // Alpha
  59958. this._engine.setAlphaMode(this.alphaMode);
  59959. if (this.alphaConstants) {
  59960. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59961. }
  59962. // Bind the output texture of the preivous post process as the input to this post process.
  59963. var source;
  59964. if (this._shareOutputWithPostProcess) {
  59965. source = this._shareOutputWithPostProcess.inputTexture;
  59966. }
  59967. else if (this._forcedOutputTexture) {
  59968. source = this._forcedOutputTexture;
  59969. }
  59970. else {
  59971. source = this.inputTexture;
  59972. }
  59973. this._effect._bindTexture("textureSampler", source);
  59974. // Parameters
  59975. this._effect.setVector2("scale", this._scaleRatio);
  59976. this.onApplyObservable.notifyObservers(this._effect);
  59977. return this._effect;
  59978. };
  59979. PostProcess.prototype._disposeTextures = function () {
  59980. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59981. return;
  59982. }
  59983. if (this._textures.length > 0) {
  59984. for (var i = 0; i < this._textures.length; i++) {
  59985. this._engine._releaseTexture(this._textures.data[i]);
  59986. }
  59987. }
  59988. this._textures.dispose();
  59989. };
  59990. /**
  59991. * Disposes the post process.
  59992. * @param camera The camera to dispose the post process on.
  59993. */
  59994. PostProcess.prototype.dispose = function (camera) {
  59995. camera = camera || this._camera;
  59996. this._disposeTextures();
  59997. if (this._scene) {
  59998. var index_1 = this._scene.postProcesses.indexOf(this);
  59999. if (index_1 !== -1) {
  60000. this._scene.postProcesses.splice(index_1, 1);
  60001. }
  60002. }
  60003. else {
  60004. var index_2 = this._engine.postProcesses.indexOf(this);
  60005. if (index_2 !== -1) {
  60006. this._engine.postProcesses.splice(index_2, 1);
  60007. }
  60008. }
  60009. if (!camera) {
  60010. return;
  60011. }
  60012. camera.detachPostProcess(this);
  60013. var index = camera._postProcesses.indexOf(this);
  60014. if (index === 0 && camera._postProcesses.length > 0) {
  60015. this._camera._postProcesses[0].markTextureDirty();
  60016. }
  60017. this.onActivateObservable.clear();
  60018. this.onAfterRenderObservable.clear();
  60019. this.onApplyObservable.clear();
  60020. this.onBeforeRenderObservable.clear();
  60021. this.onSizeChangedObservable.clear();
  60022. };
  60023. return PostProcess;
  60024. }());
  60025. BABYLON.PostProcess = PostProcess;
  60026. })(BABYLON || (BABYLON = {}));
  60027. //# sourceMappingURL=babylon.postProcess.js.map
  60028. var BABYLON;
  60029. (function (BABYLON) {
  60030. var PassPostProcess = /** @class */ (function (_super) {
  60031. __extends(PassPostProcess, _super);
  60032. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60033. if (camera === void 0) { camera = null; }
  60034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60035. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  60036. }
  60037. return PassPostProcess;
  60038. }(BABYLON.PostProcess));
  60039. BABYLON.PassPostProcess = PassPostProcess;
  60040. })(BABYLON || (BABYLON = {}));
  60041. //# sourceMappingURL=babylon.passPostProcess.js.map
  60042. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60043. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60044. s = arguments[i];
  60045. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60046. t[p] = s[p];
  60047. }
  60048. return t;
  60049. };
  60050. var BABYLON;
  60051. (function (BABYLON) {
  60052. /**
  60053. * Default implementation of @see IShadowGenerator.
  60054. * This is the main object responsible of generating shadows in the framework.
  60055. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60056. */
  60057. var ShadowGenerator = /** @class */ (function () {
  60058. /**
  60059. * Creates a ShadowGenerator object.
  60060. * A ShadowGenerator is the required tool to use the shadows.
  60061. * Each light casting shadows needs to use its own ShadowGenerator.
  60062. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60063. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60064. * @param light The light object generating the shadows.
  60065. * @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.
  60066. */
  60067. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60068. this._bias = 0.00005;
  60069. this._blurBoxOffset = 1;
  60070. this._blurScale = 2;
  60071. this._blurKernel = 1;
  60072. this._useKernelBlur = false;
  60073. this._filter = ShadowGenerator.FILTER_NONE;
  60074. this._darkness = 0;
  60075. this._transparencyShadow = false;
  60076. /**
  60077. * Controls the extent to which the shadows fade out at the edge of the frustum
  60078. * Used only by directionals and spots
  60079. */
  60080. this.frustumEdgeFalloff = 0;
  60081. /**
  60082. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60083. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60084. * It might on the other hand introduce peter panning.
  60085. */
  60086. this.forceBackFacesOnly = false;
  60087. this._lightDirection = BABYLON.Vector3.Zero();
  60088. this._viewMatrix = BABYLON.Matrix.Zero();
  60089. this._projectionMatrix = BABYLON.Matrix.Zero();
  60090. this._transformMatrix = BABYLON.Matrix.Zero();
  60091. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60092. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60093. this._currentFaceIndex = 0;
  60094. this._currentFaceIndexCache = 0;
  60095. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60096. this._mapSize = mapSize;
  60097. this._light = light;
  60098. this._scene = light.getScene();
  60099. light._shadowGenerator = this;
  60100. // Texture type fallback from float to int if not supported.
  60101. var caps = this._scene.getEngine().getCaps();
  60102. if (!useFullFloatFirst) {
  60103. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60104. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60105. }
  60106. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60107. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60108. }
  60109. else {
  60110. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60111. }
  60112. }
  60113. else {
  60114. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60115. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60116. }
  60117. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60118. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60119. }
  60120. else {
  60121. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60122. }
  60123. }
  60124. this._initializeGenerator();
  60125. }
  60126. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60127. /**
  60128. * Shadow generator mode None: no filtering applied.
  60129. */
  60130. get: function () {
  60131. return ShadowGenerator._FILTER_NONE;
  60132. },
  60133. enumerable: true,
  60134. configurable: true
  60135. });
  60136. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60137. /**
  60138. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60139. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60140. */
  60141. get: function () {
  60142. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60148. /**
  60149. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60150. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60151. */
  60152. get: function () {
  60153. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60154. },
  60155. enumerable: true,
  60156. configurable: true
  60157. });
  60158. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60159. /**
  60160. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60161. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60162. */
  60163. get: function () {
  60164. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60165. },
  60166. enumerable: true,
  60167. configurable: true
  60168. });
  60169. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60170. /**
  60171. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60172. * edge artifacts on steep falloff.
  60173. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60174. */
  60175. get: function () {
  60176. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60177. },
  60178. enumerable: true,
  60179. configurable: true
  60180. });
  60181. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60182. /**
  60183. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60184. * edge artifacts on steep falloff.
  60185. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60186. */
  60187. get: function () {
  60188. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60189. },
  60190. enumerable: true,
  60191. configurable: true
  60192. });
  60193. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60194. /**
  60195. * Gets the bias: offset applied on the depth preventing acnea.
  60196. */
  60197. get: function () {
  60198. return this._bias;
  60199. },
  60200. /**
  60201. * Sets the bias: offset applied on the depth preventing acnea.
  60202. */
  60203. set: function (bias) {
  60204. this._bias = bias;
  60205. },
  60206. enumerable: true,
  60207. configurable: true
  60208. });
  60209. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60210. /**
  60211. * Gets the blur box offset: offset applied during the blur pass.
  60212. * Only usefull if useKernelBlur = false
  60213. */
  60214. get: function () {
  60215. return this._blurBoxOffset;
  60216. },
  60217. /**
  60218. * Sets the blur box offset: offset applied during the blur pass.
  60219. * Only usefull if useKernelBlur = false
  60220. */
  60221. set: function (value) {
  60222. if (this._blurBoxOffset === value) {
  60223. return;
  60224. }
  60225. this._blurBoxOffset = value;
  60226. this._disposeBlurPostProcesses();
  60227. },
  60228. enumerable: true,
  60229. configurable: true
  60230. });
  60231. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60232. /**
  60233. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60234. * 2 means half of the size.
  60235. */
  60236. get: function () {
  60237. return this._blurScale;
  60238. },
  60239. /**
  60240. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60241. * 2 means half of the size.
  60242. */
  60243. set: function (value) {
  60244. if (this._blurScale === value) {
  60245. return;
  60246. }
  60247. this._blurScale = value;
  60248. this._disposeBlurPostProcesses();
  60249. },
  60250. enumerable: true,
  60251. configurable: true
  60252. });
  60253. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60254. /**
  60255. * Gets the blur kernel: kernel size of the blur pass.
  60256. * Only usefull if useKernelBlur = true
  60257. */
  60258. get: function () {
  60259. return this._blurKernel;
  60260. },
  60261. /**
  60262. * Sets the blur kernel: kernel size of the blur pass.
  60263. * Only usefull if useKernelBlur = true
  60264. */
  60265. set: function (value) {
  60266. if (this._blurKernel === value) {
  60267. return;
  60268. }
  60269. this._blurKernel = value;
  60270. this._disposeBlurPostProcesses();
  60271. },
  60272. enumerable: true,
  60273. configurable: true
  60274. });
  60275. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60276. /**
  60277. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60278. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60279. */
  60280. get: function () {
  60281. return this._useKernelBlur;
  60282. },
  60283. /**
  60284. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60285. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60286. */
  60287. set: function (value) {
  60288. if (this._useKernelBlur === value) {
  60289. return;
  60290. }
  60291. this._useKernelBlur = value;
  60292. this._disposeBlurPostProcesses();
  60293. },
  60294. enumerable: true,
  60295. configurable: true
  60296. });
  60297. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60298. /**
  60299. * Gets the depth scale used in ESM mode.
  60300. */
  60301. get: function () {
  60302. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60303. },
  60304. /**
  60305. * Sets the depth scale used in ESM mode.
  60306. * This can override the scale stored on the light.
  60307. */
  60308. set: function (value) {
  60309. this._depthScale = value;
  60310. },
  60311. enumerable: true,
  60312. configurable: true
  60313. });
  60314. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60315. /**
  60316. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60317. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60318. */
  60319. get: function () {
  60320. return this._filter;
  60321. },
  60322. /**
  60323. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60324. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60325. */
  60326. set: function (value) {
  60327. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60328. if (this._light.needCube()) {
  60329. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60330. this.useExponentialShadowMap = true;
  60331. return;
  60332. }
  60333. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60334. this.useCloseExponentialShadowMap = true;
  60335. return;
  60336. }
  60337. }
  60338. if (this._filter === value) {
  60339. return;
  60340. }
  60341. this._filter = value;
  60342. this._disposeBlurPostProcesses();
  60343. this._applyFilterValues();
  60344. this._light._markMeshesAsLightDirty();
  60345. },
  60346. enumerable: true,
  60347. configurable: true
  60348. });
  60349. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60350. /**
  60351. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60352. */
  60353. get: function () {
  60354. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60355. },
  60356. /**
  60357. * Sets the current filter to Poisson Sampling aka PCF.
  60358. */
  60359. set: function (value) {
  60360. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60361. return;
  60362. }
  60363. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60364. },
  60365. enumerable: true,
  60366. configurable: true
  60367. });
  60368. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60369. /**
  60370. * Gets if the current filter is set to VSM.
  60371. * DEPRECATED. Should use useExponentialShadowMap instead.
  60372. */
  60373. get: function () {
  60374. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60375. return this.useExponentialShadowMap;
  60376. },
  60377. /**
  60378. * Sets the current filter is to VSM.
  60379. * DEPRECATED. Should use useExponentialShadowMap instead.
  60380. */
  60381. set: function (value) {
  60382. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60383. this.useExponentialShadowMap = value;
  60384. },
  60385. enumerable: true,
  60386. configurable: true
  60387. });
  60388. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60389. /**
  60390. * Gets if the current filter is set to blurred VSM.
  60391. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60392. */
  60393. get: function () {
  60394. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60395. return this.useBlurExponentialShadowMap;
  60396. },
  60397. /**
  60398. * Sets the current filter is to blurred VSM.
  60399. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60400. */
  60401. set: function (value) {
  60402. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60403. this.useBlurExponentialShadowMap = value;
  60404. },
  60405. enumerable: true,
  60406. configurable: true
  60407. });
  60408. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60409. /**
  60410. * Gets if the current filter is set to ESM.
  60411. */
  60412. get: function () {
  60413. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60414. },
  60415. /**
  60416. * Sets the current filter is to ESM.
  60417. */
  60418. set: function (value) {
  60419. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60420. return;
  60421. }
  60422. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60423. },
  60424. enumerable: true,
  60425. configurable: true
  60426. });
  60427. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60428. /**
  60429. * Gets if the current filter is set to filtered ESM.
  60430. */
  60431. get: function () {
  60432. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60433. },
  60434. /**
  60435. * Gets if the current filter is set to filtered ESM.
  60436. */
  60437. set: function (value) {
  60438. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60439. return;
  60440. }
  60441. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60442. },
  60443. enumerable: true,
  60444. configurable: true
  60445. });
  60446. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60447. /**
  60448. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60449. * exponential to prevent steep falloff artifacts).
  60450. */
  60451. get: function () {
  60452. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60453. },
  60454. /**
  60455. * Sets the current filter to "close ESM" (using the inverse of the
  60456. * exponential to prevent steep falloff artifacts).
  60457. */
  60458. set: function (value) {
  60459. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60460. return;
  60461. }
  60462. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60463. },
  60464. enumerable: true,
  60465. configurable: true
  60466. });
  60467. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60468. /**
  60469. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60470. * exponential to prevent steep falloff artifacts).
  60471. */
  60472. get: function () {
  60473. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60474. },
  60475. /**
  60476. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60477. * exponential to prevent steep falloff artifacts).
  60478. */
  60479. set: function (value) {
  60480. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60481. return;
  60482. }
  60483. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60484. },
  60485. enumerable: true,
  60486. configurable: true
  60487. });
  60488. /**
  60489. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60490. * 0 means strongest and 1 would means no shadow.
  60491. * @returns the darkness.
  60492. */
  60493. ShadowGenerator.prototype.getDarkness = function () {
  60494. return this._darkness;
  60495. };
  60496. /**
  60497. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60498. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60499. * @returns the shadow generator allowing fluent coding.
  60500. */
  60501. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60502. if (darkness >= 1.0)
  60503. this._darkness = 1.0;
  60504. else if (darkness <= 0.0)
  60505. this._darkness = 0.0;
  60506. else
  60507. this._darkness = darkness;
  60508. return this;
  60509. };
  60510. /**
  60511. * Sets the ability to have transparent shadow (boolean).
  60512. * @param transparent True if transparent else False
  60513. * @returns the shadow generator allowing fluent coding
  60514. */
  60515. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60516. this._transparencyShadow = transparent;
  60517. return this;
  60518. };
  60519. /**
  60520. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60521. * @returns The render target texture if present otherwise, null
  60522. */
  60523. ShadowGenerator.prototype.getShadowMap = function () {
  60524. return this._shadowMap;
  60525. };
  60526. /**
  60527. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60528. * @returns The render target texture if the shadow map is present otherwise, null
  60529. */
  60530. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60531. if (this._shadowMap2) {
  60532. return this._shadowMap2;
  60533. }
  60534. return this._shadowMap;
  60535. };
  60536. /**
  60537. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60538. * @param mesh Mesh to add
  60539. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60540. * @returns the Shadow Generator itself
  60541. */
  60542. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60543. if (includeDescendants === void 0) { includeDescendants = true; }
  60544. if (!this._shadowMap) {
  60545. return this;
  60546. }
  60547. if (!this._shadowMap.renderList) {
  60548. this._shadowMap.renderList = [];
  60549. }
  60550. this._shadowMap.renderList.push(mesh);
  60551. if (includeDescendants) {
  60552. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60553. }
  60554. return this;
  60555. var _a;
  60556. };
  60557. /**
  60558. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60559. * @param mesh Mesh to remove
  60560. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60561. * @returns the Shadow Generator itself
  60562. */
  60563. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60564. if (includeDescendants === void 0) { includeDescendants = true; }
  60565. if (!this._shadowMap || !this._shadowMap.renderList) {
  60566. return this;
  60567. }
  60568. var index = this._shadowMap.renderList.indexOf(mesh);
  60569. if (index !== -1) {
  60570. this._shadowMap.renderList.splice(index, 1);
  60571. }
  60572. if (includeDescendants) {
  60573. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60574. var child = _a[_i];
  60575. this.removeShadowCaster(child);
  60576. }
  60577. }
  60578. return this;
  60579. };
  60580. /**
  60581. * Returns the associated light object.
  60582. * @returns the light generating the shadow
  60583. */
  60584. ShadowGenerator.prototype.getLight = function () {
  60585. return this._light;
  60586. };
  60587. ShadowGenerator.prototype._initializeGenerator = function () {
  60588. this._light._markMeshesAsLightDirty();
  60589. this._initializeShadowMap();
  60590. };
  60591. ShadowGenerator.prototype._initializeShadowMap = function () {
  60592. var _this = this;
  60593. // Render target
  60594. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60595. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60596. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60597. this._shadowMap.anisotropicFilteringLevel = 1;
  60598. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60599. this._shadowMap.renderParticles = false;
  60600. this._shadowMap.ignoreCameraViewport = true;
  60601. // Record Face Index before render.
  60602. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60603. _this._currentFaceIndex = faceIndex;
  60604. });
  60605. // Custom render function.
  60606. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60607. // Blur if required afer render.
  60608. this._shadowMap.onAfterUnbindObservable.add(function () {
  60609. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60610. return;
  60611. }
  60612. var shadowMap = _this.getShadowMapForRendering();
  60613. if (shadowMap) {
  60614. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60615. }
  60616. });
  60617. // Clear according to the chosen filter.
  60618. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60619. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60620. this._shadowMap.onClearObservable.add(function (engine) {
  60621. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60622. engine.clear(zero, true, true, true);
  60623. }
  60624. else {
  60625. engine.clear(one, true, true, true);
  60626. }
  60627. });
  60628. };
  60629. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60630. var _this = this;
  60631. var engine = this._scene.getEngine();
  60632. var targetSize = this._mapSize / this.blurScale;
  60633. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60634. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60635. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60636. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60637. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60638. }
  60639. if (this.useKernelBlur) {
  60640. 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);
  60641. this._kernelBlurXPostprocess.width = targetSize;
  60642. this._kernelBlurXPostprocess.height = targetSize;
  60643. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60644. effect.setTexture("textureSampler", _this._shadowMap);
  60645. });
  60646. 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);
  60647. this._kernelBlurXPostprocess.autoClear = false;
  60648. this._kernelBlurYPostprocess.autoClear = false;
  60649. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60650. this._kernelBlurXPostprocess.packedFloat = true;
  60651. this._kernelBlurYPostprocess.packedFloat = true;
  60652. }
  60653. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60654. }
  60655. else {
  60656. 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);
  60657. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60658. effect.setFloat2("screenSize", targetSize, targetSize);
  60659. effect.setTexture("textureSampler", _this._shadowMap);
  60660. });
  60661. this._boxBlurPostprocess.autoClear = false;
  60662. this._blurPostProcesses = [this._boxBlurPostprocess];
  60663. }
  60664. };
  60665. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60666. var index;
  60667. var engine = this._scene.getEngine();
  60668. if (depthOnlySubMeshes.length) {
  60669. engine.setColorWrite(false);
  60670. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60671. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60672. }
  60673. engine.setColorWrite(true);
  60674. }
  60675. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60676. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60677. }
  60678. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60679. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60680. }
  60681. if (this._transparencyShadow) {
  60682. for (index = 0; index < transparentSubMeshes.length; index++) {
  60683. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60684. }
  60685. }
  60686. };
  60687. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60688. var _this = this;
  60689. var mesh = subMesh.getRenderingMesh();
  60690. var scene = this._scene;
  60691. var engine = scene.getEngine();
  60692. var material = subMesh.getMaterial();
  60693. if (!material) {
  60694. return;
  60695. }
  60696. // Culling
  60697. engine.setState(material.backFaceCulling);
  60698. // Managing instances
  60699. var batch = mesh._getInstancesRenderList(subMesh._id);
  60700. if (batch.mustReturn) {
  60701. return;
  60702. }
  60703. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60704. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60705. engine.enableEffect(this._effect);
  60706. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60707. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60708. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60709. this._effect.setVector3("lightPosition", this.getLight().position);
  60710. if (scene.activeCamera) {
  60711. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60712. }
  60713. // Alpha test
  60714. if (material && material.needAlphaTesting()) {
  60715. var alphaTexture = material.getAlphaTestTexture();
  60716. if (alphaTexture) {
  60717. this._effect.setTexture("diffuseSampler", alphaTexture);
  60718. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60719. }
  60720. }
  60721. // Bones
  60722. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60723. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60724. }
  60725. if (this.forceBackFacesOnly) {
  60726. engine.setState(true, 0, false, true);
  60727. }
  60728. // Draw
  60729. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60730. if (this.forceBackFacesOnly) {
  60731. engine.setState(true, 0, false, false);
  60732. }
  60733. }
  60734. else {
  60735. // Need to reset refresh rate of the shadowMap
  60736. if (this._shadowMap) {
  60737. this._shadowMap.resetRefreshCounter();
  60738. }
  60739. }
  60740. };
  60741. ShadowGenerator.prototype._applyFilterValues = function () {
  60742. if (!this._shadowMap) {
  60743. return;
  60744. }
  60745. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60746. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60747. }
  60748. else {
  60749. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60750. }
  60751. };
  60752. /**
  60753. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60754. * @param onCompiled Callback triggered at the and of the effects compilation
  60755. * @param options Sets of optional options forcing the compilation with different modes
  60756. */
  60757. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60758. var _this = this;
  60759. var localOptions = __assign({ useInstances: false }, options);
  60760. var shadowMap = this.getShadowMap();
  60761. if (!shadowMap) {
  60762. if (onCompiled) {
  60763. onCompiled(this);
  60764. }
  60765. return;
  60766. }
  60767. var renderList = shadowMap.renderList;
  60768. if (!renderList) {
  60769. if (onCompiled) {
  60770. onCompiled(this);
  60771. }
  60772. return;
  60773. }
  60774. var subMeshes = new Array();
  60775. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60776. var mesh = renderList_1[_i];
  60777. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60778. }
  60779. if (subMeshes.length === 0) {
  60780. if (onCompiled) {
  60781. onCompiled(this);
  60782. }
  60783. return;
  60784. }
  60785. var currentIndex = 0;
  60786. var checkReady = function () {
  60787. if (!_this._scene || !_this._scene.getEngine()) {
  60788. return;
  60789. }
  60790. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60791. currentIndex++;
  60792. if (currentIndex >= subMeshes.length) {
  60793. if (onCompiled) {
  60794. onCompiled(_this);
  60795. }
  60796. return;
  60797. }
  60798. }
  60799. setTimeout(checkReady, 16);
  60800. };
  60801. checkReady();
  60802. };
  60803. /**
  60804. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60805. * @param options Sets of optional options forcing the compilation with different modes
  60806. * @returns A promise that resolves when the compilation completes
  60807. */
  60808. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60809. var _this = this;
  60810. return new Promise(function (resolve) {
  60811. _this.forceCompilation(function () {
  60812. resolve();
  60813. }, options);
  60814. });
  60815. };
  60816. /**
  60817. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60818. * @param subMesh The submesh we want to render in the shadow map
  60819. * @param useInstances Defines wether will draw in the map using instances
  60820. * @returns true if ready otherwise, false
  60821. */
  60822. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60823. var defines = [];
  60824. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60825. defines.push("#define FLOAT");
  60826. }
  60827. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60828. defines.push("#define ESM");
  60829. }
  60830. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60831. var mesh = subMesh.getMesh();
  60832. var material = subMesh.getMaterial();
  60833. // Alpha test
  60834. if (material && material.needAlphaTesting()) {
  60835. var alphaTexture = material.getAlphaTestTexture();
  60836. if (alphaTexture) {
  60837. defines.push("#define ALPHATEST");
  60838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60839. attribs.push(BABYLON.VertexBuffer.UVKind);
  60840. defines.push("#define UV1");
  60841. }
  60842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60843. if (alphaTexture.coordinatesIndex === 1) {
  60844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60845. defines.push("#define UV2");
  60846. }
  60847. }
  60848. }
  60849. }
  60850. // Bones
  60851. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60854. if (mesh.numBoneInfluencers > 4) {
  60855. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60856. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60857. }
  60858. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60859. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60860. }
  60861. else {
  60862. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60863. }
  60864. // Instances
  60865. if (useInstances) {
  60866. defines.push("#define INSTANCES");
  60867. attribs.push("world0");
  60868. attribs.push("world1");
  60869. attribs.push("world2");
  60870. attribs.push("world3");
  60871. }
  60872. // Get correct effect
  60873. var join = defines.join("\n");
  60874. if (this._cachedDefines !== join) {
  60875. this._cachedDefines = join;
  60876. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60877. }
  60878. if (!this._effect.isReady()) {
  60879. return false;
  60880. }
  60881. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60882. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60883. this._initializeBlurRTTAndPostProcesses();
  60884. }
  60885. }
  60886. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60887. return false;
  60888. }
  60889. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60890. return false;
  60891. }
  60892. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60893. return false;
  60894. }
  60895. return true;
  60896. };
  60897. /**
  60898. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60899. * @param defines Defines of the material we want to update
  60900. * @param lightIndex Index of the light in the enabled light list of the material
  60901. */
  60902. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60903. var scene = this._scene;
  60904. var light = this._light;
  60905. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60906. return;
  60907. }
  60908. defines["SHADOW" + lightIndex] = true;
  60909. if (this.usePoissonSampling) {
  60910. defines["SHADOWPCF" + lightIndex] = true;
  60911. }
  60912. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60913. defines["SHADOWESM" + lightIndex] = true;
  60914. }
  60915. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60916. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60917. }
  60918. if (light.needCube()) {
  60919. defines["SHADOWCUBE" + lightIndex] = true;
  60920. }
  60921. };
  60922. /**
  60923. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60924. * defined in the generator but impacting the effect).
  60925. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60926. * @param effect The effect we are binfing the information for
  60927. */
  60928. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60929. var light = this._light;
  60930. var scene = this._scene;
  60931. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60932. return;
  60933. }
  60934. var camera = scene.activeCamera;
  60935. if (!camera) {
  60936. return;
  60937. }
  60938. var shadowMap = this.getShadowMap();
  60939. if (!shadowMap) {
  60940. return;
  60941. }
  60942. if (!light.needCube()) {
  60943. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60944. }
  60945. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60946. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60947. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60948. };
  60949. /**
  60950. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60951. * (eq to shadow prjection matrix * light transform matrix)
  60952. * @returns The transform matrix used to create the shadow map
  60953. */
  60954. ShadowGenerator.prototype.getTransformMatrix = function () {
  60955. var scene = this._scene;
  60956. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60957. return this._transformMatrix;
  60958. }
  60959. this._currentRenderID = scene.getRenderId();
  60960. this._currentFaceIndexCache = this._currentFaceIndex;
  60961. var lightPosition = this._light.position;
  60962. if (this._light.computeTransformedInformation()) {
  60963. lightPosition = this._light.transformedPosition;
  60964. }
  60965. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60966. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60967. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60968. }
  60969. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60970. this._cachedPosition.copyFrom(lightPosition);
  60971. this._cachedDirection.copyFrom(this._lightDirection);
  60972. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60973. var shadowMap = this.getShadowMap();
  60974. if (shadowMap) {
  60975. var renderList = shadowMap.renderList;
  60976. if (renderList) {
  60977. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60978. }
  60979. }
  60980. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60981. }
  60982. return this._transformMatrix;
  60983. };
  60984. /**
  60985. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60986. * Cube and 2D textures for instance.
  60987. */
  60988. ShadowGenerator.prototype.recreateShadowMap = function () {
  60989. var shadowMap = this._shadowMap;
  60990. if (!shadowMap) {
  60991. return;
  60992. }
  60993. // Track render list.
  60994. var renderList = shadowMap.renderList;
  60995. // Clean up existing data.
  60996. this._disposeRTTandPostProcesses();
  60997. // Reinitializes.
  60998. this._initializeGenerator();
  60999. // Reaffect the filter to ensure a correct fallback if necessary.
  61000. this.filter = this.filter;
  61001. // Reaffect the filter.
  61002. this._applyFilterValues();
  61003. // Reaffect Render List.
  61004. this._shadowMap.renderList = renderList;
  61005. };
  61006. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61007. if (this._shadowMap2) {
  61008. this._shadowMap2.dispose();
  61009. this._shadowMap2 = null;
  61010. }
  61011. if (this._boxBlurPostprocess) {
  61012. this._boxBlurPostprocess.dispose();
  61013. this._boxBlurPostprocess = null;
  61014. }
  61015. if (this._kernelBlurXPostprocess) {
  61016. this._kernelBlurXPostprocess.dispose();
  61017. this._kernelBlurXPostprocess = null;
  61018. }
  61019. if (this._kernelBlurYPostprocess) {
  61020. this._kernelBlurYPostprocess.dispose();
  61021. this._kernelBlurYPostprocess = null;
  61022. }
  61023. this._blurPostProcesses = [];
  61024. };
  61025. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61026. if (this._shadowMap) {
  61027. this._shadowMap.dispose();
  61028. this._shadowMap = null;
  61029. }
  61030. this._disposeBlurPostProcesses();
  61031. };
  61032. /**
  61033. * Disposes the ShadowGenerator.
  61034. * Returns nothing.
  61035. */
  61036. ShadowGenerator.prototype.dispose = function () {
  61037. this._disposeRTTandPostProcesses();
  61038. if (this._light) {
  61039. this._light._shadowGenerator = null;
  61040. this._light._markMeshesAsLightDirty();
  61041. }
  61042. };
  61043. /**
  61044. * Serializes the shadow generator setup to a json object.
  61045. * @returns The serialized JSON object
  61046. */
  61047. ShadowGenerator.prototype.serialize = function () {
  61048. var serializationObject = {};
  61049. var shadowMap = this.getShadowMap();
  61050. if (!shadowMap) {
  61051. return serializationObject;
  61052. }
  61053. serializationObject.lightId = this._light.id;
  61054. serializationObject.mapSize = shadowMap.getRenderSize();
  61055. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61056. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61057. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61058. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61059. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61060. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61061. serializationObject.depthScale = this.depthScale;
  61062. serializationObject.darkness = this.getDarkness();
  61063. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61064. serializationObject.blurKernel = this.blurKernel;
  61065. serializationObject.blurScale = this.blurScale;
  61066. serializationObject.useKernelBlur = this.useKernelBlur;
  61067. serializationObject.transparencyShadow = this._transparencyShadow;
  61068. serializationObject.renderList = [];
  61069. if (shadowMap.renderList) {
  61070. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61071. var mesh = shadowMap.renderList[meshIndex];
  61072. serializationObject.renderList.push(mesh.id);
  61073. }
  61074. }
  61075. return serializationObject;
  61076. };
  61077. /**
  61078. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61079. * @param parsedShadowGenerator The JSON object to parse
  61080. * @param scene The scene to create the shadow map for
  61081. * @returns The parsed shadow generator
  61082. */
  61083. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61084. //casting to point light, as light is missing the position attr and typescript complains.
  61085. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61086. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61087. var shadowMap = shadowGenerator.getShadowMap();
  61088. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61089. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61090. meshes.forEach(function (mesh) {
  61091. if (!shadowMap) {
  61092. return;
  61093. }
  61094. if (!shadowMap.renderList) {
  61095. shadowMap.renderList = [];
  61096. }
  61097. shadowMap.renderList.push(mesh);
  61098. });
  61099. }
  61100. if (parsedShadowGenerator.usePoissonSampling) {
  61101. shadowGenerator.usePoissonSampling = true;
  61102. }
  61103. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61104. shadowGenerator.useExponentialShadowMap = true;
  61105. }
  61106. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61107. shadowGenerator.useBlurExponentialShadowMap = true;
  61108. }
  61109. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61110. shadowGenerator.useCloseExponentialShadowMap = true;
  61111. }
  61112. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61113. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61114. }
  61115. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61116. shadowGenerator.useExponentialShadowMap = true;
  61117. }
  61118. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61119. shadowGenerator.useBlurExponentialShadowMap = true;
  61120. }
  61121. if (parsedShadowGenerator.depthScale) {
  61122. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61123. }
  61124. if (parsedShadowGenerator.blurScale) {
  61125. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61126. }
  61127. if (parsedShadowGenerator.blurBoxOffset) {
  61128. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61129. }
  61130. if (parsedShadowGenerator.useKernelBlur) {
  61131. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61132. }
  61133. if (parsedShadowGenerator.blurKernel) {
  61134. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61135. }
  61136. if (parsedShadowGenerator.bias !== undefined) {
  61137. shadowGenerator.bias = parsedShadowGenerator.bias;
  61138. }
  61139. if (parsedShadowGenerator.darkness) {
  61140. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61141. }
  61142. if (parsedShadowGenerator.transparencyShadow) {
  61143. shadowGenerator.setTransparencyShadow(true);
  61144. }
  61145. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61146. return shadowGenerator;
  61147. };
  61148. ShadowGenerator._FILTER_NONE = 0;
  61149. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61150. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61151. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61152. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61153. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61154. return ShadowGenerator;
  61155. }());
  61156. BABYLON.ShadowGenerator = ShadowGenerator;
  61157. })(BABYLON || (BABYLON = {}));
  61158. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61159. var BABYLON;
  61160. (function (BABYLON) {
  61161. var DefaultLoadingScreen = /** @class */ (function () {
  61162. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61163. if (_loadingText === void 0) { _loadingText = ""; }
  61164. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61165. var _this = this;
  61166. this._renderingCanvas = _renderingCanvas;
  61167. this._loadingText = _loadingText;
  61168. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61169. // Resize
  61170. this._resizeLoadingUI = function () {
  61171. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61172. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61173. if (!_this._loadingDiv) {
  61174. return;
  61175. }
  61176. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61177. _this._loadingDiv.style.left = canvasRect.left + "px";
  61178. _this._loadingDiv.style.top = canvasRect.top + "px";
  61179. _this._loadingDiv.style.width = canvasRect.width + "px";
  61180. _this._loadingDiv.style.height = canvasRect.height + "px";
  61181. };
  61182. }
  61183. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61184. if (this._loadingDiv) {
  61185. // Do not add a loading screen if there is already one
  61186. return;
  61187. }
  61188. this._loadingDiv = document.createElement("div");
  61189. this._loadingDiv.id = "babylonjsLoadingDiv";
  61190. this._loadingDiv.style.opacity = "0";
  61191. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61192. this._loadingDiv.style.pointerEvents = "none";
  61193. // Loading text
  61194. this._loadingTextDiv = document.createElement("div");
  61195. this._loadingTextDiv.style.position = "absolute";
  61196. this._loadingTextDiv.style.left = "0";
  61197. this._loadingTextDiv.style.top = "50%";
  61198. this._loadingTextDiv.style.marginTop = "80px";
  61199. this._loadingTextDiv.style.width = "100%";
  61200. this._loadingTextDiv.style.height = "20px";
  61201. this._loadingTextDiv.style.fontFamily = "Arial";
  61202. this._loadingTextDiv.style.fontSize = "14px";
  61203. this._loadingTextDiv.style.color = "white";
  61204. this._loadingTextDiv.style.textAlign = "center";
  61205. this._loadingTextDiv.innerHTML = "Loading";
  61206. this._loadingDiv.appendChild(this._loadingTextDiv);
  61207. //set the predefined text
  61208. this._loadingTextDiv.innerHTML = this._loadingText;
  61209. // Generating keyframes
  61210. var style = document.createElement('style');
  61211. style.type = 'text/css';
  61212. 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 }";
  61213. style.innerHTML = keyFrames;
  61214. document.getElementsByTagName('head')[0].appendChild(style);
  61215. // Loading img
  61216. var imgBack = new Image();
  61217. 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";
  61218. imgBack.style.position = "absolute";
  61219. imgBack.style.left = "50%";
  61220. imgBack.style.top = "50%";
  61221. imgBack.style.marginLeft = "-60px";
  61222. imgBack.style.marginTop = "-60px";
  61223. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61224. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61225. imgBack.style.transformOrigin = "50% 50%";
  61226. imgBack.style.webkitTransformOrigin = "50% 50%";
  61227. this._loadingDiv.appendChild(imgBack);
  61228. this._resizeLoadingUI();
  61229. window.addEventListener("resize", this._resizeLoadingUI);
  61230. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61231. document.body.appendChild(this._loadingDiv);
  61232. this._loadingDiv.style.opacity = "1";
  61233. };
  61234. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61235. var _this = this;
  61236. if (!this._loadingDiv) {
  61237. return;
  61238. }
  61239. var onTransitionEnd = function () {
  61240. if (!_this._loadingDiv) {
  61241. return;
  61242. }
  61243. document.body.removeChild(_this._loadingDiv);
  61244. window.removeEventListener("resize", _this._resizeLoadingUI);
  61245. _this._loadingDiv = null;
  61246. };
  61247. this._loadingDiv.style.opacity = "0";
  61248. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61249. };
  61250. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61251. set: function (text) {
  61252. this._loadingText = text;
  61253. if (this._loadingTextDiv) {
  61254. this._loadingTextDiv.innerHTML = this._loadingText;
  61255. }
  61256. },
  61257. enumerable: true,
  61258. configurable: true
  61259. });
  61260. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61261. get: function () {
  61262. return this._loadingDivBackgroundColor;
  61263. },
  61264. set: function (color) {
  61265. this._loadingDivBackgroundColor = color;
  61266. if (!this._loadingDiv) {
  61267. return;
  61268. }
  61269. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61270. },
  61271. enumerable: true,
  61272. configurable: true
  61273. });
  61274. return DefaultLoadingScreen;
  61275. }());
  61276. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61277. })(BABYLON || (BABYLON = {}));
  61278. //# sourceMappingURL=babylon.loadingScreen.js.map
  61279. var BABYLON;
  61280. (function (BABYLON) {
  61281. var SceneLoaderProgressEvent = /** @class */ (function () {
  61282. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61283. this.lengthComputable = lengthComputable;
  61284. this.loaded = loaded;
  61285. this.total = total;
  61286. }
  61287. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61288. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61289. };
  61290. return SceneLoaderProgressEvent;
  61291. }());
  61292. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61293. var SceneLoader = /** @class */ (function () {
  61294. function SceneLoader() {
  61295. }
  61296. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61297. get: function () {
  61298. return 0;
  61299. },
  61300. enumerable: true,
  61301. configurable: true
  61302. });
  61303. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61304. get: function () {
  61305. return 1;
  61306. },
  61307. enumerable: true,
  61308. configurable: true
  61309. });
  61310. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61311. get: function () {
  61312. return 2;
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61318. get: function () {
  61319. return 3;
  61320. },
  61321. enumerable: true,
  61322. configurable: true
  61323. });
  61324. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61325. get: function () {
  61326. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61327. },
  61328. set: function (value) {
  61329. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61330. },
  61331. enumerable: true,
  61332. configurable: true
  61333. });
  61334. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61335. get: function () {
  61336. return SceneLoader._ShowLoadingScreen;
  61337. },
  61338. set: function (value) {
  61339. SceneLoader._ShowLoadingScreen = value;
  61340. },
  61341. enumerable: true,
  61342. configurable: true
  61343. });
  61344. Object.defineProperty(SceneLoader, "loggingLevel", {
  61345. get: function () {
  61346. return SceneLoader._loggingLevel;
  61347. },
  61348. set: function (value) {
  61349. SceneLoader._loggingLevel = value;
  61350. },
  61351. enumerable: true,
  61352. configurable: true
  61353. });
  61354. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61355. get: function () {
  61356. return SceneLoader._CleanBoneMatrixWeights;
  61357. },
  61358. set: function (value) {
  61359. SceneLoader._CleanBoneMatrixWeights = value;
  61360. },
  61361. enumerable: true,
  61362. configurable: true
  61363. });
  61364. SceneLoader._getDefaultPlugin = function () {
  61365. return SceneLoader._registeredPlugins[".babylon"];
  61366. };
  61367. SceneLoader._getPluginForExtension = function (extension) {
  61368. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61369. if (registeredPlugin) {
  61370. return registeredPlugin;
  61371. }
  61372. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61373. return SceneLoader._getDefaultPlugin();
  61374. };
  61375. SceneLoader._getPluginForDirectLoad = function (data) {
  61376. for (var extension in SceneLoader._registeredPlugins) {
  61377. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61378. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61379. return SceneLoader._registeredPlugins[extension];
  61380. }
  61381. }
  61382. return SceneLoader._getDefaultPlugin();
  61383. };
  61384. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61385. if (sceneFilename.name) {
  61386. sceneFilename = sceneFilename.name;
  61387. }
  61388. var queryStringPosition = sceneFilename.indexOf("?");
  61389. if (queryStringPosition !== -1) {
  61390. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61391. }
  61392. var dotPosition = sceneFilename.lastIndexOf(".");
  61393. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61394. return SceneLoader._getPluginForExtension(extension);
  61395. };
  61396. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61397. SceneLoader._getDirectLoad = function (sceneFilename) {
  61398. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61399. return sceneFilename.substr(5);
  61400. }
  61401. return null;
  61402. };
  61403. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61404. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61405. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61406. var plugin;
  61407. if (registeredPlugin.plugin.createPlugin) {
  61408. plugin = registeredPlugin.plugin.createPlugin();
  61409. }
  61410. else {
  61411. plugin = registeredPlugin.plugin;
  61412. }
  61413. var useArrayBuffer = registeredPlugin.isBinary;
  61414. var database;
  61415. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61416. var dataCallback = function (data, responseURL) {
  61417. if (scene.isDisposed) {
  61418. onError("Scene has been disposed");
  61419. return;
  61420. }
  61421. scene.database = database;
  61422. onSuccess(plugin, data, responseURL);
  61423. };
  61424. var request = null;
  61425. var pluginDisposed = false;
  61426. var onDisposeObservable = plugin.onDisposeObservable;
  61427. if (onDisposeObservable) {
  61428. onDisposeObservable.add(function () {
  61429. pluginDisposed = true;
  61430. if (request) {
  61431. request.abort();
  61432. request = null;
  61433. }
  61434. onDispose();
  61435. });
  61436. }
  61437. var manifestChecked = function () {
  61438. if (pluginDisposed) {
  61439. return;
  61440. }
  61441. var url = rootUrl + sceneFilename;
  61442. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61443. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61444. } : undefined, database, useArrayBuffer, function (request, exception) {
  61445. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61446. });
  61447. };
  61448. if (directLoad) {
  61449. dataCallback(directLoad);
  61450. return plugin;
  61451. }
  61452. if (rootUrl.indexOf("file:") === -1) {
  61453. if (scene.getEngine().enableOfflineSupport) {
  61454. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61455. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61456. }
  61457. else {
  61458. manifestChecked();
  61459. }
  61460. }
  61461. else {
  61462. var fileOrString = sceneFilename;
  61463. if (fileOrString.name) {
  61464. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61465. }
  61466. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61467. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61468. }
  61469. else {
  61470. onError("Unable to find file named " + sceneFilename);
  61471. }
  61472. }
  61473. return plugin;
  61474. };
  61475. // Public functions
  61476. SceneLoader.GetPluginForExtension = function (extension) {
  61477. return SceneLoader._getPluginForExtension(extension).plugin;
  61478. };
  61479. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61480. return !!SceneLoader._registeredPlugins[extension];
  61481. };
  61482. SceneLoader.RegisterPlugin = function (plugin) {
  61483. if (typeof plugin.extensions === "string") {
  61484. var extension = plugin.extensions;
  61485. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61486. plugin: plugin,
  61487. isBinary: false
  61488. };
  61489. }
  61490. else {
  61491. var extensions = plugin.extensions;
  61492. Object.keys(extensions).forEach(function (extension) {
  61493. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61494. plugin: plugin,
  61495. isBinary: extensions[extension].isBinary
  61496. };
  61497. });
  61498. }
  61499. };
  61500. /**
  61501. * Import meshes into a scene
  61502. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61503. * @param rootUrl a string that defines the root url for scene and resources
  61504. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61505. * @param scene the instance of BABYLON.Scene to append to
  61506. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61507. * @param onProgress a callback with a progress event for each file being loaded
  61508. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61509. * @param pluginExtension the extension used to determine the plugin
  61510. * @returns The loaded plugin
  61511. */
  61512. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61513. if (onSuccess === void 0) { onSuccess = null; }
  61514. if (onProgress === void 0) { onProgress = null; }
  61515. if (onError === void 0) { onError = null; }
  61516. if (pluginExtension === void 0) { pluginExtension = null; }
  61517. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61518. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61519. return null;
  61520. }
  61521. var loadingToken = {};
  61522. scene._addPendingData(loadingToken);
  61523. var disposeHandler = function () {
  61524. scene._removePendingData(loadingToken);
  61525. };
  61526. var errorHandler = function (message, exception) {
  61527. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61528. if (onError) {
  61529. onError(scene, errorMessage, exception);
  61530. }
  61531. else {
  61532. BABYLON.Tools.Error(errorMessage);
  61533. // should the exception be thrown?
  61534. }
  61535. disposeHandler();
  61536. };
  61537. var progressHandler = onProgress ? function (event) {
  61538. try {
  61539. onProgress(event);
  61540. }
  61541. catch (e) {
  61542. errorHandler("Error in onProgress callback", e);
  61543. }
  61544. } : undefined;
  61545. var successHandler = function (meshes, particleSystems, skeletons) {
  61546. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61547. if (onSuccess) {
  61548. try {
  61549. onSuccess(meshes, particleSystems, skeletons);
  61550. }
  61551. catch (e) {
  61552. errorHandler("Error in onSuccess callback", e);
  61553. }
  61554. }
  61555. scene._removePendingData(loadingToken);
  61556. };
  61557. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61558. if (plugin.rewriteRootURL) {
  61559. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61560. }
  61561. if (sceneFilename === "") {
  61562. if (sceneFilename === "") {
  61563. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61564. }
  61565. }
  61566. if (plugin.importMesh) {
  61567. var syncedPlugin = plugin;
  61568. var meshes = new Array();
  61569. var particleSystems = new Array();
  61570. var skeletons = new Array();
  61571. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61572. return;
  61573. }
  61574. scene.loadingPluginName = plugin.name;
  61575. successHandler(meshes, particleSystems, skeletons);
  61576. }
  61577. else {
  61578. var asyncedPlugin = plugin;
  61579. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61580. scene.loadingPluginName = plugin.name;
  61581. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61582. }).catch(function (error) {
  61583. errorHandler(error.message, error);
  61584. });
  61585. }
  61586. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61587. };
  61588. /**
  61589. * Import meshes into a scene
  61590. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61591. * @param rootUrl a string that defines the root url for scene and resources
  61592. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61593. * @param scene the instance of BABYLON.Scene to append to
  61594. * @param onProgress a callback with a progress event for each file being loaded
  61595. * @param pluginExtension the extension used to determine the plugin
  61596. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61597. */
  61598. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61599. if (onProgress === void 0) { onProgress = null; }
  61600. if (pluginExtension === void 0) { pluginExtension = null; }
  61601. return new Promise(function (resolve, reject) {
  61602. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61603. resolve({
  61604. meshes: meshes,
  61605. particleSystems: particleSystems,
  61606. skeletons: skeletons
  61607. });
  61608. }, onProgress, function (scene, message, exception) {
  61609. reject(exception || new Error(message));
  61610. });
  61611. });
  61612. };
  61613. /**
  61614. * Load a scene
  61615. * @param rootUrl a string that defines the root url for scene and resources
  61616. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61617. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61618. * @param onSuccess a callback with the scene when import succeeds
  61619. * @param onProgress a callback with a progress event for each file being loaded
  61620. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61621. * @param pluginExtension the extension used to determine the plugin
  61622. * @returns The loaded plugin
  61623. */
  61624. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61625. if (onSuccess === void 0) { onSuccess = null; }
  61626. if (onProgress === void 0) { onProgress = null; }
  61627. if (onError === void 0) { onError = null; }
  61628. if (pluginExtension === void 0) { pluginExtension = null; }
  61629. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61630. };
  61631. /**
  61632. * Load a scene
  61633. * @param rootUrl a string that defines the root url for scene and resources
  61634. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61635. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61636. * @param onProgress a callback with a progress event for each file being loaded
  61637. * @param pluginExtension the extension used to determine the plugin
  61638. * @returns The loaded scene
  61639. */
  61640. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61641. if (onProgress === void 0) { onProgress = null; }
  61642. if (pluginExtension === void 0) { pluginExtension = null; }
  61643. return new Promise(function (resolve, reject) {
  61644. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61645. resolve(scene);
  61646. }, onProgress, function (scene, message, exception) {
  61647. reject(exception || new Error(message));
  61648. }, pluginExtension);
  61649. });
  61650. };
  61651. /**
  61652. * Append a scene
  61653. * @param rootUrl a string that defines the root url for scene and resources
  61654. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61655. * @param scene is the instance of BABYLON.Scene to append to
  61656. * @param onSuccess a callback with the scene when import succeeds
  61657. * @param onProgress a callback with a progress event for each file being loaded
  61658. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61659. * @param pluginExtension the extension used to determine the plugin
  61660. * @returns The loaded plugin
  61661. */
  61662. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61663. if (onSuccess === void 0) { onSuccess = null; }
  61664. if (onProgress === void 0) { onProgress = null; }
  61665. if (onError === void 0) { onError = null; }
  61666. if (pluginExtension === void 0) { pluginExtension = null; }
  61667. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61668. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61669. return null;
  61670. }
  61671. if (SceneLoader.ShowLoadingScreen) {
  61672. scene.getEngine().displayLoadingUI();
  61673. }
  61674. var loadingToken = {};
  61675. scene._addPendingData(loadingToken);
  61676. var disposeHandler = function () {
  61677. scene._removePendingData(loadingToken);
  61678. scene.getEngine().hideLoadingUI();
  61679. };
  61680. var errorHandler = function (message, exception) {
  61681. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61682. if (onError) {
  61683. onError(scene, errorMessage, exception);
  61684. }
  61685. else {
  61686. BABYLON.Tools.Error(errorMessage);
  61687. // should the exception be thrown?
  61688. }
  61689. disposeHandler();
  61690. };
  61691. var progressHandler = onProgress ? function (event) {
  61692. try {
  61693. onProgress(event);
  61694. }
  61695. catch (e) {
  61696. errorHandler("Error in onProgress callback", e);
  61697. }
  61698. } : undefined;
  61699. var successHandler = function () {
  61700. if (onSuccess) {
  61701. try {
  61702. onSuccess(scene);
  61703. }
  61704. catch (e) {
  61705. errorHandler("Error in onSuccess callback", e);
  61706. }
  61707. }
  61708. scene._removePendingData(loadingToken);
  61709. };
  61710. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61711. if (sceneFilename === "") {
  61712. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61713. }
  61714. if (plugin.load) {
  61715. var syncedPlugin = plugin;
  61716. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61717. return;
  61718. }
  61719. scene.loadingPluginName = plugin.name;
  61720. successHandler();
  61721. }
  61722. else {
  61723. var asyncedPlugin = plugin;
  61724. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61725. scene.loadingPluginName = plugin.name;
  61726. successHandler();
  61727. }).catch(function (error) {
  61728. errorHandler(error.message, error);
  61729. });
  61730. }
  61731. if (SceneLoader.ShowLoadingScreen) {
  61732. scene.executeWhenReady(function () {
  61733. scene.getEngine().hideLoadingUI();
  61734. });
  61735. }
  61736. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61737. };
  61738. /**
  61739. * Append a scene
  61740. * @param rootUrl a string that defines the root url for scene and resources
  61741. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61742. * @param scene is the instance of BABYLON.Scene to append to
  61743. * @param onProgress a callback with a progress event for each file being loaded
  61744. * @param pluginExtension the extension used to determine the plugin
  61745. * @returns The given scene
  61746. */
  61747. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61748. if (onProgress === void 0) { onProgress = null; }
  61749. if (pluginExtension === void 0) { pluginExtension = null; }
  61750. return new Promise(function (resolve, reject) {
  61751. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61752. resolve(scene);
  61753. }, onProgress, function (scene, message, exception) {
  61754. reject(exception || new Error(message));
  61755. }, pluginExtension);
  61756. });
  61757. };
  61758. /**
  61759. * Load a scene into an asset container
  61760. * @param rootUrl a string that defines the root url for scene and resources
  61761. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61762. * @param scene is the instance of BABYLON.Scene to append to
  61763. * @param onSuccess a callback with the scene when import succeeds
  61764. * @param onProgress a callback with a progress event for each file being loaded
  61765. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61766. * @param pluginExtension the extension used to determine the plugin
  61767. * @returns The loaded plugin
  61768. */
  61769. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61770. if (onSuccess === void 0) { onSuccess = null; }
  61771. if (onProgress === void 0) { onProgress = null; }
  61772. if (onError === void 0) { onError = null; }
  61773. if (pluginExtension === void 0) { pluginExtension = null; }
  61774. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61775. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61776. return null;
  61777. }
  61778. var loadingToken = {};
  61779. scene._addPendingData(loadingToken);
  61780. var disposeHandler = function () {
  61781. scene._removePendingData(loadingToken);
  61782. };
  61783. var errorHandler = function (message, exception) {
  61784. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61785. if (onError) {
  61786. onError(scene, errorMessage, exception);
  61787. }
  61788. else {
  61789. BABYLON.Tools.Error(errorMessage);
  61790. // should the exception be thrown?
  61791. }
  61792. disposeHandler();
  61793. };
  61794. var progressHandler = onProgress ? function (event) {
  61795. try {
  61796. onProgress(event);
  61797. }
  61798. catch (e) {
  61799. errorHandler("Error in onProgress callback", e);
  61800. }
  61801. } : undefined;
  61802. var successHandler = function (assets) {
  61803. if (onSuccess) {
  61804. try {
  61805. onSuccess(assets);
  61806. }
  61807. catch (e) {
  61808. errorHandler("Error in onSuccess callback", e);
  61809. }
  61810. }
  61811. scene._removePendingData(loadingToken);
  61812. };
  61813. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61814. if (plugin.loadAssetContainer) {
  61815. var syncedPlugin = plugin;
  61816. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61817. if (!assetContainer) {
  61818. return;
  61819. }
  61820. scene.loadingPluginName = plugin.name;
  61821. successHandler(assetContainer);
  61822. }
  61823. else if (plugin.loadAssetContainerAsync) {
  61824. var asyncedPlugin = plugin;
  61825. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61826. scene.loadingPluginName = plugin.name;
  61827. successHandler(assetContainer);
  61828. }).catch(function (error) {
  61829. errorHandler(error.message, error);
  61830. });
  61831. }
  61832. else {
  61833. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61834. }
  61835. if (SceneLoader.ShowLoadingScreen) {
  61836. scene.executeWhenReady(function () {
  61837. scene.getEngine().hideLoadingUI();
  61838. });
  61839. }
  61840. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61841. };
  61842. /**
  61843. * Load a scene into an asset container
  61844. * @param rootUrl a string that defines the root url for scene and resources
  61845. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61846. * @param scene is the instance of BABYLON.Scene to append to
  61847. * @param onProgress a callback with a progress event for each file being loaded
  61848. * @param pluginExtension the extension used to determine the plugin
  61849. * @returns The loaded asset container
  61850. */
  61851. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61852. if (onProgress === void 0) { onProgress = null; }
  61853. if (pluginExtension === void 0) { pluginExtension = null; }
  61854. return new Promise(function (resolve, reject) {
  61855. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61856. resolve(assetContainer);
  61857. }, onProgress, function (scene, message, exception) {
  61858. reject(exception || new Error(message));
  61859. }, pluginExtension);
  61860. });
  61861. };
  61862. // Flags
  61863. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61864. SceneLoader._ShowLoadingScreen = true;
  61865. SceneLoader._CleanBoneMatrixWeights = false;
  61866. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61867. // Members
  61868. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61869. SceneLoader._registeredPlugins = {};
  61870. return SceneLoader;
  61871. }());
  61872. BABYLON.SceneLoader = SceneLoader;
  61873. ;
  61874. })(BABYLON || (BABYLON = {}));
  61875. //# sourceMappingURL=babylon.sceneLoader.js.map
  61876. var BABYLON;
  61877. (function (BABYLON) {
  61878. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61879. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61880. var parsedMaterial = parsedData.materials[index];
  61881. if (parsedMaterial.id === id) {
  61882. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61883. }
  61884. }
  61885. return null;
  61886. };
  61887. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61888. for (var i in names) {
  61889. if (mesh.name === names[i]) {
  61890. hierarchyIds.push(mesh.id);
  61891. return true;
  61892. }
  61893. }
  61894. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61895. hierarchyIds.push(mesh.id);
  61896. return true;
  61897. }
  61898. return false;
  61899. };
  61900. var logOperation = function (operation, producer) {
  61901. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61902. };
  61903. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61904. if (addToScene === void 0) { addToScene = false; }
  61905. var container = new BABYLON.AssetContainer(scene);
  61906. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61907. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61908. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61909. // and avoid problems with multiple concurrent .babylon loads.
  61910. var log = "importScene has failed JSON parse";
  61911. try {
  61912. var parsedData = JSON.parse(data);
  61913. log = "";
  61914. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61915. var index;
  61916. var cache;
  61917. // Lights
  61918. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61919. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61920. var parsedLight = parsedData.lights[index];
  61921. var light = BABYLON.Light.Parse(parsedLight, scene);
  61922. if (light) {
  61923. container.lights.push(light);
  61924. log += (index === 0 ? "\n\tLights:" : "");
  61925. log += "\n\t\t" + light.toString(fullDetails);
  61926. }
  61927. }
  61928. }
  61929. // Animations
  61930. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61931. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61932. var parsedAnimation = parsedData.animations[index];
  61933. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61934. scene.animations.push(animation);
  61935. container.animations.push(animation);
  61936. log += (index === 0 ? "\n\tAnimations:" : "");
  61937. log += "\n\t\t" + animation.toString(fullDetails);
  61938. }
  61939. }
  61940. // Materials
  61941. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61942. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61943. var parsedMaterial = parsedData.materials[index];
  61944. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61945. container.materials.push(mat);
  61946. log += (index === 0 ? "\n\tMaterials:" : "");
  61947. log += "\n\t\t" + mat.toString(fullDetails);
  61948. }
  61949. }
  61950. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61951. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61952. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61953. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61954. container.multiMaterials.push(mmat);
  61955. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61956. log += "\n\t\t" + mmat.toString(fullDetails);
  61957. }
  61958. }
  61959. // Morph targets
  61960. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61961. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61962. var managerData = _a[_i];
  61963. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61964. }
  61965. }
  61966. // Skeletons
  61967. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61968. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61969. var parsedSkeleton = parsedData.skeletons[index];
  61970. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61971. container.skeletons.push(skeleton);
  61972. log += (index === 0 ? "\n\tSkeletons:" : "");
  61973. log += "\n\t\t" + skeleton.toString(fullDetails);
  61974. }
  61975. }
  61976. // Geometries
  61977. var geometries = parsedData.geometries;
  61978. if (geometries !== undefined && geometries !== null) {
  61979. var addedGeometry = new Array();
  61980. // Boxes
  61981. var boxes = geometries.boxes;
  61982. if (boxes !== undefined && boxes !== null) {
  61983. for (index = 0, cache = boxes.length; index < cache; index++) {
  61984. var parsedBox = boxes[index];
  61985. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61986. }
  61987. }
  61988. // Spheres
  61989. var spheres = geometries.spheres;
  61990. if (spheres !== undefined && spheres !== null) {
  61991. for (index = 0, cache = spheres.length; index < cache; index++) {
  61992. var parsedSphere = spheres[index];
  61993. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61994. }
  61995. }
  61996. // Cylinders
  61997. var cylinders = geometries.cylinders;
  61998. if (cylinders !== undefined && cylinders !== null) {
  61999. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62000. var parsedCylinder = cylinders[index];
  62001. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62002. }
  62003. }
  62004. // Toruses
  62005. var toruses = geometries.toruses;
  62006. if (toruses !== undefined && toruses !== null) {
  62007. for (index = 0, cache = toruses.length; index < cache; index++) {
  62008. var parsedTorus = toruses[index];
  62009. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62010. }
  62011. }
  62012. // Grounds
  62013. var grounds = geometries.grounds;
  62014. if (grounds !== undefined && grounds !== null) {
  62015. for (index = 0, cache = grounds.length; index < cache; index++) {
  62016. var parsedGround = grounds[index];
  62017. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62018. }
  62019. }
  62020. // Planes
  62021. var planes = geometries.planes;
  62022. if (planes !== undefined && planes !== null) {
  62023. for (index = 0, cache = planes.length; index < cache; index++) {
  62024. var parsedPlane = planes[index];
  62025. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62026. }
  62027. }
  62028. // TorusKnots
  62029. var torusKnots = geometries.torusKnots;
  62030. if (torusKnots !== undefined && torusKnots !== null) {
  62031. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62032. var parsedTorusKnot = torusKnots[index];
  62033. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62034. }
  62035. }
  62036. // VertexData
  62037. var vertexData = geometries.vertexData;
  62038. if (vertexData !== undefined && vertexData !== null) {
  62039. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62040. var parsedVertexData = vertexData[index];
  62041. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62042. }
  62043. }
  62044. addedGeometry.forEach(function (g) {
  62045. if (g) {
  62046. container.geometries.push(g);
  62047. }
  62048. });
  62049. }
  62050. // Transform nodes
  62051. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62052. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62053. var parsedTransformNode = parsedData.transformNodes[index];
  62054. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62055. container.transformNodes.push(node);
  62056. }
  62057. }
  62058. // Meshes
  62059. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62060. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62061. var parsedMesh = parsedData.meshes[index];
  62062. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62063. container.meshes.push(mesh);
  62064. log += (index === 0 ? "\n\tMeshes:" : "");
  62065. log += "\n\t\t" + mesh.toString(fullDetails);
  62066. }
  62067. }
  62068. // Cameras
  62069. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62070. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62071. var parsedCamera = parsedData.cameras[index];
  62072. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62073. container.cameras.push(camera);
  62074. log += (index === 0 ? "\n\tCameras:" : "");
  62075. log += "\n\t\t" + camera.toString(fullDetails);
  62076. }
  62077. }
  62078. // Browsing all the graph to connect the dots
  62079. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62080. var camera = scene.cameras[index];
  62081. if (camera._waitingParentId) {
  62082. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62083. camera._waitingParentId = null;
  62084. }
  62085. }
  62086. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62087. var light_1 = scene.lights[index];
  62088. if (light_1 && light_1._waitingParentId) {
  62089. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62090. light_1._waitingParentId = null;
  62091. }
  62092. }
  62093. // Sounds
  62094. // TODO: add sound
  62095. var loadedSounds = [];
  62096. var loadedSound;
  62097. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62098. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62099. var parsedSound = parsedData.sounds[index];
  62100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62101. if (!parsedSound.url)
  62102. parsedSound.url = parsedSound.name;
  62103. if (!loadedSounds[parsedSound.url]) {
  62104. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62105. loadedSounds[parsedSound.url] = loadedSound;
  62106. container.sounds.push(loadedSound);
  62107. }
  62108. else {
  62109. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62110. }
  62111. }
  62112. else {
  62113. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62114. }
  62115. }
  62116. }
  62117. loadedSounds = [];
  62118. // Connect parents & children and parse actions
  62119. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62120. var transformNode = scene.transformNodes[index];
  62121. if (transformNode._waitingParentId) {
  62122. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62123. transformNode._waitingParentId = null;
  62124. }
  62125. }
  62126. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62127. var mesh = scene.meshes[index];
  62128. if (mesh._waitingParentId) {
  62129. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62130. mesh._waitingParentId = null;
  62131. }
  62132. if (mesh._waitingActions) {
  62133. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62134. mesh._waitingActions = null;
  62135. }
  62136. }
  62137. // freeze world matrix application
  62138. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62139. var currentMesh = scene.meshes[index];
  62140. if (currentMesh._waitingFreezeWorldMatrix) {
  62141. currentMesh.freezeWorldMatrix();
  62142. currentMesh._waitingFreezeWorldMatrix = null;
  62143. }
  62144. else {
  62145. currentMesh.computeWorldMatrix(true);
  62146. }
  62147. }
  62148. // Particles Systems
  62149. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62150. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62151. var parsedParticleSystem = parsedData.particleSystems[index];
  62152. if (parsedParticleSystem.activeParticleCount) {
  62153. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62154. container.particleSystems.push(ps);
  62155. }
  62156. else {
  62157. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62158. container.particleSystems.push(ps);
  62159. }
  62160. }
  62161. }
  62162. // Lens flares
  62163. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62164. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62165. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62166. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62167. container.lensFlareSystems.push(lf);
  62168. }
  62169. }
  62170. // Shadows
  62171. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62172. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62173. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62174. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62175. container.shadowGenerators.push(sg);
  62176. }
  62177. }
  62178. // Lights exclusions / inclusions
  62179. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62180. var light_2 = scene.lights[index];
  62181. // Excluded check
  62182. if (light_2._excludedMeshesIds.length > 0) {
  62183. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62184. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62185. if (excludedMesh) {
  62186. light_2.excludedMeshes.push(excludedMesh);
  62187. }
  62188. }
  62189. light_2._excludedMeshesIds = [];
  62190. }
  62191. // Included check
  62192. if (light_2._includedOnlyMeshesIds.length > 0) {
  62193. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62194. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62195. if (includedOnlyMesh) {
  62196. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62197. }
  62198. }
  62199. light_2._includedOnlyMeshesIds = [];
  62200. }
  62201. }
  62202. // Actions (scene)
  62203. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62204. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62205. }
  62206. if (!addToScene) {
  62207. container.removeAllFromScene();
  62208. }
  62209. }
  62210. catch (err) {
  62211. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62212. if (onError) {
  62213. onError(msg, err);
  62214. }
  62215. else {
  62216. BABYLON.Tools.Log(msg);
  62217. throw err;
  62218. }
  62219. }
  62220. finally {
  62221. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62222. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62223. }
  62224. }
  62225. return container;
  62226. };
  62227. BABYLON.SceneLoader.RegisterPlugin({
  62228. name: "babylon.js",
  62229. extensions: ".babylon",
  62230. canDirectLoad: function (data) {
  62231. if (data.indexOf("babylon") !== -1) {
  62232. return true;
  62233. }
  62234. return false;
  62235. },
  62236. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62237. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62238. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62239. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62240. // and avoid problems with multiple concurrent .babylon loads.
  62241. var log = "importMesh has failed JSON parse";
  62242. try {
  62243. var parsedData = JSON.parse(data);
  62244. log = "";
  62245. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62246. if (!meshesNames) {
  62247. meshesNames = null;
  62248. }
  62249. else if (!Array.isArray(meshesNames)) {
  62250. meshesNames = [meshesNames];
  62251. }
  62252. var hierarchyIds = new Array();
  62253. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62254. var loadedSkeletonsIds = [];
  62255. var loadedMaterialsIds = [];
  62256. var index;
  62257. var cache;
  62258. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62259. var parsedMesh = parsedData.meshes[index];
  62260. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62261. if (meshesNames !== null) {
  62262. // Remove found mesh name from list.
  62263. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62264. }
  62265. //Geometry?
  62266. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62267. //does the file contain geometries?
  62268. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62269. //find the correct geometry and add it to the scene
  62270. var found = false;
  62271. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62272. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62273. return;
  62274. }
  62275. else {
  62276. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62277. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62278. switch (geometryType) {
  62279. case "boxes":
  62280. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62281. break;
  62282. case "spheres":
  62283. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62284. break;
  62285. case "cylinders":
  62286. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62287. break;
  62288. case "toruses":
  62289. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62290. break;
  62291. case "grounds":
  62292. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62293. break;
  62294. case "planes":
  62295. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62296. break;
  62297. case "torusKnots":
  62298. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62299. break;
  62300. case "vertexData":
  62301. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62302. break;
  62303. }
  62304. found = true;
  62305. }
  62306. });
  62307. }
  62308. });
  62309. if (found === false) {
  62310. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62311. }
  62312. }
  62313. }
  62314. // Material ?
  62315. if (parsedMesh.materialId) {
  62316. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62317. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62318. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62319. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62320. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62321. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62322. var subMatId = parsedMultiMaterial.materials[matIndex];
  62323. loadedMaterialsIds.push(subMatId);
  62324. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62325. if (mat) {
  62326. log += "\n\tMaterial " + mat.toString(fullDetails);
  62327. }
  62328. }
  62329. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62330. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62331. if (mmat) {
  62332. materialFound = true;
  62333. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62334. }
  62335. break;
  62336. }
  62337. }
  62338. }
  62339. if (materialFound === false) {
  62340. loadedMaterialsIds.push(parsedMesh.materialId);
  62341. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62342. if (!mat) {
  62343. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62344. }
  62345. else {
  62346. log += "\n\tMaterial " + mat.toString(fullDetails);
  62347. }
  62348. }
  62349. }
  62350. // Skeleton ?
  62351. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62352. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62353. if (skeletonAlreadyLoaded === false) {
  62354. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62355. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62356. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62357. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62358. skeletons.push(skeleton);
  62359. loadedSkeletonsIds.push(parsedSkeleton.id);
  62360. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62361. }
  62362. }
  62363. }
  62364. }
  62365. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62366. meshes.push(mesh);
  62367. log += "\n\tMesh " + mesh.toString(fullDetails);
  62368. }
  62369. }
  62370. // Connecting parents
  62371. var currentMesh;
  62372. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62373. currentMesh = scene.meshes[index];
  62374. if (currentMesh._waitingParentId) {
  62375. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62376. currentMesh._waitingParentId = null;
  62377. }
  62378. }
  62379. // freeze and compute world matrix application
  62380. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62381. currentMesh = scene.meshes[index];
  62382. if (currentMesh._waitingFreezeWorldMatrix) {
  62383. currentMesh.freezeWorldMatrix();
  62384. currentMesh._waitingFreezeWorldMatrix = null;
  62385. }
  62386. else {
  62387. currentMesh.computeWorldMatrix(true);
  62388. }
  62389. }
  62390. }
  62391. // Particles
  62392. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62393. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62394. var parsedParticleSystem = parsedData.particleSystems[index];
  62395. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62396. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62397. }
  62398. }
  62399. }
  62400. return true;
  62401. }
  62402. catch (err) {
  62403. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62404. if (onError) {
  62405. onError(msg, err);
  62406. }
  62407. else {
  62408. BABYLON.Tools.Log(msg);
  62409. throw err;
  62410. }
  62411. }
  62412. finally {
  62413. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62414. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62415. }
  62416. }
  62417. return false;
  62418. },
  62419. load: function (scene, data, rootUrl, onError) {
  62420. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62421. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62422. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62423. // and avoid problems with multiple concurrent .babylon loads.
  62424. var log = "importScene has failed JSON parse";
  62425. try {
  62426. var parsedData = JSON.parse(data);
  62427. log = "";
  62428. // Scene
  62429. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62430. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62431. }
  62432. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62433. scene.autoClear = parsedData.autoClear;
  62434. }
  62435. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62436. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62437. }
  62438. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62439. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62440. }
  62441. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62442. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62443. }
  62444. // Fog
  62445. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62446. scene.fogMode = parsedData.fogMode;
  62447. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62448. scene.fogStart = parsedData.fogStart;
  62449. scene.fogEnd = parsedData.fogEnd;
  62450. scene.fogDensity = parsedData.fogDensity;
  62451. log += "\tFog mode for scene: ";
  62452. switch (scene.fogMode) {
  62453. // getters not compiling, so using hardcoded
  62454. case 1:
  62455. log += "exp\n";
  62456. break;
  62457. case 2:
  62458. log += "exp2\n";
  62459. break;
  62460. case 3:
  62461. log += "linear\n";
  62462. break;
  62463. }
  62464. }
  62465. //Physics
  62466. if (parsedData.physicsEnabled) {
  62467. var physicsPlugin;
  62468. if (parsedData.physicsEngine === "cannon") {
  62469. physicsPlugin = new BABYLON.CannonJSPlugin();
  62470. }
  62471. else if (parsedData.physicsEngine === "oimo") {
  62472. physicsPlugin = new BABYLON.OimoJSPlugin();
  62473. }
  62474. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62475. //else - default engine, which is currently oimo
  62476. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62477. scene.enablePhysics(physicsGravity, physicsPlugin);
  62478. }
  62479. // Metadata
  62480. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62481. scene.metadata = parsedData.metadata;
  62482. }
  62483. //collisions, if defined. otherwise, default is true
  62484. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62485. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62486. }
  62487. scene.workerCollisions = !!parsedData.workerCollisions;
  62488. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62489. if (!container) {
  62490. return false;
  62491. }
  62492. if (parsedData.autoAnimate) {
  62493. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62494. }
  62495. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62496. scene.setActiveCameraByID(parsedData.activeCameraID);
  62497. }
  62498. // Environment texture
  62499. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62500. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62501. if (parsedData.createDefaultSkybox === true) {
  62502. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62503. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62504. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62505. }
  62506. }
  62507. // Finish
  62508. return true;
  62509. }
  62510. catch (err) {
  62511. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62512. if (onError) {
  62513. onError(msg, err);
  62514. }
  62515. else {
  62516. BABYLON.Tools.Log(msg);
  62517. throw err;
  62518. }
  62519. }
  62520. finally {
  62521. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62522. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62523. }
  62524. }
  62525. return false;
  62526. },
  62527. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62528. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62529. return container;
  62530. }
  62531. });
  62532. })(BABYLON || (BABYLON = {}));
  62533. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62534. var BABYLON;
  62535. (function (BABYLON) {
  62536. var FilesInput = /** @class */ (function () {
  62537. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62538. this.onProcessFileCallback = function () { return true; };
  62539. this._engine = engine;
  62540. this._currentScene = scene;
  62541. this._sceneLoadedCallback = sceneLoadedCallback;
  62542. this._progressCallback = progressCallback;
  62543. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62544. this._textureLoadingCallback = textureLoadingCallback;
  62545. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62546. this._onReloadCallback = onReloadCallback;
  62547. this._errorCallback = errorCallback;
  62548. }
  62549. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62550. var _this = this;
  62551. if (elementToMonitor) {
  62552. this._elementToMonitor = elementToMonitor;
  62553. this._dragEnterHandler = function (e) { _this.drag(e); };
  62554. this._dragOverHandler = function (e) { _this.drag(e); };
  62555. this._dropHandler = function (e) { _this.drop(e); };
  62556. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62557. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62558. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62559. }
  62560. };
  62561. FilesInput.prototype.dispose = function () {
  62562. if (!this._elementToMonitor) {
  62563. return;
  62564. }
  62565. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62566. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62567. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62568. };
  62569. FilesInput.prototype.renderFunction = function () {
  62570. if (this._additionalRenderLoopLogicCallback) {
  62571. this._additionalRenderLoopLogicCallback();
  62572. }
  62573. if (this._currentScene) {
  62574. if (this._textureLoadingCallback) {
  62575. var remaining = this._currentScene.getWaitingItemsCount();
  62576. if (remaining > 0) {
  62577. this._textureLoadingCallback(remaining);
  62578. }
  62579. }
  62580. this._currentScene.render();
  62581. }
  62582. };
  62583. FilesInput.prototype.drag = function (e) {
  62584. e.stopPropagation();
  62585. e.preventDefault();
  62586. };
  62587. FilesInput.prototype.drop = function (eventDrop) {
  62588. eventDrop.stopPropagation();
  62589. eventDrop.preventDefault();
  62590. this.loadFiles(eventDrop);
  62591. };
  62592. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62593. var _this = this;
  62594. var reader = folder.createReader();
  62595. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62596. reader.readEntries(function (entries) {
  62597. remaining.count += entries.length;
  62598. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62599. var entry = entries_1[_i];
  62600. if (entry.isFile) {
  62601. entry.file(function (file) {
  62602. file.correctName = relativePath + file.name;
  62603. files.push(file);
  62604. if (--remaining.count === 0) {
  62605. callback();
  62606. }
  62607. });
  62608. }
  62609. else if (entry.isDirectory) {
  62610. _this._traverseFolder(entry, files, remaining, callback);
  62611. }
  62612. }
  62613. if (--remaining.count) {
  62614. callback();
  62615. }
  62616. });
  62617. };
  62618. FilesInput.prototype._processFiles = function (files) {
  62619. for (var i = 0; i < files.length; i++) {
  62620. var name = files[i].correctName.toLowerCase();
  62621. var extension = name.split('.').pop();
  62622. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62623. continue;
  62624. }
  62625. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62626. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62627. this._sceneFileToLoad = files[i];
  62628. }
  62629. else {
  62630. FilesInput.FilesToLoad[name] = files[i];
  62631. }
  62632. }
  62633. };
  62634. FilesInput.prototype.loadFiles = function (event) {
  62635. var _this = this;
  62636. if (this._startingProcessingFilesCallback)
  62637. this._startingProcessingFilesCallback();
  62638. // Handling data transfer via drag'n'drop
  62639. if (event && event.dataTransfer && event.dataTransfer.files) {
  62640. this._filesToLoad = event.dataTransfer.files;
  62641. }
  62642. // Handling files from input files
  62643. if (event && event.target && event.target.files) {
  62644. this._filesToLoad = event.target.files;
  62645. }
  62646. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62647. var files_1 = new Array();
  62648. var folders = [];
  62649. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62650. for (var i = 0; i < this._filesToLoad.length; i++) {
  62651. var fileToLoad = this._filesToLoad[i];
  62652. var name_1 = fileToLoad.name.toLowerCase();
  62653. var entry = void 0;
  62654. fileToLoad.correctName = name_1;
  62655. if (items) {
  62656. var item = items[i];
  62657. if (item.getAsEntry) {
  62658. entry = item.getAsEntry();
  62659. }
  62660. else if (item.webkitGetAsEntry) {
  62661. entry = item.webkitGetAsEntry();
  62662. }
  62663. }
  62664. if (!entry) {
  62665. files_1.push(fileToLoad);
  62666. }
  62667. else {
  62668. if (entry.isDirectory) {
  62669. folders.push(entry);
  62670. }
  62671. else {
  62672. files_1.push(fileToLoad);
  62673. }
  62674. }
  62675. }
  62676. if (folders.length === 0) {
  62677. this._processFiles(files_1);
  62678. this._processReload();
  62679. }
  62680. else {
  62681. var remaining = { count: folders.length };
  62682. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62683. var folder = folders_1[_i];
  62684. this._traverseFolder(folder, files_1, remaining, function () {
  62685. _this._processFiles(files_1);
  62686. if (remaining.count === 0) {
  62687. _this._processReload();
  62688. }
  62689. });
  62690. }
  62691. }
  62692. }
  62693. };
  62694. FilesInput.prototype._processReload = function () {
  62695. if (this._onReloadCallback) {
  62696. this._onReloadCallback(this._sceneFileToLoad);
  62697. }
  62698. else {
  62699. this.reload();
  62700. }
  62701. };
  62702. FilesInput.prototype.reload = function () {
  62703. var _this = this;
  62704. // If a scene file has been provided
  62705. if (this._sceneFileToLoad) {
  62706. if (this._currentScene) {
  62707. if (BABYLON.Tools.errorsCount > 0) {
  62708. BABYLON.Tools.ClearLogCache();
  62709. }
  62710. this._engine.stopRenderLoop();
  62711. this._currentScene.dispose();
  62712. }
  62713. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62714. if (_this._progressCallback) {
  62715. _this._progressCallback(progress);
  62716. }
  62717. }).then(function (scene) {
  62718. _this._currentScene = scene;
  62719. if (_this._sceneLoadedCallback) {
  62720. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62721. }
  62722. // Wait for textures and shaders to be ready
  62723. _this._currentScene.executeWhenReady(function () {
  62724. _this._engine.runRenderLoop(function () {
  62725. _this.renderFunction();
  62726. });
  62727. });
  62728. }).catch(function (error) {
  62729. if (_this._errorCallback) {
  62730. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62731. }
  62732. });
  62733. }
  62734. else {
  62735. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62736. }
  62737. };
  62738. FilesInput.FilesToLoad = {};
  62739. return FilesInput;
  62740. }());
  62741. BABYLON.FilesInput = FilesInput;
  62742. })(BABYLON || (BABYLON = {}));
  62743. //# sourceMappingURL=babylon.filesInput.js.map
  62744. var BABYLON;
  62745. (function (BABYLON) {
  62746. /**
  62747. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62748. * The underlying implementation relies on an associative array to ensure the best performances.
  62749. * The value can be anything including 'null' but except 'undefined'
  62750. */
  62751. var StringDictionary = /** @class */ (function () {
  62752. function StringDictionary() {
  62753. this._count = 0;
  62754. this._data = {};
  62755. }
  62756. /**
  62757. * This will clear this dictionary and copy the content from the 'source' one.
  62758. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62759. * @param source the dictionary to take the content from and copy to this dictionary
  62760. */
  62761. StringDictionary.prototype.copyFrom = function (source) {
  62762. var _this = this;
  62763. this.clear();
  62764. source.forEach(function (t, v) { return _this.add(t, v); });
  62765. };
  62766. /**
  62767. * Get a value based from its key
  62768. * @param key the given key to get the matching value from
  62769. * @return the value if found, otherwise undefined is returned
  62770. */
  62771. StringDictionary.prototype.get = function (key) {
  62772. var val = this._data[key];
  62773. if (val !== undefined) {
  62774. return val;
  62775. }
  62776. return undefined;
  62777. };
  62778. /**
  62779. * Get a value from its key or add it if it doesn't exist.
  62780. * This method will ensure you that a given key/data will be present in the dictionary.
  62781. * @param key the given key to get the matching value from
  62782. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62783. * The factory will only be invoked if there's no data for the given key.
  62784. * @return the value corresponding to the key.
  62785. */
  62786. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62787. var val = this.get(key);
  62788. if (val !== undefined) {
  62789. return val;
  62790. }
  62791. val = factory(key);
  62792. if (val) {
  62793. this.add(key, val);
  62794. }
  62795. return val;
  62796. };
  62797. /**
  62798. * Get a value from its key if present in the dictionary otherwise add it
  62799. * @param key the key to get the value from
  62800. * @param val if there's no such key/value pair in the dictionary add it with this value
  62801. * @return the value corresponding to the key
  62802. */
  62803. StringDictionary.prototype.getOrAdd = function (key, val) {
  62804. var curVal = this.get(key);
  62805. if (curVal !== undefined) {
  62806. return curVal;
  62807. }
  62808. this.add(key, val);
  62809. return val;
  62810. };
  62811. /**
  62812. * Check if there's a given key in the dictionary
  62813. * @param key the key to check for
  62814. * @return true if the key is present, false otherwise
  62815. */
  62816. StringDictionary.prototype.contains = function (key) {
  62817. return this._data[key] !== undefined;
  62818. };
  62819. /**
  62820. * Add a new key and its corresponding value
  62821. * @param key the key to add
  62822. * @param value the value corresponding to the key
  62823. * @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
  62824. */
  62825. StringDictionary.prototype.add = function (key, value) {
  62826. if (this._data[key] !== undefined) {
  62827. return false;
  62828. }
  62829. this._data[key] = value;
  62830. ++this._count;
  62831. return true;
  62832. };
  62833. StringDictionary.prototype.set = function (key, value) {
  62834. if (this._data[key] === undefined) {
  62835. return false;
  62836. }
  62837. this._data[key] = value;
  62838. return true;
  62839. };
  62840. /**
  62841. * Get the element of the given key and remove it from the dictionary
  62842. * @param key
  62843. */
  62844. StringDictionary.prototype.getAndRemove = function (key) {
  62845. var val = this.get(key);
  62846. if (val !== undefined) {
  62847. delete this._data[key];
  62848. --this._count;
  62849. return val;
  62850. }
  62851. return null;
  62852. };
  62853. /**
  62854. * Remove a key/value from the dictionary.
  62855. * @param key the key to remove
  62856. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62857. */
  62858. StringDictionary.prototype.remove = function (key) {
  62859. if (this.contains(key)) {
  62860. delete this._data[key];
  62861. --this._count;
  62862. return true;
  62863. }
  62864. return false;
  62865. };
  62866. /**
  62867. * Clear the whole content of the dictionary
  62868. */
  62869. StringDictionary.prototype.clear = function () {
  62870. this._data = {};
  62871. this._count = 0;
  62872. };
  62873. Object.defineProperty(StringDictionary.prototype, "count", {
  62874. get: function () {
  62875. return this._count;
  62876. },
  62877. enumerable: true,
  62878. configurable: true
  62879. });
  62880. /**
  62881. * Execute a callback on each key/val of the dictionary.
  62882. * Note that you can remove any element in this dictionary in the callback implementation
  62883. * @param callback the callback to execute on a given key/value pair
  62884. */
  62885. StringDictionary.prototype.forEach = function (callback) {
  62886. for (var cur in this._data) {
  62887. var val = this._data[cur];
  62888. callback(cur, val);
  62889. }
  62890. };
  62891. /**
  62892. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62893. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62894. * Note that you can remove any element in this dictionary in the callback implementation
  62895. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62896. */
  62897. StringDictionary.prototype.first = function (callback) {
  62898. for (var cur in this._data) {
  62899. var val = this._data[cur];
  62900. var res = callback(cur, val);
  62901. if (res) {
  62902. return res;
  62903. }
  62904. }
  62905. return null;
  62906. };
  62907. return StringDictionary;
  62908. }());
  62909. BABYLON.StringDictionary = StringDictionary;
  62910. })(BABYLON || (BABYLON = {}));
  62911. //# sourceMappingURL=babylon.stringDictionary.js.map
  62912. var BABYLON;
  62913. (function (BABYLON) {
  62914. var Tags = /** @class */ (function () {
  62915. function Tags() {
  62916. }
  62917. Tags.EnableFor = function (obj) {
  62918. obj._tags = obj._tags || {};
  62919. obj.hasTags = function () {
  62920. return Tags.HasTags(obj);
  62921. };
  62922. obj.addTags = function (tagsString) {
  62923. return Tags.AddTagsTo(obj, tagsString);
  62924. };
  62925. obj.removeTags = function (tagsString) {
  62926. return Tags.RemoveTagsFrom(obj, tagsString);
  62927. };
  62928. obj.matchesTagsQuery = function (tagsQuery) {
  62929. return Tags.MatchesQuery(obj, tagsQuery);
  62930. };
  62931. };
  62932. Tags.DisableFor = function (obj) {
  62933. delete obj._tags;
  62934. delete obj.hasTags;
  62935. delete obj.addTags;
  62936. delete obj.removeTags;
  62937. delete obj.matchesTagsQuery;
  62938. };
  62939. Tags.HasTags = function (obj) {
  62940. if (!obj._tags) {
  62941. return false;
  62942. }
  62943. return !BABYLON.Tools.IsEmpty(obj._tags);
  62944. };
  62945. Tags.GetTags = function (obj, asString) {
  62946. if (asString === void 0) { asString = true; }
  62947. if (!obj._tags) {
  62948. return null;
  62949. }
  62950. if (asString) {
  62951. var tagsArray = [];
  62952. for (var tag in obj._tags) {
  62953. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62954. tagsArray.push(tag);
  62955. }
  62956. }
  62957. return tagsArray.join(" ");
  62958. }
  62959. else {
  62960. return obj._tags;
  62961. }
  62962. };
  62963. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62964. // a tag cannot start with '||', '&&', and '!'
  62965. // it cannot contain whitespaces
  62966. Tags.AddTagsTo = function (obj, tagsString) {
  62967. if (!tagsString) {
  62968. return;
  62969. }
  62970. if (typeof tagsString !== "string") {
  62971. return;
  62972. }
  62973. var tags = tagsString.split(" ");
  62974. tags.forEach(function (tag, index, array) {
  62975. Tags._AddTagTo(obj, tag);
  62976. });
  62977. };
  62978. Tags._AddTagTo = function (obj, tag) {
  62979. tag = tag.trim();
  62980. if (tag === "" || tag === "true" || tag === "false") {
  62981. return;
  62982. }
  62983. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62984. return;
  62985. }
  62986. Tags.EnableFor(obj);
  62987. obj._tags[tag] = true;
  62988. };
  62989. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62990. if (!Tags.HasTags(obj)) {
  62991. return;
  62992. }
  62993. var tags = tagsString.split(" ");
  62994. for (var t in tags) {
  62995. Tags._RemoveTagFrom(obj, tags[t]);
  62996. }
  62997. };
  62998. Tags._RemoveTagFrom = function (obj, tag) {
  62999. delete obj._tags[tag];
  63000. };
  63001. Tags.MatchesQuery = function (obj, tagsQuery) {
  63002. if (tagsQuery === undefined) {
  63003. return true;
  63004. }
  63005. if (tagsQuery === "") {
  63006. return Tags.HasTags(obj);
  63007. }
  63008. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63009. };
  63010. return Tags;
  63011. }());
  63012. BABYLON.Tags = Tags;
  63013. })(BABYLON || (BABYLON = {}));
  63014. //# sourceMappingURL=babylon.tags.js.map
  63015. var BABYLON;
  63016. (function (BABYLON) {
  63017. var AndOrNotEvaluator = /** @class */ (function () {
  63018. function AndOrNotEvaluator() {
  63019. }
  63020. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63021. if (!query.match(/\([^\(\)]*\)/g)) {
  63022. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63023. }
  63024. else {
  63025. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63026. // remove parenthesis
  63027. r = r.slice(1, r.length - 1);
  63028. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63029. });
  63030. }
  63031. if (query === "true") {
  63032. return true;
  63033. }
  63034. if (query === "false") {
  63035. return false;
  63036. }
  63037. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63038. };
  63039. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63040. evaluateCallback = evaluateCallback || (function (r) {
  63041. return r === "true" ? true : false;
  63042. });
  63043. var result;
  63044. var or = parenthesisContent.split("||");
  63045. for (var i in or) {
  63046. if (or.hasOwnProperty(i)) {
  63047. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63048. var and = ori.split("&&");
  63049. if (and.length > 1) {
  63050. for (var j = 0; j < and.length; ++j) {
  63051. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63052. if (andj !== "true" && andj !== "false") {
  63053. if (andj[0] === "!") {
  63054. result = !evaluateCallback(andj.substring(1));
  63055. }
  63056. else {
  63057. result = evaluateCallback(andj);
  63058. }
  63059. }
  63060. else {
  63061. result = andj === "true" ? true : false;
  63062. }
  63063. if (!result) {
  63064. ori = "false";
  63065. break;
  63066. }
  63067. }
  63068. }
  63069. if (result || ori === "true") {
  63070. result = true;
  63071. break;
  63072. }
  63073. // result equals false (or undefined)
  63074. if (ori !== "true" && ori !== "false") {
  63075. if (ori[0] === "!") {
  63076. result = !evaluateCallback(ori.substring(1));
  63077. }
  63078. else {
  63079. result = evaluateCallback(ori);
  63080. }
  63081. }
  63082. else {
  63083. result = ori === "true" ? true : false;
  63084. }
  63085. }
  63086. }
  63087. // the whole parenthesis scope is replaced by 'true' or 'false'
  63088. return result ? "true" : "false";
  63089. };
  63090. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63091. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63092. // remove whitespaces
  63093. r = r.replace(/[\s]/g, function () { return ""; });
  63094. return r.length % 2 ? "!" : "";
  63095. });
  63096. booleanString = booleanString.trim();
  63097. if (booleanString === "!true") {
  63098. booleanString = "false";
  63099. }
  63100. else if (booleanString === "!false") {
  63101. booleanString = "true";
  63102. }
  63103. return booleanString;
  63104. };
  63105. return AndOrNotEvaluator;
  63106. }());
  63107. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63108. })(BABYLON || (BABYLON = {}));
  63109. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63110. var BABYLON;
  63111. (function (BABYLON) {
  63112. var Database = /** @class */ (function () {
  63113. function Database(urlToScene, callbackManifestChecked) {
  63114. // Handling various flavors of prefixed version of IndexedDB
  63115. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63116. this.callbackManifestChecked = callbackManifestChecked;
  63117. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63118. this.db = null;
  63119. this._enableSceneOffline = false;
  63120. this._enableTexturesOffline = false;
  63121. this.manifestVersionFound = 0;
  63122. this.mustUpdateRessources = false;
  63123. this.hasReachedQuota = false;
  63124. if (!Database.IDBStorageEnabled) {
  63125. this.callbackManifestChecked(true);
  63126. }
  63127. else {
  63128. this.checkManifestFile();
  63129. }
  63130. }
  63131. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63132. get: function () {
  63133. return this._enableSceneOffline;
  63134. },
  63135. enumerable: true,
  63136. configurable: true
  63137. });
  63138. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63139. get: function () {
  63140. return this._enableTexturesOffline;
  63141. },
  63142. enumerable: true,
  63143. configurable: true
  63144. });
  63145. Database.prototype.checkManifestFile = function () {
  63146. var _this = this;
  63147. var noManifestFile = function () {
  63148. _this._enableSceneOffline = false;
  63149. _this._enableTexturesOffline = false;
  63150. _this.callbackManifestChecked(false);
  63151. };
  63152. var timeStampUsed = false;
  63153. var manifestURL = this.currentSceneUrl + ".manifest";
  63154. var xhr = new XMLHttpRequest();
  63155. if (navigator.onLine) {
  63156. // Adding a timestamp to by-pass browsers' cache
  63157. timeStampUsed = true;
  63158. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63159. }
  63160. xhr.open("GET", manifestURL, true);
  63161. xhr.addEventListener("load", function () {
  63162. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63163. try {
  63164. var manifestFile = JSON.parse(xhr.response);
  63165. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63166. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63167. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63168. _this.manifestVersionFound = manifestFile.version;
  63169. }
  63170. if (_this.callbackManifestChecked) {
  63171. _this.callbackManifestChecked(true);
  63172. }
  63173. }
  63174. catch (ex) {
  63175. noManifestFile();
  63176. }
  63177. }
  63178. else {
  63179. noManifestFile();
  63180. }
  63181. }, false);
  63182. xhr.addEventListener("error", function (event) {
  63183. if (timeStampUsed) {
  63184. timeStampUsed = false;
  63185. // Let's retry without the timeStamp
  63186. // It could fail when coupled with HTML5 Offline API
  63187. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63188. xhr.open("GET", retryManifestURL, true);
  63189. xhr.send();
  63190. }
  63191. else {
  63192. noManifestFile();
  63193. }
  63194. }, false);
  63195. try {
  63196. xhr.send();
  63197. }
  63198. catch (ex) {
  63199. BABYLON.Tools.Error("Error on XHR send request.");
  63200. this.callbackManifestChecked(false);
  63201. }
  63202. };
  63203. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63204. var _this = this;
  63205. var handleError = function () {
  63206. _this.isSupported = false;
  63207. if (errorCallback)
  63208. errorCallback();
  63209. };
  63210. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63211. // Your browser doesn't support IndexedDB
  63212. this.isSupported = false;
  63213. if (errorCallback)
  63214. errorCallback();
  63215. }
  63216. else {
  63217. // If the DB hasn't been opened or created yet
  63218. if (!this.db) {
  63219. this.hasReachedQuota = false;
  63220. this.isSupported = true;
  63221. var request = this.idbFactory.open("babylonjs", 1);
  63222. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63223. request.onerror = function (event) {
  63224. handleError();
  63225. };
  63226. // executes when a version change transaction cannot complete due to other active transactions
  63227. request.onblocked = function (event) {
  63228. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63229. handleError();
  63230. };
  63231. // DB has been opened successfully
  63232. request.onsuccess = function (event) {
  63233. _this.db = request.result;
  63234. successCallback();
  63235. };
  63236. // Initialization of the DB. Creating Scenes & Textures stores
  63237. request.onupgradeneeded = function (event) {
  63238. _this.db = (event.target).result;
  63239. if (_this.db) {
  63240. try {
  63241. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63242. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63243. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63244. }
  63245. catch (ex) {
  63246. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63247. handleError();
  63248. }
  63249. }
  63250. };
  63251. }
  63252. else {
  63253. if (successCallback)
  63254. successCallback();
  63255. }
  63256. }
  63257. };
  63258. Database.prototype.loadImageFromDB = function (url, image) {
  63259. var _this = this;
  63260. var completeURL = Database.ReturnFullUrlLocation(url);
  63261. var saveAndLoadImage = function () {
  63262. if (!_this.hasReachedQuota && _this.db !== null) {
  63263. // the texture is not yet in the DB, let's try to save it
  63264. _this._saveImageIntoDBAsync(completeURL, image);
  63265. }
  63266. else {
  63267. image.src = url;
  63268. }
  63269. };
  63270. if (!this.mustUpdateRessources) {
  63271. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63272. }
  63273. else {
  63274. saveAndLoadImage();
  63275. }
  63276. };
  63277. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63278. if (this.isSupported && this.db !== null) {
  63279. var texture;
  63280. var transaction = this.db.transaction(["textures"]);
  63281. transaction.onabort = function (event) {
  63282. image.src = url;
  63283. };
  63284. transaction.oncomplete = function (event) {
  63285. var blobTextureURL;
  63286. if (texture) {
  63287. var URL = window.URL || window.webkitURL;
  63288. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63289. image.onerror = function () {
  63290. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63291. image.src = url;
  63292. };
  63293. image.src = blobTextureURL;
  63294. }
  63295. else {
  63296. notInDBCallback();
  63297. }
  63298. };
  63299. var getRequest = transaction.objectStore("textures").get(url);
  63300. getRequest.onsuccess = function (event) {
  63301. texture = (event.target).result;
  63302. };
  63303. getRequest.onerror = function (event) {
  63304. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63305. image.src = url;
  63306. };
  63307. }
  63308. else {
  63309. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63310. image.src = url;
  63311. }
  63312. };
  63313. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63314. var _this = this;
  63315. if (this.isSupported) {
  63316. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63317. var generateBlobUrl = function () {
  63318. var blobTextureURL;
  63319. if (blob) {
  63320. var URL = window.URL || window.webkitURL;
  63321. try {
  63322. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63323. }
  63324. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63325. catch (ex) {
  63326. blobTextureURL = URL.createObjectURL(blob);
  63327. }
  63328. }
  63329. if (blobTextureURL) {
  63330. image.src = blobTextureURL;
  63331. }
  63332. };
  63333. if (Database.IsUASupportingBlobStorage) {
  63334. var xhr = new XMLHttpRequest(), blob;
  63335. xhr.open("GET", url, true);
  63336. xhr.responseType = "blob";
  63337. xhr.addEventListener("load", function () {
  63338. if (xhr.status === 200 && _this.db) {
  63339. // Blob as response (XHR2)
  63340. blob = xhr.response;
  63341. var transaction = _this.db.transaction(["textures"], "readwrite");
  63342. // the transaction could abort because of a QuotaExceededError error
  63343. transaction.onabort = function (event) {
  63344. try {
  63345. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63346. var srcElement = (event.srcElement || event.target);
  63347. var error = srcElement.error;
  63348. if (error && error.name === "QuotaExceededError") {
  63349. _this.hasReachedQuota = true;
  63350. }
  63351. }
  63352. catch (ex) { }
  63353. generateBlobUrl();
  63354. };
  63355. transaction.oncomplete = function (event) {
  63356. generateBlobUrl();
  63357. };
  63358. var newTexture = { textureUrl: url, data: blob };
  63359. try {
  63360. // Put the blob into the dabase
  63361. var addRequest = transaction.objectStore("textures").put(newTexture);
  63362. addRequest.onsuccess = function (event) {
  63363. };
  63364. addRequest.onerror = function (event) {
  63365. generateBlobUrl();
  63366. };
  63367. }
  63368. catch (ex) {
  63369. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63370. if (ex.code === 25) {
  63371. Database.IsUASupportingBlobStorage = false;
  63372. }
  63373. image.src = url;
  63374. }
  63375. }
  63376. else {
  63377. image.src = url;
  63378. }
  63379. }, false);
  63380. xhr.addEventListener("error", function (event) {
  63381. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63382. image.src = url;
  63383. }, false);
  63384. xhr.send();
  63385. }
  63386. else {
  63387. image.src = url;
  63388. }
  63389. }
  63390. else {
  63391. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63392. image.src = url;
  63393. }
  63394. };
  63395. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63396. var _this = this;
  63397. var updateVersion = function () {
  63398. // the version is not yet in the DB or we need to update it
  63399. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63400. };
  63401. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63402. };
  63403. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63404. var _this = this;
  63405. if (this.isSupported && this.db) {
  63406. var version;
  63407. try {
  63408. var transaction = this.db.transaction(["versions"]);
  63409. transaction.oncomplete = function (event) {
  63410. if (version) {
  63411. // If the version in the JSON file is > than the version in DB
  63412. if (_this.manifestVersionFound > version.data) {
  63413. _this.mustUpdateRessources = true;
  63414. updateInDBCallback();
  63415. }
  63416. else {
  63417. callback(version.data);
  63418. }
  63419. }
  63420. else {
  63421. _this.mustUpdateRessources = true;
  63422. updateInDBCallback();
  63423. }
  63424. };
  63425. transaction.onabort = function (event) {
  63426. callback(-1);
  63427. };
  63428. var getRequest = transaction.objectStore("versions").get(url);
  63429. getRequest.onsuccess = function (event) {
  63430. version = (event.target).result;
  63431. };
  63432. getRequest.onerror = function (event) {
  63433. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63434. callback(-1);
  63435. };
  63436. }
  63437. catch (ex) {
  63438. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63439. callback(-1);
  63440. }
  63441. }
  63442. else {
  63443. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63444. callback(-1);
  63445. }
  63446. };
  63447. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63448. var _this = this;
  63449. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63450. try {
  63451. // Open a transaction to the database
  63452. var transaction = this.db.transaction(["versions"], "readwrite");
  63453. // the transaction could abort because of a QuotaExceededError error
  63454. transaction.onabort = function (event) {
  63455. try {
  63456. var error = event.srcElement['error'];
  63457. if (error && error.name === "QuotaExceededError") {
  63458. _this.hasReachedQuota = true;
  63459. }
  63460. }
  63461. catch (ex) { }
  63462. callback(-1);
  63463. };
  63464. transaction.oncomplete = function (event) {
  63465. callback(_this.manifestVersionFound);
  63466. };
  63467. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63468. // Put the scene into the database
  63469. var addRequest = transaction.objectStore("versions").put(newVersion);
  63470. addRequest.onsuccess = function (event) {
  63471. };
  63472. addRequest.onerror = function (event) {
  63473. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63474. };
  63475. }
  63476. catch (ex) {
  63477. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63478. callback(-1);
  63479. }
  63480. }
  63481. else {
  63482. callback(-1);
  63483. }
  63484. };
  63485. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63486. var _this = this;
  63487. var completeUrl = Database.ReturnFullUrlLocation(url);
  63488. var saveAndLoadFile = function () {
  63489. // the scene is not yet in the DB, let's try to save it
  63490. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63491. };
  63492. this._checkVersionFromDB(completeUrl, function (version) {
  63493. if (version !== -1) {
  63494. if (!_this.mustUpdateRessources) {
  63495. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63496. }
  63497. else {
  63498. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63499. }
  63500. }
  63501. else {
  63502. if (errorCallback) {
  63503. errorCallback();
  63504. }
  63505. }
  63506. });
  63507. };
  63508. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63509. if (this.isSupported && this.db) {
  63510. var targetStore;
  63511. if (url.indexOf(".babylon") !== -1) {
  63512. targetStore = "scenes";
  63513. }
  63514. else {
  63515. targetStore = "textures";
  63516. }
  63517. var file;
  63518. var transaction = this.db.transaction([targetStore]);
  63519. transaction.oncomplete = function (event) {
  63520. if (file) {
  63521. callback(file.data);
  63522. }
  63523. else {
  63524. notInDBCallback();
  63525. }
  63526. };
  63527. transaction.onabort = function (event) {
  63528. notInDBCallback();
  63529. };
  63530. var getRequest = transaction.objectStore(targetStore).get(url);
  63531. getRequest.onsuccess = function (event) {
  63532. file = (event.target).result;
  63533. };
  63534. getRequest.onerror = function (event) {
  63535. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63536. notInDBCallback();
  63537. };
  63538. }
  63539. else {
  63540. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63541. callback();
  63542. }
  63543. };
  63544. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63545. var _this = this;
  63546. if (this.isSupported) {
  63547. var targetStore;
  63548. if (url.indexOf(".babylon") !== -1) {
  63549. targetStore = "scenes";
  63550. }
  63551. else {
  63552. targetStore = "textures";
  63553. }
  63554. // Create XHR
  63555. var xhr = new XMLHttpRequest();
  63556. var fileData;
  63557. xhr.open("GET", url, true);
  63558. if (useArrayBuffer) {
  63559. xhr.responseType = "arraybuffer";
  63560. }
  63561. if (progressCallback) {
  63562. xhr.onprogress = progressCallback;
  63563. }
  63564. xhr.addEventListener("load", function () {
  63565. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63566. // Blob as response (XHR2)
  63567. //fileData = xhr.responseText;
  63568. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63569. if (!_this.hasReachedQuota && _this.db) {
  63570. // Open a transaction to the database
  63571. var transaction = _this.db.transaction([targetStore], "readwrite");
  63572. // the transaction could abort because of a QuotaExceededError error
  63573. transaction.onabort = function (event) {
  63574. try {
  63575. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63576. var error = event.srcElement['error'];
  63577. if (error && error.name === "QuotaExceededError") {
  63578. _this.hasReachedQuota = true;
  63579. }
  63580. }
  63581. catch (ex) { }
  63582. callback(fileData);
  63583. };
  63584. transaction.oncomplete = function (event) {
  63585. callback(fileData);
  63586. };
  63587. var newFile;
  63588. if (targetStore === "scenes") {
  63589. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63590. }
  63591. else {
  63592. newFile = { textureUrl: url, data: fileData };
  63593. }
  63594. try {
  63595. // Put the scene into the database
  63596. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63597. addRequest.onsuccess = function (event) {
  63598. };
  63599. addRequest.onerror = function (event) {
  63600. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63601. };
  63602. }
  63603. catch (ex) {
  63604. callback(fileData);
  63605. }
  63606. }
  63607. else {
  63608. callback(fileData);
  63609. }
  63610. }
  63611. else {
  63612. callback();
  63613. }
  63614. }, false);
  63615. xhr.addEventListener("error", function (event) {
  63616. BABYLON.Tools.Error("error on XHR request.");
  63617. callback();
  63618. }, false);
  63619. xhr.send();
  63620. }
  63621. else {
  63622. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63623. callback();
  63624. }
  63625. };
  63626. Database.IsUASupportingBlobStorage = true;
  63627. Database.IDBStorageEnabled = true;
  63628. Database.parseURL = function (url) {
  63629. var a = document.createElement('a');
  63630. a.href = url;
  63631. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63632. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63633. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63634. return absLocation;
  63635. };
  63636. Database.ReturnFullUrlLocation = function (url) {
  63637. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63638. return (Database.parseURL(window.location.href) + url);
  63639. }
  63640. else {
  63641. return url;
  63642. }
  63643. };
  63644. return Database;
  63645. }());
  63646. BABYLON.Database = Database;
  63647. })(BABYLON || (BABYLON = {}));
  63648. //# sourceMappingURL=babylon.database.js.map
  63649. var BABYLON;
  63650. (function (BABYLON) {
  63651. var FresnelParameters = /** @class */ (function () {
  63652. function FresnelParameters() {
  63653. this._isEnabled = true;
  63654. this.leftColor = BABYLON.Color3.White();
  63655. this.rightColor = BABYLON.Color3.Black();
  63656. this.bias = 0;
  63657. this.power = 1;
  63658. }
  63659. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63660. get: function () {
  63661. return this._isEnabled;
  63662. },
  63663. set: function (value) {
  63664. if (this._isEnabled === value) {
  63665. return;
  63666. }
  63667. this._isEnabled = value;
  63668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63669. },
  63670. enumerable: true,
  63671. configurable: true
  63672. });
  63673. FresnelParameters.prototype.clone = function () {
  63674. var newFresnelParameters = new FresnelParameters();
  63675. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63676. return newFresnelParameters;
  63677. };
  63678. FresnelParameters.prototype.serialize = function () {
  63679. var serializationObject = {};
  63680. serializationObject.isEnabled = this.isEnabled;
  63681. serializationObject.leftColor = this.leftColor;
  63682. serializationObject.rightColor = this.rightColor;
  63683. serializationObject.bias = this.bias;
  63684. serializationObject.power = this.power;
  63685. return serializationObject;
  63686. };
  63687. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63688. var fresnelParameters = new FresnelParameters();
  63689. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63690. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63691. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63692. fresnelParameters.bias = parsedFresnelParameters.bias;
  63693. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63694. return fresnelParameters;
  63695. };
  63696. return FresnelParameters;
  63697. }());
  63698. BABYLON.FresnelParameters = FresnelParameters;
  63699. })(BABYLON || (BABYLON = {}));
  63700. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63701. var BABYLON;
  63702. (function (BABYLON) {
  63703. var MultiMaterial = /** @class */ (function (_super) {
  63704. __extends(MultiMaterial, _super);
  63705. function MultiMaterial(name, scene) {
  63706. var _this = _super.call(this, name, scene, true) || this;
  63707. scene.multiMaterials.push(_this);
  63708. _this.subMaterials = new Array();
  63709. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63710. return _this;
  63711. }
  63712. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63713. get: function () {
  63714. return this._subMaterials;
  63715. },
  63716. set: function (value) {
  63717. this._subMaterials = value;
  63718. this._hookArray(value);
  63719. },
  63720. enumerable: true,
  63721. configurable: true
  63722. });
  63723. MultiMaterial.prototype._hookArray = function (array) {
  63724. var _this = this;
  63725. var oldPush = array.push;
  63726. array.push = function () {
  63727. var items = [];
  63728. for (var _i = 0; _i < arguments.length; _i++) {
  63729. items[_i] = arguments[_i];
  63730. }
  63731. var result = oldPush.apply(array, items);
  63732. _this._markAllSubMeshesAsTexturesDirty();
  63733. return result;
  63734. };
  63735. var oldSplice = array.splice;
  63736. array.splice = function (index, deleteCount) {
  63737. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63738. _this._markAllSubMeshesAsTexturesDirty();
  63739. return deleted;
  63740. };
  63741. };
  63742. // Properties
  63743. MultiMaterial.prototype.getSubMaterial = function (index) {
  63744. if (index < 0 || index >= this.subMaterials.length) {
  63745. return this.getScene().defaultMaterial;
  63746. }
  63747. return this.subMaterials[index];
  63748. };
  63749. MultiMaterial.prototype.getActiveTextures = function () {
  63750. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63751. if (subMaterial) {
  63752. return subMaterial.getActiveTextures();
  63753. }
  63754. else {
  63755. return [];
  63756. }
  63757. }));
  63758. var _a;
  63759. };
  63760. // Methods
  63761. MultiMaterial.prototype.getClassName = function () {
  63762. return "MultiMaterial";
  63763. };
  63764. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63765. for (var index = 0; index < this.subMaterials.length; index++) {
  63766. var subMaterial = this.subMaterials[index];
  63767. if (subMaterial) {
  63768. if (subMaterial.storeEffectOnSubMeshes) {
  63769. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63770. return false;
  63771. }
  63772. continue;
  63773. }
  63774. if (!subMaterial.isReady(mesh)) {
  63775. return false;
  63776. }
  63777. }
  63778. }
  63779. return true;
  63780. };
  63781. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63782. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63783. for (var index = 0; index < this.subMaterials.length; index++) {
  63784. var subMaterial = null;
  63785. var current = this.subMaterials[index];
  63786. if (cloneChildren && current) {
  63787. subMaterial = current.clone(name + "-" + current.name);
  63788. }
  63789. else {
  63790. subMaterial = this.subMaterials[index];
  63791. }
  63792. newMultiMaterial.subMaterials.push(subMaterial);
  63793. }
  63794. return newMultiMaterial;
  63795. };
  63796. MultiMaterial.prototype.serialize = function () {
  63797. var serializationObject = {};
  63798. serializationObject.name = this.name;
  63799. serializationObject.id = this.id;
  63800. if (BABYLON.Tags) {
  63801. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63802. }
  63803. serializationObject.materials = [];
  63804. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63805. var subMat = this.subMaterials[matIndex];
  63806. if (subMat) {
  63807. serializationObject.materials.push(subMat.id);
  63808. }
  63809. else {
  63810. serializationObject.materials.push(null);
  63811. }
  63812. }
  63813. return serializationObject;
  63814. };
  63815. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63816. var scene = this.getScene();
  63817. if (!scene) {
  63818. return;
  63819. }
  63820. var index = scene.multiMaterials.indexOf(this);
  63821. if (index >= 0) {
  63822. scene.multiMaterials.splice(index, 1);
  63823. }
  63824. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63825. };
  63826. return MultiMaterial;
  63827. }(BABYLON.Material));
  63828. BABYLON.MultiMaterial = MultiMaterial;
  63829. })(BABYLON || (BABYLON = {}));
  63830. //# sourceMappingURL=babylon.multiMaterial.js.map
  63831. var BABYLON;
  63832. (function (BABYLON) {
  63833. var FreeCameraTouchInput = /** @class */ (function () {
  63834. function FreeCameraTouchInput() {
  63835. this._offsetX = null;
  63836. this._offsetY = null;
  63837. this._pointerPressed = new Array();
  63838. this.touchAngularSensibility = 200000.0;
  63839. this.touchMoveSensibility = 250.0;
  63840. }
  63841. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63842. var _this = this;
  63843. var previousPosition = null;
  63844. if (this._pointerInput === undefined) {
  63845. this._onLostFocus = function (evt) {
  63846. _this._offsetX = null;
  63847. _this._offsetY = null;
  63848. };
  63849. this._pointerInput = function (p, s) {
  63850. var evt = p.event;
  63851. if (evt.pointerType === "mouse") {
  63852. return;
  63853. }
  63854. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63855. if (!noPreventDefault) {
  63856. evt.preventDefault();
  63857. }
  63858. _this._pointerPressed.push(evt.pointerId);
  63859. if (_this._pointerPressed.length !== 1) {
  63860. return;
  63861. }
  63862. previousPosition = {
  63863. x: evt.clientX,
  63864. y: evt.clientY
  63865. };
  63866. }
  63867. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63868. if (!noPreventDefault) {
  63869. evt.preventDefault();
  63870. }
  63871. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63872. if (index === -1) {
  63873. return;
  63874. }
  63875. _this._pointerPressed.splice(index, 1);
  63876. if (index != 0) {
  63877. return;
  63878. }
  63879. previousPosition = null;
  63880. _this._offsetX = null;
  63881. _this._offsetY = null;
  63882. }
  63883. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63884. if (!noPreventDefault) {
  63885. evt.preventDefault();
  63886. }
  63887. if (!previousPosition) {
  63888. return;
  63889. }
  63890. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63891. if (index != 0) {
  63892. return;
  63893. }
  63894. _this._offsetX = evt.clientX - previousPosition.x;
  63895. _this._offsetY = -(evt.clientY - previousPosition.y);
  63896. }
  63897. };
  63898. }
  63899. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63900. if (this._onLostFocus) {
  63901. element.addEventListener("blur", this._onLostFocus);
  63902. }
  63903. };
  63904. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63905. if (this._pointerInput && element) {
  63906. if (this._observer) {
  63907. this.camera.getScene().onPointerObservable.remove(this._observer);
  63908. this._observer = null;
  63909. }
  63910. if (this._onLostFocus) {
  63911. element.removeEventListener("blur", this._onLostFocus);
  63912. this._onLostFocus = null;
  63913. }
  63914. this._pointerPressed = [];
  63915. this._offsetX = null;
  63916. this._offsetY = null;
  63917. }
  63918. };
  63919. FreeCameraTouchInput.prototype.checkInputs = function () {
  63920. if (this._offsetX && this._offsetY) {
  63921. var camera = this.camera;
  63922. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63923. if (this._pointerPressed.length > 1) {
  63924. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63925. }
  63926. else {
  63927. var speed = camera._computeLocalCameraSpeed();
  63928. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63929. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63930. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63931. }
  63932. }
  63933. };
  63934. FreeCameraTouchInput.prototype.getClassName = function () {
  63935. return "FreeCameraTouchInput";
  63936. };
  63937. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63938. return "touch";
  63939. };
  63940. __decorate([
  63941. BABYLON.serialize()
  63942. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63943. __decorate([
  63944. BABYLON.serialize()
  63945. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63946. return FreeCameraTouchInput;
  63947. }());
  63948. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63949. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63950. })(BABYLON || (BABYLON = {}));
  63951. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63952. var BABYLON;
  63953. (function (BABYLON) {
  63954. // We're mainly based on the logic defined into the FreeCamera code
  63955. var TouchCamera = /** @class */ (function (_super) {
  63956. __extends(TouchCamera, _super);
  63957. //-- end properties for backward compatibility for inputs
  63958. function TouchCamera(name, position, scene) {
  63959. var _this = _super.call(this, name, position, scene) || this;
  63960. _this.inputs.addTouch();
  63961. _this._setupInputs();
  63962. return _this;
  63963. }
  63964. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63965. //-- Begin properties for backward compatibility for inputs
  63966. get: function () {
  63967. var touch = this.inputs.attached["touch"];
  63968. if (touch)
  63969. return touch.touchAngularSensibility;
  63970. return 0;
  63971. },
  63972. set: function (value) {
  63973. var touch = this.inputs.attached["touch"];
  63974. if (touch)
  63975. touch.touchAngularSensibility = value;
  63976. },
  63977. enumerable: true,
  63978. configurable: true
  63979. });
  63980. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63981. get: function () {
  63982. var touch = this.inputs.attached["touch"];
  63983. if (touch)
  63984. return touch.touchMoveSensibility;
  63985. return 0;
  63986. },
  63987. set: function (value) {
  63988. var touch = this.inputs.attached["touch"];
  63989. if (touch)
  63990. touch.touchMoveSensibility = value;
  63991. },
  63992. enumerable: true,
  63993. configurable: true
  63994. });
  63995. TouchCamera.prototype.getClassName = function () {
  63996. return "TouchCamera";
  63997. };
  63998. TouchCamera.prototype._setupInputs = function () {
  63999. var mouse = this.inputs.attached["mouse"];
  64000. if (mouse) {
  64001. mouse.touchEnabled = false;
  64002. }
  64003. };
  64004. return TouchCamera;
  64005. }(BABYLON.FreeCamera));
  64006. BABYLON.TouchCamera = TouchCamera;
  64007. })(BABYLON || (BABYLON = {}));
  64008. //# sourceMappingURL=babylon.touchCamera.js.map
  64009. var BABYLON;
  64010. (function (BABYLON) {
  64011. var ProceduralTexture = /** @class */ (function (_super) {
  64012. __extends(ProceduralTexture, _super);
  64013. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64014. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64016. if (isCube === void 0) { isCube = false; }
  64017. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64018. _this.isCube = isCube;
  64019. _this.isEnabled = true;
  64020. _this._currentRefreshId = -1;
  64021. _this._refreshRate = 1;
  64022. _this._vertexBuffers = {};
  64023. _this._uniforms = new Array();
  64024. _this._samplers = new Array();
  64025. _this._textures = {};
  64026. _this._floats = {};
  64027. _this._floatsArrays = {};
  64028. _this._colors3 = {};
  64029. _this._colors4 = {};
  64030. _this._vectors2 = {};
  64031. _this._vectors3 = {};
  64032. _this._matrices = {};
  64033. _this._fallbackTextureUsed = false;
  64034. scene._proceduralTextures.push(_this);
  64035. _this._engine = scene.getEngine();
  64036. _this.name = name;
  64037. _this.isRenderTarget = true;
  64038. _this._size = size;
  64039. _this._generateMipMaps = generateMipMaps;
  64040. _this.setFragment(fragment);
  64041. _this._fallbackTexture = fallbackTexture;
  64042. if (isCube) {
  64043. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64044. _this.setFloat("face", 0);
  64045. }
  64046. else {
  64047. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64048. }
  64049. // VBO
  64050. var vertices = [];
  64051. vertices.push(1, 1);
  64052. vertices.push(-1, 1);
  64053. vertices.push(-1, -1);
  64054. vertices.push(1, -1);
  64055. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64056. _this._createIndexBuffer();
  64057. return _this;
  64058. }
  64059. ProceduralTexture.prototype._createIndexBuffer = function () {
  64060. var engine = this._engine;
  64061. // Indices
  64062. var indices = [];
  64063. indices.push(0);
  64064. indices.push(1);
  64065. indices.push(2);
  64066. indices.push(0);
  64067. indices.push(2);
  64068. indices.push(3);
  64069. this._indexBuffer = engine.createIndexBuffer(indices);
  64070. };
  64071. ProceduralTexture.prototype._rebuild = function () {
  64072. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64073. if (vb) {
  64074. vb._rebuild();
  64075. }
  64076. this._createIndexBuffer();
  64077. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64078. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64079. }
  64080. };
  64081. ProceduralTexture.prototype.reset = function () {
  64082. if (this._effect === undefined) {
  64083. return;
  64084. }
  64085. var engine = this._engine;
  64086. engine._releaseEffect(this._effect);
  64087. };
  64088. ProceduralTexture.prototype.isReady = function () {
  64089. var _this = this;
  64090. var engine = this._engine;
  64091. var shaders;
  64092. if (!this._fragment) {
  64093. return false;
  64094. }
  64095. if (this._fallbackTextureUsed) {
  64096. return true;
  64097. }
  64098. if (this._fragment.fragmentElement !== undefined) {
  64099. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64100. }
  64101. else {
  64102. shaders = { vertex: "procedural", fragment: this._fragment };
  64103. }
  64104. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64105. _this.releaseInternalTexture();
  64106. if (_this._fallbackTexture) {
  64107. _this._texture = _this._fallbackTexture._texture;
  64108. if (_this._texture) {
  64109. _this._texture.incrementReferences();
  64110. }
  64111. }
  64112. _this._fallbackTextureUsed = true;
  64113. });
  64114. return this._effect.isReady();
  64115. };
  64116. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64117. this._currentRefreshId = -1;
  64118. };
  64119. ProceduralTexture.prototype.setFragment = function (fragment) {
  64120. this._fragment = fragment;
  64121. };
  64122. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64123. get: function () {
  64124. return this._refreshRate;
  64125. },
  64126. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64127. set: function (value) {
  64128. this._refreshRate = value;
  64129. this.resetRefreshCounter();
  64130. },
  64131. enumerable: true,
  64132. configurable: true
  64133. });
  64134. ProceduralTexture.prototype._shouldRender = function () {
  64135. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64136. return false;
  64137. }
  64138. if (this._fallbackTextureUsed) {
  64139. return false;
  64140. }
  64141. if (this._currentRefreshId === -1) {
  64142. this._currentRefreshId = 1;
  64143. return true;
  64144. }
  64145. if (this.refreshRate === this._currentRefreshId) {
  64146. this._currentRefreshId = 1;
  64147. return true;
  64148. }
  64149. this._currentRefreshId++;
  64150. return false;
  64151. };
  64152. ProceduralTexture.prototype.getRenderSize = function () {
  64153. return this._size;
  64154. };
  64155. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64156. if (this._fallbackTextureUsed) {
  64157. return;
  64158. }
  64159. this.releaseInternalTexture();
  64160. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64161. };
  64162. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64163. if (this._uniforms.indexOf(uniformName) === -1) {
  64164. this._uniforms.push(uniformName);
  64165. }
  64166. };
  64167. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64168. if (this._samplers.indexOf(name) === -1) {
  64169. this._samplers.push(name);
  64170. }
  64171. this._textures[name] = texture;
  64172. return this;
  64173. };
  64174. ProceduralTexture.prototype.setFloat = function (name, value) {
  64175. this._checkUniform(name);
  64176. this._floats[name] = value;
  64177. return this;
  64178. };
  64179. ProceduralTexture.prototype.setFloats = function (name, value) {
  64180. this._checkUniform(name);
  64181. this._floatsArrays[name] = value;
  64182. return this;
  64183. };
  64184. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64185. this._checkUniform(name);
  64186. this._colors3[name] = value;
  64187. return this;
  64188. };
  64189. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64190. this._checkUniform(name);
  64191. this._colors4[name] = value;
  64192. return this;
  64193. };
  64194. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64195. this._checkUniform(name);
  64196. this._vectors2[name] = value;
  64197. return this;
  64198. };
  64199. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64200. this._checkUniform(name);
  64201. this._vectors3[name] = value;
  64202. return this;
  64203. };
  64204. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64205. this._checkUniform(name);
  64206. this._matrices[name] = value;
  64207. return this;
  64208. };
  64209. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64210. var scene = this.getScene();
  64211. if (!scene) {
  64212. return;
  64213. }
  64214. var engine = this._engine;
  64215. // Render
  64216. engine.enableEffect(this._effect);
  64217. engine.setState(false);
  64218. // Texture
  64219. for (var name in this._textures) {
  64220. this._effect.setTexture(name, this._textures[name]);
  64221. }
  64222. // Float
  64223. for (name in this._floats) {
  64224. this._effect.setFloat(name, this._floats[name]);
  64225. }
  64226. // Floats
  64227. for (name in this._floatsArrays) {
  64228. this._effect.setArray(name, this._floatsArrays[name]);
  64229. }
  64230. // Color3
  64231. for (name in this._colors3) {
  64232. this._effect.setColor3(name, this._colors3[name]);
  64233. }
  64234. // Color4
  64235. for (name in this._colors4) {
  64236. var color = this._colors4[name];
  64237. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64238. }
  64239. // Vector2
  64240. for (name in this._vectors2) {
  64241. this._effect.setVector2(name, this._vectors2[name]);
  64242. }
  64243. // Vector3
  64244. for (name in this._vectors3) {
  64245. this._effect.setVector3(name, this._vectors3[name]);
  64246. }
  64247. // Matrix
  64248. for (name in this._matrices) {
  64249. this._effect.setMatrix(name, this._matrices[name]);
  64250. }
  64251. if (!this._texture) {
  64252. return;
  64253. }
  64254. if (this.isCube) {
  64255. for (var face = 0; face < 6; face++) {
  64256. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64257. // VBOs
  64258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64259. this._effect.setFloat("face", face);
  64260. // Clear
  64261. engine.clear(scene.clearColor, true, true, true);
  64262. // Draw order
  64263. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64264. // Mipmaps
  64265. if (face === 5) {
  64266. engine.generateMipMapsForCubemap(this._texture);
  64267. }
  64268. }
  64269. }
  64270. else {
  64271. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64272. // VBOs
  64273. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64274. // Clear
  64275. engine.clear(scene.clearColor, true, true, true);
  64276. // Draw order
  64277. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64278. }
  64279. // Unbind
  64280. engine.unBindFramebuffer(this._texture, this.isCube);
  64281. if (this.onGenerated) {
  64282. this.onGenerated();
  64283. }
  64284. };
  64285. ProceduralTexture.prototype.clone = function () {
  64286. var textureSize = this.getSize();
  64287. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64288. // Base texture
  64289. newTexture.hasAlpha = this.hasAlpha;
  64290. newTexture.level = this.level;
  64291. // RenderTarget Texture
  64292. newTexture.coordinatesMode = this.coordinatesMode;
  64293. return newTexture;
  64294. };
  64295. ProceduralTexture.prototype.dispose = function () {
  64296. var scene = this.getScene();
  64297. if (!scene) {
  64298. return;
  64299. }
  64300. var index = scene._proceduralTextures.indexOf(this);
  64301. if (index >= 0) {
  64302. scene._proceduralTextures.splice(index, 1);
  64303. }
  64304. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64305. if (vertexBuffer) {
  64306. vertexBuffer.dispose();
  64307. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64308. }
  64309. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64310. this._indexBuffer = null;
  64311. }
  64312. _super.prototype.dispose.call(this);
  64313. };
  64314. return ProceduralTexture;
  64315. }(BABYLON.Texture));
  64316. BABYLON.ProceduralTexture = ProceduralTexture;
  64317. })(BABYLON || (BABYLON = {}));
  64318. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64319. var BABYLON;
  64320. (function (BABYLON) {
  64321. var CustomProceduralTexture = /** @class */ (function (_super) {
  64322. __extends(CustomProceduralTexture, _super);
  64323. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64324. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64325. _this._animate = true;
  64326. _this._time = 0;
  64327. _this._texturePath = texturePath;
  64328. //Try to load json
  64329. _this.loadJson(texturePath);
  64330. _this.refreshRate = 1;
  64331. return _this;
  64332. }
  64333. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64334. var _this = this;
  64335. var noConfigFile = function () {
  64336. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64337. try {
  64338. _this.setFragment(_this._texturePath);
  64339. }
  64340. catch (ex) {
  64341. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64342. }
  64343. };
  64344. var configFileUrl = jsonUrl + "/config.json";
  64345. var xhr = new XMLHttpRequest();
  64346. xhr.open("GET", configFileUrl, true);
  64347. xhr.addEventListener("load", function () {
  64348. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64349. try {
  64350. _this._config = JSON.parse(xhr.response);
  64351. _this.updateShaderUniforms();
  64352. _this.updateTextures();
  64353. _this.setFragment(_this._texturePath + "/custom");
  64354. _this._animate = _this._config.animate;
  64355. _this.refreshRate = _this._config.refreshrate;
  64356. }
  64357. catch (ex) {
  64358. noConfigFile();
  64359. }
  64360. }
  64361. else {
  64362. noConfigFile();
  64363. }
  64364. }, false);
  64365. xhr.addEventListener("error", function () {
  64366. noConfigFile();
  64367. }, false);
  64368. try {
  64369. xhr.send();
  64370. }
  64371. catch (ex) {
  64372. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64373. }
  64374. };
  64375. CustomProceduralTexture.prototype.isReady = function () {
  64376. if (!_super.prototype.isReady.call(this)) {
  64377. return false;
  64378. }
  64379. for (var name in this._textures) {
  64380. var texture = this._textures[name];
  64381. if (!texture.isReady()) {
  64382. return false;
  64383. }
  64384. }
  64385. return true;
  64386. };
  64387. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64388. var scene = this.getScene();
  64389. if (this._animate && scene) {
  64390. this._time += scene.getAnimationRatio() * 0.03;
  64391. this.updateShaderUniforms();
  64392. }
  64393. _super.prototype.render.call(this, useCameraPostProcess);
  64394. };
  64395. CustomProceduralTexture.prototype.updateTextures = function () {
  64396. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64397. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64398. }
  64399. };
  64400. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64401. if (this._config) {
  64402. for (var j = 0; j < this._config.uniforms.length; j++) {
  64403. var uniform = this._config.uniforms[j];
  64404. switch (uniform.type) {
  64405. case "float":
  64406. this.setFloat(uniform.name, uniform.value);
  64407. break;
  64408. case "color3":
  64409. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64410. break;
  64411. case "color4":
  64412. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64413. break;
  64414. case "vector2":
  64415. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64416. break;
  64417. case "vector3":
  64418. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64419. break;
  64420. }
  64421. }
  64422. }
  64423. this.setFloat("time", this._time);
  64424. };
  64425. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64426. get: function () {
  64427. return this._animate;
  64428. },
  64429. set: function (value) {
  64430. this._animate = value;
  64431. },
  64432. enumerable: true,
  64433. configurable: true
  64434. });
  64435. return CustomProceduralTexture;
  64436. }(BABYLON.ProceduralTexture));
  64437. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64438. })(BABYLON || (BABYLON = {}));
  64439. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64440. var BABYLON;
  64441. (function (BABYLON) {
  64442. var FreeCameraGamepadInput = /** @class */ (function () {
  64443. function FreeCameraGamepadInput() {
  64444. this.gamepadAngularSensibility = 200;
  64445. this.gamepadMoveSensibility = 40;
  64446. // private members
  64447. this._cameraTransform = BABYLON.Matrix.Identity();
  64448. this._deltaTransform = BABYLON.Vector3.Zero();
  64449. this._vector3 = BABYLON.Vector3.Zero();
  64450. this._vector2 = BABYLON.Vector2.Zero();
  64451. }
  64452. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64453. var _this = this;
  64454. var manager = this.camera.getScene().gamepadManager;
  64455. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64456. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64457. // prioritize XBOX gamepads.
  64458. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64459. _this.gamepad = gamepad;
  64460. }
  64461. }
  64462. });
  64463. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64464. if (_this.gamepad === gamepad) {
  64465. _this.gamepad = null;
  64466. }
  64467. });
  64468. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64469. };
  64470. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64471. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64472. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64473. this.gamepad = null;
  64474. };
  64475. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64476. if (this.gamepad && this.gamepad.leftStick) {
  64477. var camera = this.camera;
  64478. var LSValues = this.gamepad.leftStick;
  64479. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64480. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64481. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64482. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64483. var RSValues = this.gamepad.rightStick;
  64484. if (RSValues) {
  64485. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64486. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64487. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64488. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64489. }
  64490. else {
  64491. RSValues = { x: 0, y: 0 };
  64492. }
  64493. if (!camera.rotationQuaternion) {
  64494. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64495. }
  64496. else {
  64497. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64498. }
  64499. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64500. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64501. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64502. camera.cameraDirection.addInPlace(this._deltaTransform);
  64503. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64504. camera.cameraRotation.addInPlace(this._vector2);
  64505. }
  64506. };
  64507. FreeCameraGamepadInput.prototype.getClassName = function () {
  64508. return "FreeCameraGamepadInput";
  64509. };
  64510. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64511. return "gamepad";
  64512. };
  64513. __decorate([
  64514. BABYLON.serialize()
  64515. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64516. __decorate([
  64517. BABYLON.serialize()
  64518. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64519. return FreeCameraGamepadInput;
  64520. }());
  64521. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64522. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64523. })(BABYLON || (BABYLON = {}));
  64524. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64525. var BABYLON;
  64526. (function (BABYLON) {
  64527. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64528. function ArcRotateCameraGamepadInput() {
  64529. this.gamepadRotationSensibility = 80;
  64530. this.gamepadMoveSensibility = 40;
  64531. }
  64532. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64533. var _this = this;
  64534. var manager = this.camera.getScene().gamepadManager;
  64535. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64536. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64537. // prioritize XBOX gamepads.
  64538. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64539. _this.gamepad = gamepad;
  64540. }
  64541. }
  64542. });
  64543. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64544. if (_this.gamepad === gamepad) {
  64545. _this.gamepad = null;
  64546. }
  64547. });
  64548. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64549. };
  64550. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64551. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64552. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64553. this.gamepad = null;
  64554. };
  64555. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64556. if (this.gamepad) {
  64557. var camera = this.camera;
  64558. var RSValues = this.gamepad.rightStick;
  64559. if (RSValues) {
  64560. if (RSValues.x != 0) {
  64561. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64562. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64563. camera.inertialAlphaOffset += normalizedRX;
  64564. }
  64565. }
  64566. if (RSValues.y != 0) {
  64567. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64568. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64569. camera.inertialBetaOffset += normalizedRY;
  64570. }
  64571. }
  64572. }
  64573. var LSValues = this.gamepad.leftStick;
  64574. if (LSValues && LSValues.y != 0) {
  64575. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64576. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64577. this.camera.inertialRadiusOffset -= normalizedLY;
  64578. }
  64579. }
  64580. }
  64581. };
  64582. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64583. return "ArcRotateCameraGamepadInput";
  64584. };
  64585. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64586. return "gamepad";
  64587. };
  64588. __decorate([
  64589. BABYLON.serialize()
  64590. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64591. __decorate([
  64592. BABYLON.serialize()
  64593. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64594. return ArcRotateCameraGamepadInput;
  64595. }());
  64596. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64597. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64598. })(BABYLON || (BABYLON = {}));
  64599. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64600. var BABYLON;
  64601. (function (BABYLON) {
  64602. var GamepadManager = /** @class */ (function () {
  64603. function GamepadManager(_scene) {
  64604. var _this = this;
  64605. this._scene = _scene;
  64606. this._babylonGamepads = [];
  64607. this._oneGamepadConnected = false;
  64608. this._isMonitoring = false;
  64609. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64610. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64611. this._gamepadEventSupported = false;
  64612. }
  64613. else {
  64614. this._gamepadEventSupported = 'GamepadEvent' in window;
  64615. this._gamepadSupport = (navigator.getGamepads ||
  64616. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64617. }
  64618. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64619. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64620. for (var i in _this._babylonGamepads) {
  64621. var gamepad = _this._babylonGamepads[i];
  64622. if (gamepad && gamepad._isConnected) {
  64623. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64624. }
  64625. }
  64626. });
  64627. this._onGamepadConnectedEvent = function (evt) {
  64628. var gamepad = evt.gamepad;
  64629. if (gamepad.index in _this._babylonGamepads) {
  64630. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64631. return;
  64632. }
  64633. }
  64634. var newGamepad;
  64635. if (_this._babylonGamepads[gamepad.index]) {
  64636. newGamepad = _this._babylonGamepads[gamepad.index];
  64637. newGamepad.browserGamepad = gamepad;
  64638. newGamepad._isConnected = true;
  64639. }
  64640. else {
  64641. newGamepad = _this._addNewGamepad(gamepad);
  64642. }
  64643. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64644. _this._startMonitoringGamepads();
  64645. };
  64646. this._onGamepadDisconnectedEvent = function (evt) {
  64647. var gamepad = evt.gamepad;
  64648. // Remove the gamepad from the list of gamepads to monitor.
  64649. for (var i in _this._babylonGamepads) {
  64650. if (_this._babylonGamepads[i].index === gamepad.index) {
  64651. var disconnectedGamepad = _this._babylonGamepads[i];
  64652. disconnectedGamepad._isConnected = false;
  64653. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64654. break;
  64655. }
  64656. }
  64657. };
  64658. if (this._gamepadSupport) {
  64659. //first add already-connected gamepads
  64660. this._updateGamepadObjects();
  64661. if (this._babylonGamepads.length) {
  64662. this._startMonitoringGamepads();
  64663. }
  64664. // Checking if the gamepad connected event is supported (like in Firefox)
  64665. if (this._gamepadEventSupported) {
  64666. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64667. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64668. }
  64669. else {
  64670. this._startMonitoringGamepads();
  64671. }
  64672. }
  64673. }
  64674. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64675. get: function () {
  64676. return this._babylonGamepads;
  64677. },
  64678. enumerable: true,
  64679. configurable: true
  64680. });
  64681. GamepadManager.prototype.getGamepadByType = function (type) {
  64682. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64683. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64684. var gamepad = _a[_i];
  64685. if (gamepad && gamepad.type === type) {
  64686. return gamepad;
  64687. }
  64688. }
  64689. return null;
  64690. };
  64691. GamepadManager.prototype.dispose = function () {
  64692. if (this._gamepadEventSupported) {
  64693. if (this._onGamepadConnectedEvent) {
  64694. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64695. }
  64696. if (this._onGamepadDisconnectedEvent) {
  64697. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64698. }
  64699. this._onGamepadConnectedEvent = null;
  64700. this._onGamepadDisconnectedEvent = null;
  64701. }
  64702. this._babylonGamepads.forEach(function (gamepad) {
  64703. gamepad.dispose();
  64704. });
  64705. this.onGamepadConnectedObservable.clear();
  64706. this.onGamepadDisconnectedObservable.clear();
  64707. this._oneGamepadConnected = false;
  64708. this._stopMonitoringGamepads();
  64709. this._babylonGamepads = [];
  64710. };
  64711. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64712. if (!this._oneGamepadConnected) {
  64713. this._oneGamepadConnected = true;
  64714. }
  64715. var newGamepad;
  64716. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64717. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64718. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64719. }
  64720. else if (gamepad.pose) {
  64721. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64722. }
  64723. else {
  64724. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64725. }
  64726. this._babylonGamepads[newGamepad.index] = newGamepad;
  64727. return newGamepad;
  64728. };
  64729. GamepadManager.prototype._startMonitoringGamepads = function () {
  64730. if (!this._isMonitoring) {
  64731. this._isMonitoring = true;
  64732. //back-comp
  64733. if (!this._scene) {
  64734. this._checkGamepadsStatus();
  64735. }
  64736. }
  64737. };
  64738. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64739. this._isMonitoring = false;
  64740. };
  64741. GamepadManager.prototype._checkGamepadsStatus = function () {
  64742. var _this = this;
  64743. // Hack to be compatible Chrome
  64744. this._updateGamepadObjects();
  64745. for (var i in this._babylonGamepads) {
  64746. var gamepad = this._babylonGamepads[i];
  64747. if (!gamepad || !gamepad.isConnected) {
  64748. continue;
  64749. }
  64750. gamepad.update();
  64751. }
  64752. if (this._isMonitoring && !this._scene) {
  64753. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64754. }
  64755. };
  64756. // This function is called only on Chrome, which does not properly support
  64757. // connection/disconnection events and forces you to recopy again the gamepad object
  64758. GamepadManager.prototype._updateGamepadObjects = function () {
  64759. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64760. for (var i = 0; i < gamepads.length; i++) {
  64761. if (gamepads[i]) {
  64762. if (!this._babylonGamepads[gamepads[i].index]) {
  64763. var newGamepad = this._addNewGamepad(gamepads[i]);
  64764. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64765. }
  64766. else {
  64767. // Forced to copy again this object for Chrome for unknown reason
  64768. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64769. if (!this._babylonGamepads[i].isConnected) {
  64770. this._babylonGamepads[i]._isConnected = true;
  64771. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64772. }
  64773. }
  64774. }
  64775. }
  64776. };
  64777. return GamepadManager;
  64778. }());
  64779. BABYLON.GamepadManager = GamepadManager;
  64780. })(BABYLON || (BABYLON = {}));
  64781. //# sourceMappingURL=babylon.gamepadManager.js.map
  64782. var BABYLON;
  64783. (function (BABYLON) {
  64784. var StickValues = /** @class */ (function () {
  64785. function StickValues(x, y) {
  64786. this.x = x;
  64787. this.y = y;
  64788. }
  64789. return StickValues;
  64790. }());
  64791. BABYLON.StickValues = StickValues;
  64792. var Gamepad = /** @class */ (function () {
  64793. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64794. if (leftStickX === void 0) { leftStickX = 0; }
  64795. if (leftStickY === void 0) { leftStickY = 1; }
  64796. if (rightStickX === void 0) { rightStickX = 2; }
  64797. if (rightStickY === void 0) { rightStickY = 3; }
  64798. this.id = id;
  64799. this.index = index;
  64800. this.browserGamepad = browserGamepad;
  64801. this._isConnected = true;
  64802. this._invertLeftStickY = false;
  64803. this.type = Gamepad.GAMEPAD;
  64804. this._leftStickAxisX = leftStickX;
  64805. this._leftStickAxisY = leftStickY;
  64806. this._rightStickAxisX = rightStickX;
  64807. this._rightStickAxisY = rightStickY;
  64808. if (this.browserGamepad.axes.length >= 2) {
  64809. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64810. }
  64811. if (this.browserGamepad.axes.length >= 4) {
  64812. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64813. }
  64814. }
  64815. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64816. get: function () {
  64817. return this._isConnected;
  64818. },
  64819. enumerable: true,
  64820. configurable: true
  64821. });
  64822. Gamepad.prototype.onleftstickchanged = function (callback) {
  64823. this._onleftstickchanged = callback;
  64824. };
  64825. Gamepad.prototype.onrightstickchanged = function (callback) {
  64826. this._onrightstickchanged = callback;
  64827. };
  64828. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64829. get: function () {
  64830. return this._leftStick;
  64831. },
  64832. set: function (newValues) {
  64833. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64834. this._onleftstickchanged(newValues);
  64835. }
  64836. this._leftStick = newValues;
  64837. },
  64838. enumerable: true,
  64839. configurable: true
  64840. });
  64841. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64842. get: function () {
  64843. return this._rightStick;
  64844. },
  64845. set: function (newValues) {
  64846. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64847. this._onrightstickchanged(newValues);
  64848. }
  64849. this._rightStick = newValues;
  64850. },
  64851. enumerable: true,
  64852. configurable: true
  64853. });
  64854. Gamepad.prototype.update = function () {
  64855. if (this._leftStick) {
  64856. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64857. if (this._invertLeftStickY) {
  64858. this.leftStick.y *= -1;
  64859. }
  64860. }
  64861. if (this._rightStick) {
  64862. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64863. }
  64864. };
  64865. Gamepad.prototype.dispose = function () {
  64866. };
  64867. Gamepad.GAMEPAD = 0;
  64868. Gamepad.GENERIC = 1;
  64869. Gamepad.XBOX = 2;
  64870. Gamepad.POSE_ENABLED = 3;
  64871. return Gamepad;
  64872. }());
  64873. BABYLON.Gamepad = Gamepad;
  64874. var GenericPad = /** @class */ (function (_super) {
  64875. __extends(GenericPad, _super);
  64876. function GenericPad(id, index, browserGamepad) {
  64877. var _this = _super.call(this, id, index, browserGamepad) || this;
  64878. _this.onButtonDownObservable = new BABYLON.Observable();
  64879. _this.onButtonUpObservable = new BABYLON.Observable();
  64880. _this.type = Gamepad.GENERIC;
  64881. _this._buttons = new Array(browserGamepad.buttons.length);
  64882. return _this;
  64883. }
  64884. GenericPad.prototype.onbuttondown = function (callback) {
  64885. this._onbuttondown = callback;
  64886. };
  64887. GenericPad.prototype.onbuttonup = function (callback) {
  64888. this._onbuttonup = callback;
  64889. };
  64890. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64891. if (newValue !== currentValue) {
  64892. if (newValue === 1) {
  64893. if (this._onbuttondown) {
  64894. this._onbuttondown(buttonIndex);
  64895. }
  64896. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64897. }
  64898. if (newValue === 0) {
  64899. if (this._onbuttonup) {
  64900. this._onbuttonup(buttonIndex);
  64901. }
  64902. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64903. }
  64904. }
  64905. return newValue;
  64906. };
  64907. GenericPad.prototype.update = function () {
  64908. _super.prototype.update.call(this);
  64909. for (var index = 0; index < this._buttons.length; index++) {
  64910. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64911. }
  64912. };
  64913. GenericPad.prototype.dispose = function () {
  64914. _super.prototype.dispose.call(this);
  64915. this.onButtonDownObservable.clear();
  64916. this.onButtonUpObservable.clear();
  64917. };
  64918. return GenericPad;
  64919. }(Gamepad));
  64920. BABYLON.GenericPad = GenericPad;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.gamepad.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. var Xbox360Button;
  64926. (function (Xbox360Button) {
  64927. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64928. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64929. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64930. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64931. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64932. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64933. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64934. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64935. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64936. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64937. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64938. var Xbox360Dpad;
  64939. (function (Xbox360Dpad) {
  64940. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64941. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64942. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64943. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64944. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64945. var Xbox360Pad = /** @class */ (function (_super) {
  64946. __extends(Xbox360Pad, _super);
  64947. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64948. if (xboxOne === void 0) { xboxOne = false; }
  64949. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64950. _this._leftTrigger = 0;
  64951. _this._rightTrigger = 0;
  64952. _this.onButtonDownObservable = new BABYLON.Observable();
  64953. _this.onButtonUpObservable = new BABYLON.Observable();
  64954. _this.onPadDownObservable = new BABYLON.Observable();
  64955. _this.onPadUpObservable = new BABYLON.Observable();
  64956. _this._buttonA = 0;
  64957. _this._buttonB = 0;
  64958. _this._buttonX = 0;
  64959. _this._buttonY = 0;
  64960. _this._buttonBack = 0;
  64961. _this._buttonStart = 0;
  64962. _this._buttonLB = 0;
  64963. _this._buttonRB = 0;
  64964. _this._buttonLeftStick = 0;
  64965. _this._buttonRightStick = 0;
  64966. _this._dPadUp = 0;
  64967. _this._dPadDown = 0;
  64968. _this._dPadLeft = 0;
  64969. _this._dPadRight = 0;
  64970. _this._isXboxOnePad = false;
  64971. _this.type = BABYLON.Gamepad.XBOX;
  64972. _this._isXboxOnePad = xboxOne;
  64973. return _this;
  64974. }
  64975. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64976. this._onlefttriggerchanged = callback;
  64977. };
  64978. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64979. this._onrighttriggerchanged = callback;
  64980. };
  64981. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64982. get: function () {
  64983. return this._leftTrigger;
  64984. },
  64985. set: function (newValue) {
  64986. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64987. this._onlefttriggerchanged(newValue);
  64988. }
  64989. this._leftTrigger = newValue;
  64990. },
  64991. enumerable: true,
  64992. configurable: true
  64993. });
  64994. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64995. get: function () {
  64996. return this._rightTrigger;
  64997. },
  64998. set: function (newValue) {
  64999. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65000. this._onrighttriggerchanged(newValue);
  65001. }
  65002. this._rightTrigger = newValue;
  65003. },
  65004. enumerable: true,
  65005. configurable: true
  65006. });
  65007. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65008. this._onbuttondown = callback;
  65009. };
  65010. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65011. this._onbuttonup = callback;
  65012. };
  65013. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65014. this._ondpaddown = callback;
  65015. };
  65016. Xbox360Pad.prototype.ondpadup = function (callback) {
  65017. this._ondpadup = callback;
  65018. };
  65019. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65020. if (newValue !== currentValue) {
  65021. if (newValue === 1) {
  65022. if (this._onbuttondown) {
  65023. this._onbuttondown(buttonType);
  65024. }
  65025. this.onButtonDownObservable.notifyObservers(buttonType);
  65026. }
  65027. if (newValue === 0) {
  65028. if (this._onbuttonup) {
  65029. this._onbuttonup(buttonType);
  65030. }
  65031. this.onButtonUpObservable.notifyObservers(buttonType);
  65032. }
  65033. }
  65034. return newValue;
  65035. };
  65036. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65037. if (newValue !== currentValue) {
  65038. if (newValue === 1) {
  65039. if (this._ondpaddown) {
  65040. this._ondpaddown(buttonType);
  65041. }
  65042. this.onPadDownObservable.notifyObservers(buttonType);
  65043. }
  65044. if (newValue === 0) {
  65045. if (this._ondpadup) {
  65046. this._ondpadup(buttonType);
  65047. }
  65048. this.onPadUpObservable.notifyObservers(buttonType);
  65049. }
  65050. }
  65051. return newValue;
  65052. };
  65053. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65054. get: function () {
  65055. return this._buttonA;
  65056. },
  65057. set: function (value) {
  65058. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65064. get: function () {
  65065. return this._buttonB;
  65066. },
  65067. set: function (value) {
  65068. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65074. get: function () {
  65075. return this._buttonX;
  65076. },
  65077. set: function (value) {
  65078. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65084. get: function () {
  65085. return this._buttonY;
  65086. },
  65087. set: function (value) {
  65088. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65094. get: function () {
  65095. return this._buttonStart;
  65096. },
  65097. set: function (value) {
  65098. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65104. get: function () {
  65105. return this._buttonBack;
  65106. },
  65107. set: function (value) {
  65108. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65109. },
  65110. enumerable: true,
  65111. configurable: true
  65112. });
  65113. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65114. get: function () {
  65115. return this._buttonLB;
  65116. },
  65117. set: function (value) {
  65118. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65124. get: function () {
  65125. return this._buttonRB;
  65126. },
  65127. set: function (value) {
  65128. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65129. },
  65130. enumerable: true,
  65131. configurable: true
  65132. });
  65133. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65134. get: function () {
  65135. return this._buttonLeftStick;
  65136. },
  65137. set: function (value) {
  65138. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65139. },
  65140. enumerable: true,
  65141. configurable: true
  65142. });
  65143. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65144. get: function () {
  65145. return this._buttonRightStick;
  65146. },
  65147. set: function (value) {
  65148. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65149. },
  65150. enumerable: true,
  65151. configurable: true
  65152. });
  65153. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65154. get: function () {
  65155. return this._dPadUp;
  65156. },
  65157. set: function (value) {
  65158. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65159. },
  65160. enumerable: true,
  65161. configurable: true
  65162. });
  65163. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65164. get: function () {
  65165. return this._dPadDown;
  65166. },
  65167. set: function (value) {
  65168. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65174. get: function () {
  65175. return this._dPadLeft;
  65176. },
  65177. set: function (value) {
  65178. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65179. },
  65180. enumerable: true,
  65181. configurable: true
  65182. });
  65183. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65184. get: function () {
  65185. return this._dPadRight;
  65186. },
  65187. set: function (value) {
  65188. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65189. },
  65190. enumerable: true,
  65191. configurable: true
  65192. });
  65193. Xbox360Pad.prototype.update = function () {
  65194. _super.prototype.update.call(this);
  65195. if (this._isXboxOnePad) {
  65196. this.buttonA = this.browserGamepad.buttons[0].value;
  65197. this.buttonB = this.browserGamepad.buttons[1].value;
  65198. this.buttonX = this.browserGamepad.buttons[2].value;
  65199. this.buttonY = this.browserGamepad.buttons[3].value;
  65200. this.buttonLB = this.browserGamepad.buttons[4].value;
  65201. this.buttonRB = this.browserGamepad.buttons[5].value;
  65202. this.leftTrigger = this.browserGamepad.axes[2];
  65203. this.rightTrigger = this.browserGamepad.axes[5];
  65204. this.buttonBack = this.browserGamepad.buttons[9].value;
  65205. this.buttonStart = this.browserGamepad.buttons[8].value;
  65206. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65207. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65208. this.dPadUp = this.browserGamepad.buttons[11].value;
  65209. this.dPadDown = this.browserGamepad.buttons[12].value;
  65210. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65211. this.dPadRight = this.browserGamepad.buttons[14].value;
  65212. }
  65213. else {
  65214. this.buttonA = this.browserGamepad.buttons[0].value;
  65215. this.buttonB = this.browserGamepad.buttons[1].value;
  65216. this.buttonX = this.browserGamepad.buttons[2].value;
  65217. this.buttonY = this.browserGamepad.buttons[3].value;
  65218. this.buttonLB = this.browserGamepad.buttons[4].value;
  65219. this.buttonRB = this.browserGamepad.buttons[5].value;
  65220. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65221. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65222. this.buttonBack = this.browserGamepad.buttons[8].value;
  65223. this.buttonStart = this.browserGamepad.buttons[9].value;
  65224. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65225. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65226. this.dPadUp = this.browserGamepad.buttons[12].value;
  65227. this.dPadDown = this.browserGamepad.buttons[13].value;
  65228. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65229. this.dPadRight = this.browserGamepad.buttons[15].value;
  65230. }
  65231. };
  65232. Xbox360Pad.prototype.dispose = function () {
  65233. _super.prototype.dispose.call(this);
  65234. this.onButtonDownObservable.clear();
  65235. this.onButtonUpObservable.clear();
  65236. this.onPadDownObservable.clear();
  65237. this.onPadUpObservable.clear();
  65238. };
  65239. return Xbox360Pad;
  65240. }(BABYLON.Gamepad));
  65241. BABYLON.Xbox360Pad = Xbox360Pad;
  65242. })(BABYLON || (BABYLON = {}));
  65243. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65244. var BABYLON;
  65245. (function (BABYLON) {
  65246. var PoseEnabledControllerType;
  65247. (function (PoseEnabledControllerType) {
  65248. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65249. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65250. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65251. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65252. /**
  65253. * Google Daydream
  65254. */
  65255. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65256. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65257. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65258. var PoseEnabledControllerHelper = /** @class */ (function () {
  65259. function PoseEnabledControllerHelper() {
  65260. }
  65261. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65262. // Oculus Touch
  65263. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65264. return new BABYLON.OculusTouchController(vrGamepad);
  65265. }
  65266. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65267. return new BABYLON.WindowsMotionController(vrGamepad);
  65268. }
  65269. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65270. return new BABYLON.ViveController(vrGamepad);
  65271. }
  65272. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65273. return new BABYLON.GearVRController(vrGamepad);
  65274. }
  65275. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65276. return new BABYLON.DaydreamController(vrGamepad);
  65277. }
  65278. else {
  65279. return new BABYLON.GenericController(vrGamepad);
  65280. }
  65281. };
  65282. return PoseEnabledControllerHelper;
  65283. }());
  65284. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65285. var PoseEnabledController = /** @class */ (function (_super) {
  65286. __extends(PoseEnabledController, _super);
  65287. function PoseEnabledController(browserGamepad) {
  65288. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65289. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65290. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65291. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65292. // Represents device position and rotation in babylon space
  65293. _this.devicePosition = BABYLON.Vector3.Zero();
  65294. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65295. _this.deviceScaleFactor = 1;
  65296. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65297. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65298. /**
  65299. * Node to be used when casting a ray from the controller
  65300. */
  65301. _this._pointingPoseNode = null;
  65302. _this._workingMatrix = BABYLON.Matrix.Identity();
  65303. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65304. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65305. _this.position = BABYLON.Vector3.Zero();
  65306. _this.rotationQuaternion = new BABYLON.Quaternion();
  65307. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65308. _this._calculatedRotation = new BABYLON.Quaternion();
  65309. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65310. return _this;
  65311. }
  65312. PoseEnabledController.prototype.update = function () {
  65313. _super.prototype.update.call(this);
  65314. var pose = this.browserGamepad.pose;
  65315. this.updateFromDevice(pose);
  65316. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65317. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65318. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65319. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65320. if (this._mesh) {
  65321. this._mesh.position.copyFrom(this.devicePosition);
  65322. if (this._mesh.rotationQuaternion) {
  65323. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65324. }
  65325. }
  65326. };
  65327. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65328. if (poseData) {
  65329. this.rawPose = poseData;
  65330. if (poseData.position) {
  65331. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65332. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65333. this._deviceRoomPosition.z *= -1;
  65334. }
  65335. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65336. this._calculatedPosition.addInPlace(this.position);
  65337. }
  65338. var pose = this.rawPose;
  65339. if (poseData.orientation && pose.orientation) {
  65340. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65341. if (this._mesh) {
  65342. if (this._mesh.getScene().useRightHandedSystem) {
  65343. this._deviceRoomRotationQuaternion.z *= -1;
  65344. this._deviceRoomRotationQuaternion.w *= -1;
  65345. }
  65346. else {
  65347. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65348. }
  65349. }
  65350. // if the camera is set, rotate to the camera's rotation
  65351. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65352. }
  65353. }
  65354. };
  65355. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65356. if (this._mesh) {
  65357. this._mesh.parent = null;
  65358. }
  65359. this._mesh = mesh;
  65360. if (this._poseControlledCamera) {
  65361. this._mesh.parent = this._poseControlledCamera;
  65362. }
  65363. if (!this._mesh.rotationQuaternion) {
  65364. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65365. }
  65366. };
  65367. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65368. this._poseControlledCamera = camera;
  65369. if (this._mesh) {
  65370. this._mesh.parent = this._poseControlledCamera;
  65371. }
  65372. };
  65373. PoseEnabledController.prototype.dispose = function () {
  65374. if (this._mesh) {
  65375. this._mesh.dispose();
  65376. }
  65377. this._mesh = null;
  65378. _super.prototype.dispose.call(this);
  65379. };
  65380. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65381. get: function () {
  65382. return this._mesh;
  65383. },
  65384. enumerable: true,
  65385. configurable: true
  65386. });
  65387. PoseEnabledController.prototype.getForwardRay = function (length) {
  65388. if (length === void 0) { length = 100; }
  65389. if (!this.mesh) {
  65390. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65391. }
  65392. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65393. var origin = m.getTranslation();
  65394. var forward = new BABYLON.Vector3(0, 0, -1);
  65395. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65396. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65397. return new BABYLON.Ray(origin, direction, length);
  65398. };
  65399. /**
  65400. * Name of the child mesh that can be used to cast a ray from the controller
  65401. */
  65402. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65403. return PoseEnabledController;
  65404. }(BABYLON.Gamepad));
  65405. BABYLON.PoseEnabledController = PoseEnabledController;
  65406. })(BABYLON || (BABYLON = {}));
  65407. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65408. var BABYLON;
  65409. (function (BABYLON) {
  65410. var WebVRController = /** @class */ (function (_super) {
  65411. __extends(WebVRController, _super);
  65412. function WebVRController(vrGamepad) {
  65413. var _this = _super.call(this, vrGamepad) || this;
  65414. // Observables
  65415. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65416. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65417. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65418. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65419. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65420. _this.pad = { x: 0, y: 0 };
  65421. // avoid GC, store state in a tmp object
  65422. _this._changes = {
  65423. pressChanged: false,
  65424. touchChanged: false,
  65425. valueChanged: false,
  65426. changed: false
  65427. };
  65428. _this._buttons = new Array(vrGamepad.buttons.length);
  65429. _this.hand = vrGamepad.hand;
  65430. return _this;
  65431. }
  65432. WebVRController.prototype.onButtonStateChange = function (callback) {
  65433. this._onButtonStateChange = callback;
  65434. };
  65435. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65436. get: function () {
  65437. return this._defaultModel;
  65438. },
  65439. enumerable: true,
  65440. configurable: true
  65441. });
  65442. WebVRController.prototype.update = function () {
  65443. _super.prototype.update.call(this);
  65444. for (var index = 0; index < this._buttons.length; index++) {
  65445. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65446. }
  65447. ;
  65448. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65449. this.pad.x = this.leftStick.x;
  65450. this.pad.y = this.leftStick.y;
  65451. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65452. }
  65453. };
  65454. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65455. if (!newState) {
  65456. newState = {
  65457. pressed: false,
  65458. touched: false,
  65459. value: 0
  65460. };
  65461. }
  65462. if (!currentState) {
  65463. this._buttons[buttonIndex] = {
  65464. pressed: newState.pressed,
  65465. touched: newState.touched,
  65466. value: newState.value
  65467. };
  65468. return;
  65469. }
  65470. this._checkChanges(newState, currentState);
  65471. if (this._changes.changed) {
  65472. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65473. this._handleButtonChange(buttonIndex, newState, this._changes);
  65474. }
  65475. this._buttons[buttonIndex].pressed = newState.pressed;
  65476. this._buttons[buttonIndex].touched = newState.touched;
  65477. // oculus triggers are never 0, thou not touched.
  65478. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65479. };
  65480. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65481. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65482. this._changes.touchChanged = newState.touched !== currentState.touched;
  65483. this._changes.valueChanged = newState.value !== currentState.value;
  65484. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65485. return this._changes;
  65486. };
  65487. WebVRController.prototype.dispose = function () {
  65488. _super.prototype.dispose.call(this);
  65489. this.onTriggerStateChangedObservable.clear();
  65490. this.onMainButtonStateChangedObservable.clear();
  65491. this.onSecondaryButtonStateChangedObservable.clear();
  65492. this.onPadStateChangedObservable.clear();
  65493. this.onPadValuesChangedObservable.clear();
  65494. };
  65495. return WebVRController;
  65496. }(BABYLON.PoseEnabledController));
  65497. BABYLON.WebVRController = WebVRController;
  65498. })(BABYLON || (BABYLON = {}));
  65499. //# sourceMappingURL=babylon.webVRController.js.map
  65500. var BABYLON;
  65501. (function (BABYLON) {
  65502. var OculusTouchController = /** @class */ (function (_super) {
  65503. __extends(OculusTouchController, _super);
  65504. function OculusTouchController(vrGamepad) {
  65505. var _this = _super.call(this, vrGamepad) || this;
  65506. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65507. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65508. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65509. return _this;
  65510. }
  65511. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65512. var _this = this;
  65513. var meshName;
  65514. // Hand
  65515. if (this.hand === 'left') {
  65516. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65517. }
  65518. else {
  65519. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65520. }
  65521. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65522. /*
  65523. Parent Mesh name: oculus_touch_left
  65524. - body
  65525. - trigger
  65526. - thumbstick
  65527. - grip
  65528. - button_y
  65529. - button_x
  65530. - button_enter
  65531. */
  65532. _this._defaultModel = newMeshes[1];
  65533. _this.attachToMesh(_this._defaultModel);
  65534. if (meshLoaded) {
  65535. meshLoaded(_this._defaultModel);
  65536. }
  65537. });
  65538. };
  65539. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65540. // helper getters for left and right hand.
  65541. get: function () {
  65542. if (this.hand === 'right') {
  65543. return this.onMainButtonStateChangedObservable;
  65544. }
  65545. else {
  65546. throw new Error('No A button on left hand');
  65547. }
  65548. },
  65549. enumerable: true,
  65550. configurable: true
  65551. });
  65552. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65553. get: function () {
  65554. if (this.hand === 'right') {
  65555. return this.onSecondaryButtonStateChangedObservable;
  65556. }
  65557. else {
  65558. throw new Error('No B button on left hand');
  65559. }
  65560. },
  65561. enumerable: true,
  65562. configurable: true
  65563. });
  65564. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65565. get: function () {
  65566. if (this.hand === 'left') {
  65567. return this.onMainButtonStateChangedObservable;
  65568. }
  65569. else {
  65570. throw new Error('No X button on right hand');
  65571. }
  65572. },
  65573. enumerable: true,
  65574. configurable: true
  65575. });
  65576. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65577. get: function () {
  65578. if (this.hand === 'left') {
  65579. return this.onSecondaryButtonStateChangedObservable;
  65580. }
  65581. else {
  65582. throw new Error('No Y button on right hand');
  65583. }
  65584. },
  65585. enumerable: true,
  65586. configurable: true
  65587. });
  65588. /*
  65589. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65590. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65591. 2) secondary trigger (same)
  65592. 3) A (right) X (left), touch, pressed = value
  65593. 4) B / Y
  65594. 5) thumb rest
  65595. */
  65596. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65597. var notifyObject = state; //{ state: state, changes: changes };
  65598. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65599. switch (buttonIdx) {
  65600. case 0:
  65601. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65602. return;
  65603. case 1:// index trigger
  65604. if (this._defaultModel) {
  65605. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65606. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65607. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65608. }
  65609. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65610. return;
  65611. case 2:// secondary trigger
  65612. if (this._defaultModel) {
  65613. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65614. }
  65615. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65616. return;
  65617. case 3:
  65618. if (this._defaultModel) {
  65619. if (notifyObject.pressed) {
  65620. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65621. }
  65622. else {
  65623. (this._defaultModel.getChildren()[1]).position.y = 0;
  65624. }
  65625. }
  65626. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65627. return;
  65628. case 4:
  65629. if (this._defaultModel) {
  65630. if (notifyObject.pressed) {
  65631. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65632. }
  65633. else {
  65634. (this._defaultModel.getChildren()[2]).position.y = 0;
  65635. }
  65636. }
  65637. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65638. return;
  65639. case 5:
  65640. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65641. return;
  65642. }
  65643. };
  65644. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65645. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65646. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65647. return OculusTouchController;
  65648. }(BABYLON.WebVRController));
  65649. BABYLON.OculusTouchController = OculusTouchController;
  65650. })(BABYLON || (BABYLON = {}));
  65651. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65652. var BABYLON;
  65653. (function (BABYLON) {
  65654. var ViveController = /** @class */ (function (_super) {
  65655. __extends(ViveController, _super);
  65656. function ViveController(vrGamepad) {
  65657. var _this = _super.call(this, vrGamepad) || this;
  65658. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65659. _this._invertLeftStickY = true;
  65660. return _this;
  65661. }
  65662. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65663. var _this = this;
  65664. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65665. /*
  65666. Parent Mesh name: ViveWand
  65667. - body
  65668. - r_gripper
  65669. - l_gripper
  65670. - menu_button
  65671. - system_button
  65672. - trackpad
  65673. - trigger
  65674. - LED
  65675. */
  65676. _this._defaultModel = newMeshes[1];
  65677. _this.attachToMesh(_this._defaultModel);
  65678. if (meshLoaded) {
  65679. meshLoaded(_this._defaultModel);
  65680. }
  65681. });
  65682. };
  65683. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65684. get: function () {
  65685. return this.onMainButtonStateChangedObservable;
  65686. },
  65687. enumerable: true,
  65688. configurable: true
  65689. });
  65690. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65691. get: function () {
  65692. return this.onMainButtonStateChangedObservable;
  65693. },
  65694. enumerable: true,
  65695. configurable: true
  65696. });
  65697. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65698. get: function () {
  65699. return this.onSecondaryButtonStateChangedObservable;
  65700. },
  65701. enumerable: true,
  65702. configurable: true
  65703. });
  65704. /**
  65705. * Vive mapping:
  65706. * 0: touchpad
  65707. * 1: trigger
  65708. * 2: left AND right buttons
  65709. * 3: menu button
  65710. */
  65711. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65712. var notifyObject = state; //{ state: state, changes: changes };
  65713. switch (buttonIdx) {
  65714. case 0:
  65715. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65716. return;
  65717. case 1:// index trigger
  65718. if (this._defaultModel) {
  65719. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65720. }
  65721. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65722. return;
  65723. case 2:// left AND right button
  65724. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65725. return;
  65726. case 3:
  65727. if (this._defaultModel) {
  65728. if (notifyObject.pressed) {
  65729. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65730. }
  65731. else {
  65732. (this._defaultModel.getChildren()[2]).position.y = 0;
  65733. }
  65734. }
  65735. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65736. return;
  65737. }
  65738. };
  65739. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65740. ViveController.MODEL_FILENAME = 'wand.babylon';
  65741. return ViveController;
  65742. }(BABYLON.WebVRController));
  65743. BABYLON.ViveController = ViveController;
  65744. })(BABYLON || (BABYLON = {}));
  65745. //# sourceMappingURL=babylon.viveController.js.map
  65746. var BABYLON;
  65747. (function (BABYLON) {
  65748. var GenericController = /** @class */ (function (_super) {
  65749. __extends(GenericController, _super);
  65750. function GenericController(vrGamepad) {
  65751. return _super.call(this, vrGamepad) || this;
  65752. }
  65753. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65754. var _this = this;
  65755. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65756. _this._defaultModel = newMeshes[1];
  65757. _this.attachToMesh(_this._defaultModel);
  65758. if (meshLoaded) {
  65759. meshLoaded(_this._defaultModel);
  65760. }
  65761. });
  65762. };
  65763. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65764. console.log("Button id: " + buttonIdx + "state: ");
  65765. console.dir(state);
  65766. };
  65767. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65768. GenericController.MODEL_FILENAME = 'generic.babylon';
  65769. return GenericController;
  65770. }(BABYLON.WebVRController));
  65771. BABYLON.GenericController = GenericController;
  65772. })(BABYLON || (BABYLON = {}));
  65773. //# sourceMappingURL=babylon.genericController.js.map
  65774. var BABYLON;
  65775. (function (BABYLON) {
  65776. var LoadedMeshInfo = /** @class */ (function () {
  65777. function LoadedMeshInfo() {
  65778. this.buttonMeshes = {};
  65779. this.axisMeshes = {};
  65780. }
  65781. return LoadedMeshInfo;
  65782. }());
  65783. var WindowsMotionController = /** @class */ (function (_super) {
  65784. __extends(WindowsMotionController, _super);
  65785. function WindowsMotionController(vrGamepad) {
  65786. var _this = _super.call(this, vrGamepad) || this;
  65787. _this._mapping = {
  65788. // Semantic button names
  65789. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65790. // A mapping of the button name to glTF model node name
  65791. // that should be transformed by button value.
  65792. buttonMeshNames: {
  65793. 'trigger': 'SELECT',
  65794. 'menu': 'MENU',
  65795. 'grip': 'GRASP',
  65796. 'thumbstick': 'THUMBSTICK_PRESS',
  65797. 'trackpad': 'TOUCHPAD_PRESS'
  65798. },
  65799. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65800. buttonObservableNames: {
  65801. 'trigger': 'onTriggerStateChangedObservable',
  65802. 'menu': 'onSecondaryButtonStateChangedObservable',
  65803. 'grip': 'onMainButtonStateChangedObservable',
  65804. 'thumbstick': 'onPadStateChangedObservable',
  65805. 'trackpad': 'onTrackpadChangedObservable'
  65806. },
  65807. // A mapping of the axis name to glTF model node name
  65808. // that should be transformed by axis value.
  65809. // This array mirrors the browserGamepad.axes array, such that
  65810. // the mesh corresponding to axis 0 is in this array index 0.
  65811. axisMeshNames: [
  65812. 'THUMBSTICK_X',
  65813. 'THUMBSTICK_Y',
  65814. 'TOUCHPAD_TOUCH_X',
  65815. 'TOUCHPAD_TOUCH_Y'
  65816. ],
  65817. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65818. };
  65819. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65820. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65821. _this.trackpad = { x: 0, y: 0 };
  65822. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65823. _this._loadedMeshInfo = null;
  65824. return _this;
  65825. }
  65826. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65827. get: function () {
  65828. return this.onTriggerStateChangedObservable;
  65829. },
  65830. enumerable: true,
  65831. configurable: true
  65832. });
  65833. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65834. get: function () {
  65835. return this.onSecondaryButtonStateChangedObservable;
  65836. },
  65837. enumerable: true,
  65838. configurable: true
  65839. });
  65840. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65841. get: function () {
  65842. return this.onMainButtonStateChangedObservable;
  65843. },
  65844. enumerable: true,
  65845. configurable: true
  65846. });
  65847. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65848. get: function () {
  65849. return this.onPadStateChangedObservable;
  65850. },
  65851. enumerable: true,
  65852. configurable: true
  65853. });
  65854. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65855. get: function () {
  65856. return this.onTrackpadChangedObservable;
  65857. },
  65858. enumerable: true,
  65859. configurable: true
  65860. });
  65861. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65862. get: function () {
  65863. return this.onTrackpadValuesChangedObservable;
  65864. },
  65865. enumerable: true,
  65866. configurable: true
  65867. });
  65868. /**
  65869. * Called once per frame by the engine.
  65870. */
  65871. WindowsMotionController.prototype.update = function () {
  65872. _super.prototype.update.call(this);
  65873. if (this.browserGamepad.axes) {
  65874. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65875. this.trackpad.x = this.browserGamepad["axes"][2];
  65876. this.trackpad.y = this.browserGamepad["axes"][3];
  65877. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65878. }
  65879. // Only need to animate axes if there is a loaded mesh
  65880. if (this._loadedMeshInfo) {
  65881. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65882. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65883. }
  65884. }
  65885. }
  65886. };
  65887. /**
  65888. * Called once for each button that changed state since the last frame
  65889. * @param buttonIdx Which button index changed
  65890. * @param state New state of the button
  65891. * @param changes Which properties on the state changed since last frame
  65892. */
  65893. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65894. var buttonName = this._mapping.buttons[buttonIdx];
  65895. if (!buttonName) {
  65896. return;
  65897. }
  65898. // Only emit events for buttons that we know how to map from index to name
  65899. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65900. if (observable) {
  65901. observable.notifyObservers(state);
  65902. }
  65903. this.lerpButtonTransform(buttonName, state.value);
  65904. };
  65905. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65906. // If there is no loaded mesh, there is nothing to transform.
  65907. if (!this._loadedMeshInfo) {
  65908. return;
  65909. }
  65910. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65911. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65912. return;
  65913. }
  65914. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65915. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65916. };
  65917. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65918. if (!this._loadedMeshInfo) {
  65919. return;
  65920. }
  65921. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65922. if (!meshInfo) {
  65923. return;
  65924. }
  65925. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65926. return;
  65927. }
  65928. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65929. var lerpValue = axisValue * 0.5 + 0.5;
  65930. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65931. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65932. };
  65933. /**
  65934. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65935. * @param scene scene in which to add meshes
  65936. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65937. */
  65938. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65939. var _this = this;
  65940. if (forceDefault === void 0) { forceDefault = false; }
  65941. var path;
  65942. var filename;
  65943. // Checking if GLB loader is present
  65944. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65945. // Determine the device specific folder based on the ID suffix
  65946. var device = 'default';
  65947. if (this.id && !forceDefault) {
  65948. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65949. device = ((match && match[0]) || device);
  65950. }
  65951. // Hand
  65952. if (this.hand === 'left') {
  65953. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65954. }
  65955. else {
  65956. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65957. }
  65958. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65959. }
  65960. else {
  65961. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65962. path = BABYLON.GenericController.MODEL_BASE_URL;
  65963. filename = BABYLON.GenericController.MODEL_FILENAME;
  65964. }
  65965. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65966. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65967. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65968. if (!_this._loadedMeshInfo) {
  65969. return;
  65970. }
  65971. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65972. _this.attachToMesh(_this._defaultModel);
  65973. if (meshLoaded) {
  65974. meshLoaded(_this._defaultModel);
  65975. }
  65976. }, null, function (scene, message) {
  65977. BABYLON.Tools.Log(message);
  65978. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65979. if (!forceDefault) {
  65980. _this.initControllerMesh(scene, meshLoaded, true);
  65981. }
  65982. });
  65983. };
  65984. /**
  65985. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65986. * can be transformed by button presses and axes values, based on this._mapping.
  65987. *
  65988. * @param scene scene in which the meshes exist
  65989. * @param meshes list of meshes that make up the controller model to process
  65990. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65991. */
  65992. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65993. var loadedMeshInfo = null;
  65994. // Create a new mesh to contain the glTF hierarchy
  65995. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65996. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65997. var childMesh = null;
  65998. for (var i = 0; i < meshes.length; i++) {
  65999. var mesh = meshes[i];
  66000. if (!mesh.parent) {
  66001. // Exclude controller meshes from picking results
  66002. mesh.isPickable = false;
  66003. // Handle root node, attach to the new parentMesh
  66004. childMesh = mesh;
  66005. break;
  66006. }
  66007. }
  66008. if (childMesh) {
  66009. childMesh.setParent(parentMesh);
  66010. // Create our mesh info. Note that this method will always return non-null.
  66011. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66012. }
  66013. else {
  66014. BABYLON.Tools.Warn('Could not find root node in model file.');
  66015. }
  66016. return loadedMeshInfo;
  66017. };
  66018. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66019. var loadedMeshInfo = new LoadedMeshInfo();
  66020. var i;
  66021. loadedMeshInfo.rootNode = rootNode;
  66022. // Reset the caches
  66023. loadedMeshInfo.buttonMeshes = {};
  66024. loadedMeshInfo.axisMeshes = {};
  66025. // Button Meshes
  66026. for (i = 0; i < this._mapping.buttons.length; i++) {
  66027. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66028. if (!buttonMeshName) {
  66029. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66030. continue;
  66031. }
  66032. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66033. if (!buttonMesh) {
  66034. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66035. continue;
  66036. }
  66037. var buttonMeshInfo = {
  66038. index: i,
  66039. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66040. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66041. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66042. };
  66043. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66044. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66045. }
  66046. else {
  66047. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66048. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66049. '(VALUE: ' + !!buttonMeshInfo.value +
  66050. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66051. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66052. ')');
  66053. }
  66054. }
  66055. // Axis Meshes
  66056. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66057. var axisMeshName = this._mapping.axisMeshNames[i];
  66058. if (!axisMeshName) {
  66059. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66060. continue;
  66061. }
  66062. var axisMesh = getChildByName(rootNode, axisMeshName);
  66063. if (!axisMesh) {
  66064. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66065. continue;
  66066. }
  66067. var axisMeshInfo = {
  66068. index: i,
  66069. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66070. min: getImmediateChildByName(axisMesh, 'MIN'),
  66071. max: getImmediateChildByName(axisMesh, 'MAX')
  66072. };
  66073. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66074. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66075. }
  66076. else {
  66077. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66078. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66079. '(VALUE: ' + !!axisMeshInfo.value +
  66080. ', MIN: ' + !!axisMeshInfo.min +
  66081. ', MAX:' + !!axisMeshInfo.max +
  66082. ')');
  66083. }
  66084. }
  66085. // Pointing Ray
  66086. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66087. if (!loadedMeshInfo.pointingPoseNode) {
  66088. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66089. }
  66090. return loadedMeshInfo;
  66091. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66092. function getChildByName(node, name) {
  66093. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66094. }
  66095. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66096. function getImmediateChildByName(node, name) {
  66097. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66098. }
  66099. };
  66100. WindowsMotionController.prototype.getForwardRay = function (length) {
  66101. if (length === void 0) { length = 100; }
  66102. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66103. return _super.prototype.getForwardRay.call(this, length);
  66104. }
  66105. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66106. var origin = m.getTranslation();
  66107. var forward = new BABYLON.Vector3(0, 0, -1);
  66108. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66109. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66110. return new BABYLON.Ray(origin, direction, length);
  66111. };
  66112. WindowsMotionController.prototype.dispose = function () {
  66113. _super.prototype.dispose.call(this);
  66114. this.onTrackpadChangedObservable.clear();
  66115. };
  66116. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66117. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66118. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66119. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66120. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66121. return WindowsMotionController;
  66122. }(BABYLON.WebVRController));
  66123. BABYLON.WindowsMotionController = WindowsMotionController;
  66124. })(BABYLON || (BABYLON = {}));
  66125. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66126. var BABYLON;
  66127. (function (BABYLON) {
  66128. var GearVRController = /** @class */ (function (_super) {
  66129. __extends(GearVRController, _super);
  66130. function GearVRController(vrGamepad) {
  66131. var _this = _super.call(this, vrGamepad) || this;
  66132. _this._buttonIndexToObservableNameMap = [
  66133. 'onTrackpadChangedObservable',
  66134. 'onTriggerStateChangedObservable' // Trigger
  66135. ];
  66136. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66137. return _this;
  66138. }
  66139. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66140. var _this = this;
  66141. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66142. _this._defaultModel = newMeshes[1];
  66143. _this.attachToMesh(_this._defaultModel);
  66144. if (meshLoaded) {
  66145. meshLoaded(_this._defaultModel);
  66146. }
  66147. });
  66148. };
  66149. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66150. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66151. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66152. // Only emit events for buttons that we know how to map from index to observable
  66153. var observable = this[observableName];
  66154. if (observable) {
  66155. observable.notifyObservers(state);
  66156. }
  66157. }
  66158. };
  66159. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66160. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66161. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66162. return GearVRController;
  66163. }(BABYLON.WebVRController));
  66164. BABYLON.GearVRController = GearVRController;
  66165. })(BABYLON || (BABYLON = {}));
  66166. //# sourceMappingURL=babylon.gearVRController.js.map
  66167. var BABYLON;
  66168. (function (BABYLON) {
  66169. /**
  66170. * Google Daydream controller
  66171. */
  66172. var DaydreamController = /** @class */ (function (_super) {
  66173. __extends(DaydreamController, _super);
  66174. function DaydreamController(vrGamepad) {
  66175. var _this = _super.call(this, vrGamepad) || this;
  66176. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66177. return _this;
  66178. }
  66179. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66180. var _this = this;
  66181. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66182. _this._defaultModel = newMeshes[1];
  66183. _this.attachToMesh(_this._defaultModel);
  66184. if (meshLoaded) {
  66185. meshLoaded(_this._defaultModel);
  66186. }
  66187. });
  66188. };
  66189. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66190. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66191. if (buttonIdx === 0) {
  66192. var observable = this.onTriggerStateChangedObservable;
  66193. if (observable) {
  66194. observable.notifyObservers(state);
  66195. }
  66196. }
  66197. else {
  66198. // If the app or home buttons are ever made available
  66199. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66200. }
  66201. };
  66202. /**
  66203. * Base Url for the controller model.
  66204. */
  66205. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66206. /**
  66207. * File name for the controller model.
  66208. */
  66209. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66210. /**
  66211. * Gamepad Id prefix used to identify Daydream Controller.
  66212. */
  66213. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66214. return DaydreamController;
  66215. }(BABYLON.WebVRController));
  66216. BABYLON.DaydreamController = DaydreamController;
  66217. })(BABYLON || (BABYLON = {}));
  66218. //# sourceMappingURL=babylon.daydreamController.js.map
  66219. var BABYLON;
  66220. (function (BABYLON) {
  66221. var FollowCamera = /** @class */ (function (_super) {
  66222. __extends(FollowCamera, _super);
  66223. function FollowCamera(name, position, scene, lockedTarget) {
  66224. if (lockedTarget === void 0) { lockedTarget = null; }
  66225. var _this = _super.call(this, name, position, scene) || this;
  66226. _this.radius = 12;
  66227. _this.rotationOffset = 0;
  66228. _this.heightOffset = 4;
  66229. _this.cameraAcceleration = 0.05;
  66230. _this.maxCameraSpeed = 20;
  66231. _this.lockedTarget = lockedTarget;
  66232. return _this;
  66233. }
  66234. FollowCamera.prototype.getRadians = function (degrees) {
  66235. return degrees * Math.PI / 180;
  66236. };
  66237. FollowCamera.prototype.follow = function (cameraTarget) {
  66238. if (!cameraTarget)
  66239. return;
  66240. var yRotation;
  66241. if (cameraTarget.rotationQuaternion) {
  66242. var rotMatrix = new BABYLON.Matrix();
  66243. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66244. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66245. }
  66246. else {
  66247. yRotation = cameraTarget.rotation.y;
  66248. }
  66249. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66250. var targetPosition = cameraTarget.getAbsolutePosition();
  66251. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66252. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66253. var dx = targetX - this.position.x;
  66254. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66255. var dz = (targetZ) - this.position.z;
  66256. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66257. var vy = dy * this.cameraAcceleration;
  66258. var vz = dz * this.cameraAcceleration * 2;
  66259. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66260. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66261. }
  66262. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66263. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66264. }
  66265. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66266. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66267. }
  66268. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66269. this.setTarget(targetPosition);
  66270. };
  66271. FollowCamera.prototype._checkInputs = function () {
  66272. _super.prototype._checkInputs.call(this);
  66273. if (this.lockedTarget) {
  66274. this.follow(this.lockedTarget);
  66275. }
  66276. };
  66277. FollowCamera.prototype.getClassName = function () {
  66278. return "FollowCamera";
  66279. };
  66280. __decorate([
  66281. BABYLON.serialize()
  66282. ], FollowCamera.prototype, "radius", void 0);
  66283. __decorate([
  66284. BABYLON.serialize()
  66285. ], FollowCamera.prototype, "rotationOffset", void 0);
  66286. __decorate([
  66287. BABYLON.serialize()
  66288. ], FollowCamera.prototype, "heightOffset", void 0);
  66289. __decorate([
  66290. BABYLON.serialize()
  66291. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66292. __decorate([
  66293. BABYLON.serialize()
  66294. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66295. __decorate([
  66296. BABYLON.serializeAsMeshReference("lockedTargetId")
  66297. ], FollowCamera.prototype, "lockedTarget", void 0);
  66298. return FollowCamera;
  66299. }(BABYLON.TargetCamera));
  66300. BABYLON.FollowCamera = FollowCamera;
  66301. var ArcFollowCamera = /** @class */ (function (_super) {
  66302. __extends(ArcFollowCamera, _super);
  66303. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66304. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66305. _this.alpha = alpha;
  66306. _this.beta = beta;
  66307. _this.radius = radius;
  66308. _this.target = target;
  66309. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66310. _this.follow();
  66311. return _this;
  66312. }
  66313. ArcFollowCamera.prototype.follow = function () {
  66314. if (!this.target) {
  66315. return;
  66316. }
  66317. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66318. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66319. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66320. var targetPosition = this.target.getAbsolutePosition();
  66321. this.position = targetPosition.add(this._cartesianCoordinates);
  66322. this.setTarget(targetPosition);
  66323. };
  66324. ArcFollowCamera.prototype._checkInputs = function () {
  66325. _super.prototype._checkInputs.call(this);
  66326. this.follow();
  66327. };
  66328. ArcFollowCamera.prototype.getClassName = function () {
  66329. return "ArcFollowCamera";
  66330. };
  66331. return ArcFollowCamera;
  66332. }(BABYLON.TargetCamera));
  66333. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66334. })(BABYLON || (BABYLON = {}));
  66335. //# sourceMappingURL=babylon.followCamera.js.map
  66336. var BABYLON;
  66337. (function (BABYLON) {
  66338. // We're mainly based on the logic defined into the FreeCamera code
  66339. var UniversalCamera = /** @class */ (function (_super) {
  66340. __extends(UniversalCamera, _super);
  66341. //-- end properties for backward compatibility for inputs
  66342. function UniversalCamera(name, position, scene) {
  66343. var _this = _super.call(this, name, position, scene) || this;
  66344. _this.inputs.addGamepad();
  66345. return _this;
  66346. }
  66347. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66348. //-- Begin properties for backward compatibility for inputs
  66349. get: function () {
  66350. var gamepad = this.inputs.attached["gamepad"];
  66351. if (gamepad)
  66352. return gamepad.gamepadAngularSensibility;
  66353. return 0;
  66354. },
  66355. set: function (value) {
  66356. var gamepad = this.inputs.attached["gamepad"];
  66357. if (gamepad)
  66358. gamepad.gamepadAngularSensibility = value;
  66359. },
  66360. enumerable: true,
  66361. configurable: true
  66362. });
  66363. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66364. get: function () {
  66365. var gamepad = this.inputs.attached["gamepad"];
  66366. if (gamepad)
  66367. return gamepad.gamepadMoveSensibility;
  66368. return 0;
  66369. },
  66370. set: function (value) {
  66371. var gamepad = this.inputs.attached["gamepad"];
  66372. if (gamepad)
  66373. gamepad.gamepadMoveSensibility = value;
  66374. },
  66375. enumerable: true,
  66376. configurable: true
  66377. });
  66378. UniversalCamera.prototype.getClassName = function () {
  66379. return "UniversalCamera";
  66380. };
  66381. return UniversalCamera;
  66382. }(BABYLON.TouchCamera));
  66383. BABYLON.UniversalCamera = UniversalCamera;
  66384. })(BABYLON || (BABYLON = {}));
  66385. //# sourceMappingURL=babylon.universalCamera.js.map
  66386. var BABYLON;
  66387. (function (BABYLON) {
  66388. // We're mainly based on the logic defined into the FreeCamera code
  66389. var GamepadCamera = /** @class */ (function (_super) {
  66390. __extends(GamepadCamera, _super);
  66391. //-- end properties for backward compatibility for inputs
  66392. function GamepadCamera(name, position, scene) {
  66393. return _super.call(this, name, position, scene) || this;
  66394. }
  66395. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66396. //-- Begin properties for backward compatibility for inputs
  66397. get: function () {
  66398. var gamepad = this.inputs.attached["gamepad"];
  66399. if (gamepad)
  66400. return gamepad.gamepadAngularSensibility;
  66401. return 0;
  66402. },
  66403. set: function (value) {
  66404. var gamepad = this.inputs.attached["gamepad"];
  66405. if (gamepad)
  66406. gamepad.gamepadAngularSensibility = value;
  66407. },
  66408. enumerable: true,
  66409. configurable: true
  66410. });
  66411. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66412. get: function () {
  66413. var gamepad = this.inputs.attached["gamepad"];
  66414. if (gamepad)
  66415. return gamepad.gamepadMoveSensibility;
  66416. return 0;
  66417. },
  66418. set: function (value) {
  66419. var gamepad = this.inputs.attached["gamepad"];
  66420. if (gamepad)
  66421. gamepad.gamepadMoveSensibility = value;
  66422. },
  66423. enumerable: true,
  66424. configurable: true
  66425. });
  66426. GamepadCamera.prototype.getClassName = function () {
  66427. return "GamepadCamera";
  66428. };
  66429. return GamepadCamera;
  66430. }(BABYLON.UniversalCamera));
  66431. BABYLON.GamepadCamera = GamepadCamera;
  66432. })(BABYLON || (BABYLON = {}));
  66433. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66434. var BABYLON;
  66435. (function (BABYLON) {
  66436. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66437. function PostProcessRenderPipelineManager() {
  66438. this._renderPipelines = {};
  66439. }
  66440. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66441. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66442. };
  66443. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66444. if (unique === void 0) { unique = false; }
  66445. var renderPipeline = this._renderPipelines[renderPipelineName];
  66446. if (!renderPipeline) {
  66447. return;
  66448. }
  66449. renderPipeline._attachCameras(cameras, unique);
  66450. };
  66451. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66452. var renderPipeline = this._renderPipelines[renderPipelineName];
  66453. if (!renderPipeline) {
  66454. return;
  66455. }
  66456. renderPipeline._detachCameras(cameras);
  66457. };
  66458. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66459. var renderPipeline = this._renderPipelines[renderPipelineName];
  66460. if (!renderPipeline) {
  66461. return;
  66462. }
  66463. renderPipeline._enableEffect(renderEffectName, cameras);
  66464. };
  66465. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66466. var renderPipeline = this._renderPipelines[renderPipelineName];
  66467. if (!renderPipeline) {
  66468. return;
  66469. }
  66470. renderPipeline._disableEffect(renderEffectName, cameras);
  66471. };
  66472. PostProcessRenderPipelineManager.prototype.update = function () {
  66473. for (var renderPipelineName in this._renderPipelines) {
  66474. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66475. var pipeline = this._renderPipelines[renderPipelineName];
  66476. if (!pipeline.isSupported) {
  66477. pipeline.dispose();
  66478. delete this._renderPipelines[renderPipelineName];
  66479. }
  66480. else {
  66481. pipeline._update();
  66482. }
  66483. }
  66484. }
  66485. };
  66486. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66487. for (var renderPipelineName in this._renderPipelines) {
  66488. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66489. var pipeline = this._renderPipelines[renderPipelineName];
  66490. pipeline._rebuild();
  66491. }
  66492. }
  66493. };
  66494. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66495. for (var renderPipelineName in this._renderPipelines) {
  66496. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66497. var pipeline = this._renderPipelines[renderPipelineName];
  66498. pipeline.dispose();
  66499. }
  66500. }
  66501. };
  66502. return PostProcessRenderPipelineManager;
  66503. }());
  66504. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66505. })(BABYLON || (BABYLON = {}));
  66506. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66507. var BABYLON;
  66508. (function (BABYLON) {
  66509. /**
  66510. * This represents a set of one or more post processes in Babylon.
  66511. * A post process can be used to apply a shader to a texture after it is rendered.
  66512. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66513. */
  66514. var PostProcessRenderEffect = /** @class */ (function () {
  66515. /**
  66516. * Instantiates a post process render effect.
  66517. * A post process can be used to apply a shader to a texture after it is rendered.
  66518. * @param engine The engine the effect is tied to
  66519. * @param name The name of the effect
  66520. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66521. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66522. */
  66523. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66524. this._name = name;
  66525. this._singleInstance = singleInstance || true;
  66526. this._getPostProcesses = getPostProcesses;
  66527. this._cameras = {};
  66528. this._indicesForCamera = {};
  66529. this._postProcesses = {};
  66530. }
  66531. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66532. /**
  66533. * Checks if all the post processes in the effect are supported.
  66534. */
  66535. get: function () {
  66536. for (var index in this._postProcesses) {
  66537. for (var ppIndex in this._postProcesses[index]) {
  66538. if (!this._postProcesses[index][ppIndex].isSupported) {
  66539. return false;
  66540. }
  66541. }
  66542. }
  66543. return true;
  66544. },
  66545. enumerable: true,
  66546. configurable: true
  66547. });
  66548. /**
  66549. * Updates the current state of the effect
  66550. */
  66551. PostProcessRenderEffect.prototype._update = function () {
  66552. };
  66553. /**
  66554. * Attaches the effect on cameras
  66555. * @param cameras The camera to attach to.
  66556. */
  66557. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66558. var _this = this;
  66559. var cameraKey;
  66560. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66561. if (!cams) {
  66562. return;
  66563. }
  66564. for (var i = 0; i < cams.length; i++) {
  66565. var camera = cams[i];
  66566. var cameraName = camera.name;
  66567. if (this._singleInstance) {
  66568. cameraKey = 0;
  66569. }
  66570. else {
  66571. cameraKey = cameraName;
  66572. }
  66573. if (!this._postProcesses[cameraKey]) {
  66574. var postProcess = this._getPostProcesses();
  66575. if (postProcess) {
  66576. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66577. }
  66578. }
  66579. if (!this._indicesForCamera[cameraName]) {
  66580. this._indicesForCamera[cameraName] = [];
  66581. }
  66582. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66583. var index = camera.attachPostProcess(postProcess);
  66584. _this._indicesForCamera[cameraName].push(index);
  66585. });
  66586. if (!this._cameras[cameraName]) {
  66587. this._cameras[cameraName] = camera;
  66588. }
  66589. }
  66590. };
  66591. /**
  66592. * Detatches the effect on cameras
  66593. * @param cameras The camera to detatch from.
  66594. */
  66595. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66596. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66597. if (!cams) {
  66598. return;
  66599. }
  66600. for (var i = 0; i < cams.length; i++) {
  66601. var camera = cams[i];
  66602. var cameraName = camera.name;
  66603. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66604. camera.detachPostProcess(postProcess);
  66605. });
  66606. if (this._cameras[cameraName]) {
  66607. //this._indicesForCamera.splice(index, 1);
  66608. this._cameras[cameraName] = null;
  66609. }
  66610. }
  66611. };
  66612. /**
  66613. * Enables the effect on given cameras
  66614. * @param cameras The camera to enable.
  66615. */
  66616. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66617. var _this = this;
  66618. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66619. if (!cams) {
  66620. return;
  66621. }
  66622. for (var i = 0; i < cams.length; i++) {
  66623. var camera = cams[i];
  66624. var cameraName = camera.name;
  66625. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66626. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66627. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66628. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66629. });
  66630. }
  66631. }
  66632. }
  66633. };
  66634. /**
  66635. * Disables the effect on the given cameras
  66636. * @param cameras The camera to disable.
  66637. */
  66638. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66639. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66640. if (!cams) {
  66641. return;
  66642. }
  66643. for (var i = 0; i < cams.length; i++) {
  66644. var camera = cams[i];
  66645. var cameraName = camera.name;
  66646. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66647. camera.detachPostProcess(postProcess);
  66648. });
  66649. }
  66650. };
  66651. /**
  66652. * Gets a list of the post processes contained in the effect.
  66653. * @param camera The camera to get the post processes on.
  66654. * @returns The list of the post processes in the effect.
  66655. */
  66656. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66657. if (this._singleInstance) {
  66658. return this._postProcesses[0];
  66659. }
  66660. else {
  66661. if (!camera) {
  66662. return null;
  66663. }
  66664. return this._postProcesses[camera.name];
  66665. }
  66666. };
  66667. return PostProcessRenderEffect;
  66668. }());
  66669. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66670. })(BABYLON || (BABYLON = {}));
  66671. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66672. var BABYLON;
  66673. (function (BABYLON) {
  66674. var PostProcessRenderPipeline = /** @class */ (function () {
  66675. function PostProcessRenderPipeline(engine, name) {
  66676. this.engine = engine;
  66677. this._name = name;
  66678. this._renderEffects = {};
  66679. this._renderEffectsForIsolatedPass = new Array();
  66680. this._cameras = [];
  66681. }
  66682. PostProcessRenderPipeline.prototype.getClassName = function () {
  66683. return "PostProcessRenderPipeline";
  66684. };
  66685. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66686. get: function () {
  66687. for (var renderEffectName in this._renderEffects) {
  66688. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66689. if (!this._renderEffects[renderEffectName].isSupported) {
  66690. return false;
  66691. }
  66692. }
  66693. }
  66694. return true;
  66695. },
  66696. enumerable: true,
  66697. configurable: true
  66698. });
  66699. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66700. this._renderEffects[renderEffect._name] = renderEffect;
  66701. };
  66702. // private
  66703. PostProcessRenderPipeline.prototype._rebuild = function () {
  66704. };
  66705. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66706. var renderEffects = this._renderEffects[renderEffectName];
  66707. if (!renderEffects) {
  66708. return;
  66709. }
  66710. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66711. };
  66712. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66713. var renderEffects = this._renderEffects[renderEffectName];
  66714. if (!renderEffects) {
  66715. return;
  66716. }
  66717. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66718. };
  66719. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66720. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66721. if (!cams) {
  66722. return;
  66723. }
  66724. var indicesToDelete = [];
  66725. var i;
  66726. for (i = 0; i < cams.length; i++) {
  66727. var camera = cams[i];
  66728. var cameraName = camera.name;
  66729. if (this._cameras.indexOf(camera) === -1) {
  66730. this._cameras[cameraName] = camera;
  66731. }
  66732. else if (unique) {
  66733. indicesToDelete.push(i);
  66734. }
  66735. }
  66736. for (i = 0; i < indicesToDelete.length; i++) {
  66737. cameras.splice(indicesToDelete[i], 1);
  66738. }
  66739. for (var renderEffectName in this._renderEffects) {
  66740. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66741. this._renderEffects[renderEffectName]._attachCameras(cams);
  66742. }
  66743. }
  66744. };
  66745. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66746. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66747. if (!cams) {
  66748. return;
  66749. }
  66750. for (var renderEffectName in this._renderEffects) {
  66751. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66752. this._renderEffects[renderEffectName]._detachCameras(cams);
  66753. }
  66754. }
  66755. for (var i = 0; i < cams.length; i++) {
  66756. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66757. }
  66758. };
  66759. PostProcessRenderPipeline.prototype._update = function () {
  66760. for (var renderEffectName in this._renderEffects) {
  66761. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66762. this._renderEffects[renderEffectName]._update();
  66763. }
  66764. }
  66765. for (var i = 0; i < this._cameras.length; i++) {
  66766. var cameraName = this._cameras[i].name;
  66767. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66768. this._renderEffectsForIsolatedPass[cameraName]._update();
  66769. }
  66770. }
  66771. };
  66772. PostProcessRenderPipeline.prototype._reset = function () {
  66773. this._renderEffects = {};
  66774. this._renderEffectsForIsolatedPass = new Array();
  66775. };
  66776. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66777. // 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)
  66778. var effectKeys = Object.keys(this._renderEffects);
  66779. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66780. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66781. if (postProcesses) {
  66782. postProcesses[0].samples = 4;
  66783. return true;
  66784. }
  66785. }
  66786. return false;
  66787. };
  66788. PostProcessRenderPipeline.prototype.dispose = function () {
  66789. // Must be implemented by children
  66790. };
  66791. __decorate([
  66792. BABYLON.serialize()
  66793. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66794. return PostProcessRenderPipeline;
  66795. }());
  66796. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66797. })(BABYLON || (BABYLON = {}));
  66798. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66799. var BABYLON;
  66800. (function (BABYLON) {
  66801. /**
  66802. * This represents a depth renderer in Babylon.
  66803. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66804. */
  66805. var DepthRenderer = /** @class */ (function () {
  66806. /**
  66807. * Instantiates a depth renderer
  66808. * @param scene The scene the renderer belongs to
  66809. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66810. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66811. */
  66812. function DepthRenderer(scene, type, camera) {
  66813. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66814. if (camera === void 0) { camera = null; }
  66815. var _this = this;
  66816. this._scene = scene;
  66817. this._camera = camera;
  66818. var engine = scene.getEngine();
  66819. // Render target
  66820. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66821. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66822. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66823. this._depthMap.refreshRate = 1;
  66824. this._depthMap.renderParticles = false;
  66825. this._depthMap.renderList = null;
  66826. // Camera to get depth map from to support multiple concurrent cameras
  66827. this._depthMap.activeCamera = this._camera;
  66828. this._depthMap.ignoreCameraViewport = true;
  66829. this._depthMap.useCameraPostProcesses = false;
  66830. // set default depth value to 1.0 (far away)
  66831. this._depthMap.onClearObservable.add(function (engine) {
  66832. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66833. });
  66834. // Custom render function
  66835. var renderSubMesh = function (subMesh) {
  66836. var mesh = subMesh.getRenderingMesh();
  66837. var scene = _this._scene;
  66838. var engine = scene.getEngine();
  66839. var material = subMesh.getMaterial();
  66840. if (!material) {
  66841. return;
  66842. }
  66843. // Culling and reverse (right handed system)
  66844. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66845. // Managing instances
  66846. var batch = mesh._getInstancesRenderList(subMesh._id);
  66847. if (batch.mustReturn) {
  66848. return;
  66849. }
  66850. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66851. var camera = _this._camera || scene.activeCamera;
  66852. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66853. engine.enableEffect(_this._effect);
  66854. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66855. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66856. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66857. // Alpha test
  66858. if (material && material.needAlphaTesting()) {
  66859. var alphaTexture = material.getAlphaTestTexture();
  66860. if (alphaTexture) {
  66861. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66862. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66863. }
  66864. }
  66865. // Bones
  66866. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66867. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66868. }
  66869. // Draw
  66870. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66871. }
  66872. };
  66873. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66874. var index;
  66875. if (depthOnlySubMeshes.length) {
  66876. engine.setColorWrite(false);
  66877. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66878. renderSubMesh(depthOnlySubMeshes.data[index]);
  66879. }
  66880. engine.setColorWrite(true);
  66881. }
  66882. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66883. renderSubMesh(opaqueSubMeshes.data[index]);
  66884. }
  66885. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66886. renderSubMesh(alphaTestSubMeshes.data[index]);
  66887. }
  66888. };
  66889. }
  66890. /**
  66891. * Creates the depth rendering effect and checks if the effect is ready.
  66892. * @param subMesh The submesh to be used to render the depth map of
  66893. * @param useInstances If multiple world instances should be used
  66894. * @returns if the depth renderer is ready to render the depth map
  66895. */
  66896. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66897. var material = subMesh.getMaterial();
  66898. if (material.disableDepthWrite) {
  66899. return false;
  66900. }
  66901. var defines = [];
  66902. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66903. var mesh = subMesh.getMesh();
  66904. // Alpha test
  66905. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66906. defines.push("#define ALPHATEST");
  66907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66908. attribs.push(BABYLON.VertexBuffer.UVKind);
  66909. defines.push("#define UV1");
  66910. }
  66911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66912. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66913. defines.push("#define UV2");
  66914. }
  66915. }
  66916. // Bones
  66917. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66918. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66919. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66920. if (mesh.numBoneInfluencers > 4) {
  66921. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66922. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66923. }
  66924. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66925. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66926. }
  66927. else {
  66928. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66929. }
  66930. // Instances
  66931. if (useInstances) {
  66932. defines.push("#define INSTANCES");
  66933. attribs.push("world0");
  66934. attribs.push("world1");
  66935. attribs.push("world2");
  66936. attribs.push("world3");
  66937. }
  66938. // Get correct effect
  66939. var join = defines.join("\n");
  66940. if (this._cachedDefines !== join) {
  66941. this._cachedDefines = join;
  66942. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66943. }
  66944. return this._effect.isReady();
  66945. };
  66946. /**
  66947. * Gets the texture which the depth map will be written to.
  66948. * @returns The depth map texture
  66949. */
  66950. DepthRenderer.prototype.getDepthMap = function () {
  66951. return this._depthMap;
  66952. };
  66953. /**
  66954. * Disposes of the depth renderer.
  66955. */
  66956. DepthRenderer.prototype.dispose = function () {
  66957. this._depthMap.dispose();
  66958. };
  66959. return DepthRenderer;
  66960. }());
  66961. BABYLON.DepthRenderer = DepthRenderer;
  66962. })(BABYLON || (BABYLON = {}));
  66963. //# sourceMappingURL=babylon.depthRenderer.js.map
  66964. var BABYLON;
  66965. (function (BABYLON) {
  66966. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66967. __extends(SSAORenderingPipeline, _super);
  66968. /**
  66969. * @constructor
  66970. * @param {string} name - The rendering pipeline name
  66971. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66972. * @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 }
  66973. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66974. */
  66975. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66976. var _this = _super.call(this, scene.getEngine(), name) || this;
  66977. // Members
  66978. /**
  66979. * The PassPostProcess id in the pipeline that contains the original scene color
  66980. * @type {string}
  66981. */
  66982. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66983. /**
  66984. * The SSAO PostProcess id in the pipeline
  66985. * @type {string}
  66986. */
  66987. _this.SSAORenderEffect = "SSAORenderEffect";
  66988. /**
  66989. * The horizontal blur PostProcess id in the pipeline
  66990. * @type {string}
  66991. */
  66992. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66993. /**
  66994. * The vertical blur PostProcess id in the pipeline
  66995. * @type {string}
  66996. */
  66997. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66998. /**
  66999. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67000. * @type {string}
  67001. */
  67002. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67003. /**
  67004. * The output strength of the SSAO post-process. Default value is 1.0.
  67005. * @type {number}
  67006. */
  67007. _this.totalStrength = 1.0;
  67008. /**
  67009. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67010. * @type {number}
  67011. */
  67012. _this.radius = 0.0001;
  67013. /**
  67014. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67015. * Must not be equal to fallOff and superior to fallOff.
  67016. * Default value is 0.975
  67017. * @type {number}
  67018. */
  67019. _this.area = 0.0075;
  67020. /**
  67021. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67022. * Must not be equal to area and inferior to area.
  67023. * Default value is 0.0
  67024. * @type {number}
  67025. */
  67026. _this.fallOff = 0.000001;
  67027. /**
  67028. * The base color of the SSAO post-process
  67029. * The final result is "base + ssao" between [0, 1]
  67030. * @type {number}
  67031. */
  67032. _this.base = 0.5;
  67033. _this._firstUpdate = true;
  67034. _this._scene = scene;
  67035. // Set up assets
  67036. _this._createRandomTexture();
  67037. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67038. var ssaoRatio = ratio.ssaoRatio || ratio;
  67039. var combineRatio = ratio.combineRatio || ratio;
  67040. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67041. _this._createSSAOPostProcess(ssaoRatio);
  67042. _this._createBlurPostProcess(ssaoRatio);
  67043. _this._createSSAOCombinePostProcess(combineRatio);
  67044. // Set up pipeline
  67045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67047. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67048. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67049. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67050. // Finish
  67051. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67052. if (cameras)
  67053. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67054. return _this;
  67055. }
  67056. // Public Methods
  67057. /**
  67058. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67059. */
  67060. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67061. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67062. for (var i = 0; i < this._scene.cameras.length; i++) {
  67063. var camera = this._scene.cameras[i];
  67064. this._originalColorPostProcess.dispose(camera);
  67065. this._ssaoPostProcess.dispose(camera);
  67066. this._blurHPostProcess.dispose(camera);
  67067. this._blurVPostProcess.dispose(camera);
  67068. this._ssaoCombinePostProcess.dispose(camera);
  67069. }
  67070. this._randomTexture.dispose();
  67071. if (disableDepthRender)
  67072. this._scene.disableDepthRenderer();
  67073. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67074. _super.prototype.dispose.call(this);
  67075. };
  67076. // Private Methods
  67077. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67078. var _this = this;
  67079. var size = 16;
  67080. 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);
  67081. 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);
  67082. this._blurHPostProcess.onActivateObservable.add(function () {
  67083. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67084. _this._blurHPostProcess.kernel = size * dw;
  67085. });
  67086. this._blurVPostProcess.onActivateObservable.add(function () {
  67087. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67088. _this._blurVPostProcess.kernel = size * dw;
  67089. });
  67090. };
  67091. SSAORenderingPipeline.prototype._rebuild = function () {
  67092. this._firstUpdate = true;
  67093. _super.prototype._rebuild.call(this);
  67094. };
  67095. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67096. var _this = this;
  67097. var numSamples = 16;
  67098. var sampleSphere = [
  67099. 0.5381, 0.1856, -0.4319,
  67100. 0.1379, 0.2486, 0.4430,
  67101. 0.3371, 0.5679, -0.0057,
  67102. -0.6999, -0.0451, -0.0019,
  67103. 0.0689, -0.1598, -0.8547,
  67104. 0.0560, 0.0069, -0.1843,
  67105. -0.0146, 0.1402, 0.0762,
  67106. 0.0100, -0.1924, -0.0344,
  67107. -0.3577, -0.5301, -0.4358,
  67108. -0.3169, 0.1063, 0.0158,
  67109. 0.0103, -0.5869, 0.0046,
  67110. -0.0897, -0.4940, 0.3287,
  67111. 0.7119, -0.0154, -0.0918,
  67112. -0.0533, 0.0596, -0.5411,
  67113. 0.0352, -0.0631, 0.5460,
  67114. -0.4776, 0.2847, -0.0271
  67115. ];
  67116. var samplesFactor = 1.0 / numSamples;
  67117. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67118. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67119. "area", "fallOff", "base", "range", "viewport"
  67120. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67121. this._ssaoPostProcess.onApply = function (effect) {
  67122. if (_this._firstUpdate) {
  67123. effect.setArray3("sampleSphere", sampleSphere);
  67124. effect.setFloat("samplesFactor", samplesFactor);
  67125. effect.setFloat("randTextureTiles", 4.0);
  67126. }
  67127. effect.setFloat("totalStrength", _this.totalStrength);
  67128. effect.setFloat("radius", _this.radius);
  67129. effect.setFloat("area", _this.area);
  67130. effect.setFloat("fallOff", _this.fallOff);
  67131. effect.setFloat("base", _this.base);
  67132. effect.setTexture("textureSampler", _this._depthTexture);
  67133. effect.setTexture("randomSampler", _this._randomTexture);
  67134. };
  67135. };
  67136. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67137. var _this = this;
  67138. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67139. this._ssaoCombinePostProcess.onApply = function (effect) {
  67140. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67141. };
  67142. };
  67143. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67144. var size = 512;
  67145. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67146. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67147. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67148. var context = this._randomTexture.getContext();
  67149. var rand = function (min, max) {
  67150. return Math.random() * (max - min) + min;
  67151. };
  67152. var randVector = BABYLON.Vector3.Zero();
  67153. for (var x = 0; x < size; x++) {
  67154. for (var y = 0; y < size; y++) {
  67155. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67156. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67157. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67158. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67159. context.fillRect(x, y, 1, 1);
  67160. }
  67161. }
  67162. this._randomTexture.update(false);
  67163. };
  67164. __decorate([
  67165. BABYLON.serialize()
  67166. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67167. __decorate([
  67168. BABYLON.serialize()
  67169. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67170. __decorate([
  67171. BABYLON.serialize()
  67172. ], SSAORenderingPipeline.prototype, "area", void 0);
  67173. __decorate([
  67174. BABYLON.serialize()
  67175. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67176. __decorate([
  67177. BABYLON.serialize()
  67178. ], SSAORenderingPipeline.prototype, "base", void 0);
  67179. return SSAORenderingPipeline;
  67180. }(BABYLON.PostProcessRenderPipeline));
  67181. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67182. })(BABYLON || (BABYLON = {}));
  67183. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67184. var BABYLON;
  67185. (function (BABYLON) {
  67186. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67187. __extends(SSAO2RenderingPipeline, _super);
  67188. /**
  67189. * @constructor
  67190. * @param {string} name - The rendering pipeline name
  67191. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67192. * @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 }
  67193. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67194. */
  67195. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67196. var _this = _super.call(this, scene.getEngine(), name) || this;
  67197. // Members
  67198. /**
  67199. * The PassPostProcess id in the pipeline that contains the original scene color
  67200. * @type {string}
  67201. */
  67202. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67203. /**
  67204. * The SSAO PostProcess id in the pipeline
  67205. * @type {string}
  67206. */
  67207. _this.SSAORenderEffect = "SSAORenderEffect";
  67208. /**
  67209. * The horizontal blur PostProcess id in the pipeline
  67210. * @type {string}
  67211. */
  67212. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67213. /**
  67214. * The vertical blur PostProcess id in the pipeline
  67215. * @type {string}
  67216. */
  67217. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67218. /**
  67219. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67220. * @type {string}
  67221. */
  67222. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67223. /**
  67224. * The output strength of the SSAO post-process. Default value is 1.0.
  67225. * @type {number}
  67226. */
  67227. _this.totalStrength = 1.0;
  67228. /**
  67229. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67230. * @type {number}
  67231. */
  67232. _this.maxZ = 100.0;
  67233. /**
  67234. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67235. * @type {number}
  67236. */
  67237. _this.minZAspect = 0.2;
  67238. /**
  67239. * Number of samples used for the SSAO calculations. Default value is 8
  67240. * @type {number}
  67241. */
  67242. _this._samples = 8;
  67243. /**
  67244. * Are we using bilateral blur ?
  67245. * @type {boolean}
  67246. */
  67247. _this._expensiveBlur = true;
  67248. /**
  67249. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67250. * @type {number}
  67251. */
  67252. _this.radius = 2.0;
  67253. /**
  67254. * The base color of the SSAO post-process
  67255. * The final result is "base + ssao" between [0, 1]
  67256. * @type {number}
  67257. */
  67258. _this.base = 0.1;
  67259. _this._firstUpdate = true;
  67260. _this._scene = scene;
  67261. if (!_this.isSupported) {
  67262. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67263. return _this;
  67264. }
  67265. var ssaoRatio = ratio.ssaoRatio || ratio;
  67266. var blurRatio = ratio.blurRatio || ratio;
  67267. // Set up assets
  67268. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67269. _this._createRandomTexture();
  67270. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67271. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67272. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67273. _this._createSSAOPostProcess(1.0);
  67274. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67275. _this._createSSAOCombinePostProcess(blurRatio);
  67276. // Set up pipeline
  67277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67278. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67281. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67282. // Finish
  67283. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67284. if (cameras)
  67285. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67286. return _this;
  67287. }
  67288. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67289. get: function () {
  67290. return this._samples;
  67291. },
  67292. set: function (n) {
  67293. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67294. this._samples = n;
  67295. this._sampleSphere = this._generateHemisphere();
  67296. this._firstUpdate = true;
  67297. },
  67298. enumerable: true,
  67299. configurable: true
  67300. });
  67301. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67302. get: function () {
  67303. return this._expensiveBlur;
  67304. },
  67305. set: function (b) {
  67306. 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"]);
  67307. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67308. this._expensiveBlur = b;
  67309. this._firstUpdate = true;
  67310. },
  67311. enumerable: true,
  67312. configurable: true
  67313. });
  67314. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67315. /**
  67316. * Support test.
  67317. * @type {boolean}
  67318. */
  67319. get: function () {
  67320. var engine = BABYLON.Engine.LastCreatedEngine;
  67321. if (!engine) {
  67322. return false;
  67323. }
  67324. return engine.getCaps().drawBuffersExtension;
  67325. },
  67326. enumerable: true,
  67327. configurable: true
  67328. });
  67329. // Public Methods
  67330. /**
  67331. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67332. */
  67333. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67334. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67335. for (var i = 0; i < this._scene.cameras.length; i++) {
  67336. var camera = this._scene.cameras[i];
  67337. this._originalColorPostProcess.dispose(camera);
  67338. this._ssaoPostProcess.dispose(camera);
  67339. this._blurHPostProcess.dispose(camera);
  67340. this._blurVPostProcess.dispose(camera);
  67341. this._ssaoCombinePostProcess.dispose(camera);
  67342. }
  67343. this._randomTexture.dispose();
  67344. if (disableGeometryBufferRenderer)
  67345. this._scene.disableGeometryBufferRenderer();
  67346. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67347. _super.prototype.dispose.call(this);
  67348. };
  67349. // Private Methods
  67350. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67351. var _this = this;
  67352. this._samplerOffsets = [];
  67353. var expensive = this.expensiveBlur;
  67354. for (var i = -8; i < 8; i++) {
  67355. this._samplerOffsets.push(i * 2 + 0.5);
  67356. }
  67357. 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");
  67358. this._blurHPostProcess.onApply = function (effect) {
  67359. if (!_this._scene.activeCamera) {
  67360. return;
  67361. }
  67362. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67363. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67364. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67365. effect.setFloat("radius", _this.radius);
  67366. effect.setTexture("depthSampler", _this._depthTexture);
  67367. if (_this._firstUpdate) {
  67368. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67369. }
  67370. };
  67371. 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");
  67372. this._blurVPostProcess.onApply = function (effect) {
  67373. if (!_this._scene.activeCamera) {
  67374. return;
  67375. }
  67376. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67377. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67378. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67379. effect.setFloat("radius", _this.radius);
  67380. effect.setTexture("depthSampler", _this._depthTexture);
  67381. if (_this._firstUpdate) {
  67382. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67383. _this._firstUpdate = false;
  67384. }
  67385. };
  67386. };
  67387. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67388. this._firstUpdate = true;
  67389. _super.prototype._rebuild.call(this);
  67390. };
  67391. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67392. var numSamples = this.samples;
  67393. var result = [];
  67394. var vector, scale;
  67395. var rand = function (min, max) {
  67396. return Math.random() * (max - min) + min;
  67397. };
  67398. var i = 0;
  67399. while (i < numSamples) {
  67400. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67401. vector.normalize();
  67402. scale = i / numSamples;
  67403. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67404. vector.scaleInPlace(scale);
  67405. result.push(vector.x, vector.y, vector.z);
  67406. i++;
  67407. }
  67408. return result;
  67409. };
  67410. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67411. var _this = this;
  67412. var numSamples = this.samples;
  67413. this._sampleSphere = this._generateHemisphere();
  67414. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67415. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67416. "base", "range", "projection", "near", "far", "texelSize",
  67417. "xViewport", "yViewport", "maxZ", "minZAspect"
  67418. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67419. this._ssaoPostProcess.onApply = function (effect) {
  67420. if (_this._firstUpdate) {
  67421. effect.setArray3("sampleSphere", _this._sampleSphere);
  67422. effect.setFloat("randTextureTiles", 4.0);
  67423. }
  67424. if (!_this._scene.activeCamera) {
  67425. return;
  67426. }
  67427. effect.setFloat("samplesFactor", 1 / _this.samples);
  67428. effect.setFloat("totalStrength", _this.totalStrength);
  67429. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67430. effect.setFloat("radius", _this.radius);
  67431. effect.setFloat("maxZ", _this.maxZ);
  67432. effect.setFloat("minZAspect", _this.minZAspect);
  67433. effect.setFloat("base", _this.base);
  67434. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67435. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67436. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67437. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67438. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67439. effect.setTexture("textureSampler", _this._depthTexture);
  67440. effect.setTexture("normalSampler", _this._normalTexture);
  67441. effect.setTexture("randomSampler", _this._randomTexture);
  67442. };
  67443. };
  67444. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67445. var _this = this;
  67446. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67447. this._ssaoCombinePostProcess.onApply = function (effect) {
  67448. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67449. };
  67450. };
  67451. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67452. var size = 512;
  67453. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67454. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67455. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67456. var context = this._randomTexture.getContext();
  67457. var rand = function (min, max) {
  67458. return Math.random() * (max - min) + min;
  67459. };
  67460. var randVector = BABYLON.Vector3.Zero();
  67461. for (var x = 0; x < size; x++) {
  67462. for (var y = 0; y < size; y++) {
  67463. randVector.x = rand(0.0, 1.0);
  67464. randVector.y = rand(0.0, 1.0);
  67465. randVector.z = 0.0;
  67466. randVector.normalize();
  67467. randVector.scaleInPlace(255);
  67468. randVector.x = Math.floor(randVector.x);
  67469. randVector.y = Math.floor(randVector.y);
  67470. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67471. context.fillRect(x, y, 1, 1);
  67472. }
  67473. }
  67474. this._randomTexture.update(false);
  67475. };
  67476. __decorate([
  67477. BABYLON.serialize()
  67478. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67479. __decorate([
  67480. BABYLON.serialize()
  67481. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67482. __decorate([
  67483. BABYLON.serialize()
  67484. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67485. __decorate([
  67486. BABYLON.serialize("samples")
  67487. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67488. __decorate([
  67489. BABYLON.serialize("expensiveBlur")
  67490. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67491. __decorate([
  67492. BABYLON.serialize()
  67493. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67494. __decorate([
  67495. BABYLON.serialize()
  67496. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67497. return SSAO2RenderingPipeline;
  67498. }(BABYLON.PostProcessRenderPipeline));
  67499. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67500. })(BABYLON || (BABYLON = {}));
  67501. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67502. // BABYLON.JS Chromatic Aberration GLSL Shader
  67503. // Author: Olivier Guyot
  67504. // Separates very slightly R, G and B colors on the edges of the screen
  67505. // Inspired by Francois Tarlier & Martins Upitis
  67506. var BABYLON;
  67507. (function (BABYLON) {
  67508. var LensRenderingPipeline = /** @class */ (function (_super) {
  67509. __extends(LensRenderingPipeline, _super);
  67510. /**
  67511. * @constructor
  67512. *
  67513. * Effect parameters are as follow:
  67514. * {
  67515. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67516. * edge_blur: number; // from 0 to x (1 for realism)
  67517. * distortion: number; // from 0 to x (1 for realism)
  67518. * grain_amount: number; // from 0 to 1
  67519. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67520. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67521. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67522. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67523. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67524. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67525. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67526. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67527. * }
  67528. * Note: if an effect parameter is unset, effect is disabled
  67529. *
  67530. * @param {string} name - The rendering pipeline name
  67531. * @param {object} parameters - An object containing all parameters (see above)
  67532. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67533. * @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)
  67534. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67535. */
  67536. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67537. if (ratio === void 0) { ratio = 1.0; }
  67538. var _this = _super.call(this, scene.getEngine(), name) || this;
  67539. // Lens effects can be of the following:
  67540. // - chromatic aberration (slight shift of RGB colors)
  67541. // - blur on the edge of the lens
  67542. // - lens distortion
  67543. // - depth-of-field blur & highlights enhancing
  67544. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67545. // - grain effect (noise or custom texture)
  67546. // Two additional texture samplers are needed:
  67547. // - depth map (for depth-of-field)
  67548. // - grain texture
  67549. /**
  67550. * The chromatic aberration PostProcess id in the pipeline
  67551. * @type {string}
  67552. */
  67553. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67554. /**
  67555. * The highlights enhancing PostProcess id in the pipeline
  67556. * @type {string}
  67557. */
  67558. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67559. /**
  67560. * The depth-of-field PostProcess id in the pipeline
  67561. * @type {string}
  67562. */
  67563. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67564. _this._scene = scene;
  67565. // Fetch texture samplers
  67566. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67567. if (parameters.grain_texture) {
  67568. _this._grainTexture = parameters.grain_texture;
  67569. }
  67570. else {
  67571. _this._createGrainTexture();
  67572. }
  67573. // save parameters
  67574. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67575. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67576. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67577. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67578. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67579. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67580. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67581. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67582. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67583. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67584. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67585. // Create effects
  67586. _this._createChromaticAberrationPostProcess(ratio);
  67587. _this._createHighlightsPostProcess(ratio);
  67588. _this._createDepthOfFieldPostProcess(ratio / 4);
  67589. // Set up pipeline
  67590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67593. if (_this._highlightsGain === -1) {
  67594. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67595. }
  67596. // Finish
  67597. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67598. if (cameras) {
  67599. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67600. }
  67601. return _this;
  67602. }
  67603. // public methods (self explanatory)
  67604. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67605. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67606. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67607. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67608. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67609. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67610. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67611. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67612. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67613. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67614. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67615. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67616. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67617. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67618. };
  67619. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67620. this._highlightsPostProcess.updateEffect();
  67621. };
  67622. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67623. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67624. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67625. this._highlightsGain = amount;
  67626. };
  67627. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67628. if (this._highlightsGain === -1) {
  67629. this._highlightsGain = 1.0;
  67630. }
  67631. this._highlightsThreshold = amount;
  67632. };
  67633. LensRenderingPipeline.prototype.disableHighlights = function () {
  67634. this._highlightsGain = -1;
  67635. };
  67636. /**
  67637. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67638. */
  67639. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67640. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67641. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67642. this._chromaticAberrationPostProcess = null;
  67643. this._highlightsPostProcess = null;
  67644. this._depthOfFieldPostProcess = null;
  67645. this._grainTexture.dispose();
  67646. if (disableDepthRender)
  67647. this._scene.disableDepthRenderer();
  67648. };
  67649. // colors shifting and distortion
  67650. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67651. var _this = this;
  67652. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67653. [], // samplers
  67654. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67655. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67656. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67657. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67658. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67659. effect.setFloat('radialIntensity', 1);
  67660. effect.setFloat2('direction', 17, 17);
  67661. effect.setFloat2('centerPosition', 0.5, 0.5);
  67662. };
  67663. };
  67664. // highlights enhancing
  67665. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67666. var _this = this;
  67667. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67668. [], // samplers
  67669. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67670. this._highlightsPostProcess.onApply = function (effect) {
  67671. effect.setFloat('gain', _this._highlightsGain);
  67672. effect.setFloat('threshold', _this._highlightsThreshold);
  67673. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67674. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67675. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67676. };
  67677. };
  67678. // colors shifting and distortion
  67679. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67680. var _this = this;
  67681. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67682. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67683. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67684. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67685. this._depthOfFieldPostProcess.onApply = function (effect) {
  67686. effect.setTexture("depthSampler", _this._depthTexture);
  67687. effect.setTexture("grainSampler", _this._grainTexture);
  67688. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67689. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67690. effect.setFloat('grain_amount', _this._grainAmount);
  67691. effect.setBool('blur_noise', _this._blurNoise);
  67692. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67693. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67694. effect.setFloat('distortion', _this._distortion);
  67695. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67696. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67697. effect.setFloat('aperture', _this._dofAperture);
  67698. effect.setFloat('darken', _this._dofDarken);
  67699. effect.setFloat('edge_blur', _this._edgeBlur);
  67700. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67701. if (_this._scene.activeCamera) {
  67702. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67703. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67704. }
  67705. };
  67706. };
  67707. // creates a black and white random noise texture, 512x512
  67708. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67709. var size = 512;
  67710. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67711. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67712. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67713. var context = this._grainTexture.getContext();
  67714. var rand = function (min, max) {
  67715. return Math.random() * (max - min) + min;
  67716. };
  67717. var value;
  67718. for (var x = 0; x < size; x++) {
  67719. for (var y = 0; y < size; y++) {
  67720. value = Math.floor(rand(0.42, 0.58) * 255);
  67721. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67722. context.fillRect(x, y, 1, 1);
  67723. }
  67724. }
  67725. this._grainTexture.update(false);
  67726. };
  67727. return LensRenderingPipeline;
  67728. }(BABYLON.PostProcessRenderPipeline));
  67729. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67730. })(BABYLON || (BABYLON = {}));
  67731. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67732. var BABYLON;
  67733. (function (BABYLON) {
  67734. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67735. __extends(StandardRenderingPipeline, _super);
  67736. /**
  67737. * @constructor
  67738. * @param {string} name - The rendering pipeline name
  67739. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67740. * @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)
  67741. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67742. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67743. */
  67744. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67745. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67746. var _this = _super.call(this, scene.getEngine(), name) || this;
  67747. _this.downSampleX4PostProcess = null;
  67748. _this.brightPassPostProcess = null;
  67749. _this.blurHPostProcesses = [];
  67750. _this.blurVPostProcesses = [];
  67751. _this.textureAdderPostProcess = null;
  67752. _this.volumetricLightPostProcess = null;
  67753. _this.volumetricLightSmoothXPostProcess = null;
  67754. _this.volumetricLightSmoothYPostProcess = null;
  67755. _this.volumetricLightMergePostProces = null;
  67756. _this.volumetricLightFinalPostProcess = null;
  67757. _this.luminancePostProcess = null;
  67758. _this.luminanceDownSamplePostProcesses = [];
  67759. _this.hdrPostProcess = null;
  67760. _this.textureAdderFinalPostProcess = null;
  67761. _this.lensFlareFinalPostProcess = null;
  67762. _this.hdrFinalPostProcess = null;
  67763. _this.lensFlarePostProcess = null;
  67764. _this.lensFlareComposePostProcess = null;
  67765. _this.motionBlurPostProcess = null;
  67766. _this.depthOfFieldPostProcess = null;
  67767. // Values
  67768. _this.brightThreshold = 1.0;
  67769. _this.blurWidth = 512.0;
  67770. _this.horizontalBlur = false;
  67771. _this.exposure = 1.0;
  67772. _this.lensTexture = null;
  67773. _this.volumetricLightCoefficient = 0.2;
  67774. _this.volumetricLightPower = 4.0;
  67775. _this.volumetricLightBlurScale = 64.0;
  67776. _this.sourceLight = null;
  67777. _this.hdrMinimumLuminance = 1.0;
  67778. _this.hdrDecreaseRate = 0.5;
  67779. _this.hdrIncreaseRate = 0.5;
  67780. _this.lensColorTexture = null;
  67781. _this.lensFlareStrength = 20.0;
  67782. _this.lensFlareGhostDispersal = 1.4;
  67783. _this.lensFlareHaloWidth = 0.7;
  67784. _this.lensFlareDistortionStrength = 16.0;
  67785. _this.lensStarTexture = null;
  67786. _this.lensFlareDirtTexture = null;
  67787. _this.depthOfFieldDistance = 10.0;
  67788. _this.depthOfFieldBlurWidth = 64.0;
  67789. _this.motionStrength = 1.0;
  67790. // IAnimatable
  67791. _this.animations = [];
  67792. _this._currentDepthOfFieldSource = null;
  67793. _this._hdrCurrentLuminance = 1.0;
  67794. // Getters and setters
  67795. _this._bloomEnabled = true;
  67796. _this._depthOfFieldEnabled = false;
  67797. _this._vlsEnabled = false;
  67798. _this._lensFlareEnabled = false;
  67799. _this._hdrEnabled = false;
  67800. _this._motionBlurEnabled = false;
  67801. _this._motionBlurSamples = 64.0;
  67802. _this._volumetricLightStepsCount = 50.0;
  67803. _this._cameras = cameras || [];
  67804. // Initialize
  67805. _this._scene = scene;
  67806. _this._basePostProcess = originalPostProcess;
  67807. _this._ratio = ratio;
  67808. // Misc
  67809. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67810. // Finish
  67811. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67812. _this._buildPipeline();
  67813. return _this;
  67814. }
  67815. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67816. get: function () {
  67817. return this._bloomEnabled;
  67818. },
  67819. set: function (enabled) {
  67820. if (this._bloomEnabled === enabled) {
  67821. return;
  67822. }
  67823. this._bloomEnabled = enabled;
  67824. this._buildPipeline();
  67825. },
  67826. enumerable: true,
  67827. configurable: true
  67828. });
  67829. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67830. get: function () {
  67831. return this._depthOfFieldEnabled;
  67832. },
  67833. set: function (enabled) {
  67834. if (this._depthOfFieldEnabled === enabled) {
  67835. return;
  67836. }
  67837. this._depthOfFieldEnabled = enabled;
  67838. this._buildPipeline();
  67839. },
  67840. enumerable: true,
  67841. configurable: true
  67842. });
  67843. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67844. get: function () {
  67845. return this._lensFlareEnabled;
  67846. },
  67847. set: function (enabled) {
  67848. if (this._lensFlareEnabled === enabled) {
  67849. return;
  67850. }
  67851. this._lensFlareEnabled = enabled;
  67852. this._buildPipeline();
  67853. },
  67854. enumerable: true,
  67855. configurable: true
  67856. });
  67857. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67858. get: function () {
  67859. return this._hdrEnabled;
  67860. },
  67861. set: function (enabled) {
  67862. if (this._hdrEnabled === enabled) {
  67863. return;
  67864. }
  67865. this._hdrEnabled = enabled;
  67866. this._buildPipeline();
  67867. },
  67868. enumerable: true,
  67869. configurable: true
  67870. });
  67871. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67872. get: function () {
  67873. return this._vlsEnabled;
  67874. },
  67875. set: function (enabled) {
  67876. if (this._vlsEnabled === enabled) {
  67877. return;
  67878. }
  67879. if (enabled) {
  67880. var geometry = this._scene.enableGeometryBufferRenderer();
  67881. if (!geometry) {
  67882. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67883. return;
  67884. }
  67885. }
  67886. this._vlsEnabled = enabled;
  67887. this._buildPipeline();
  67888. },
  67889. enumerable: true,
  67890. configurable: true
  67891. });
  67892. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67893. get: function () {
  67894. return this._motionBlurEnabled;
  67895. },
  67896. set: function (enabled) {
  67897. if (this._motionBlurEnabled === enabled) {
  67898. return;
  67899. }
  67900. this._motionBlurEnabled = enabled;
  67901. this._buildPipeline();
  67902. },
  67903. enumerable: true,
  67904. configurable: true
  67905. });
  67906. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67907. get: function () {
  67908. return this._volumetricLightStepsCount;
  67909. },
  67910. set: function (count) {
  67911. if (this.volumetricLightPostProcess) {
  67912. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67913. }
  67914. this._volumetricLightStepsCount = count;
  67915. },
  67916. enumerable: true,
  67917. configurable: true
  67918. });
  67919. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67920. get: function () {
  67921. return this._motionBlurSamples;
  67922. },
  67923. set: function (samples) {
  67924. if (this.motionBlurPostProcess) {
  67925. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67926. }
  67927. this._motionBlurSamples = samples;
  67928. },
  67929. enumerable: true,
  67930. configurable: true
  67931. });
  67932. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67933. var _this = this;
  67934. var ratio = this._ratio;
  67935. var scene = this._scene;
  67936. this._disposePostProcesses();
  67937. this._reset();
  67938. // Create pass post-process
  67939. if (!this._basePostProcess) {
  67940. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67941. this.originalPostProcess.onApply = function (effect) {
  67942. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67943. };
  67944. }
  67945. else {
  67946. this.originalPostProcess = this._basePostProcess;
  67947. }
  67948. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67949. this._currentDepthOfFieldSource = this.originalPostProcess;
  67950. if (this._vlsEnabled) {
  67951. // Create volumetric light
  67952. this._createVolumetricLightPostProcess(scene, ratio);
  67953. // Create volumetric light final post-process
  67954. 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);
  67955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67956. }
  67957. if (this._bloomEnabled) {
  67958. // Create down sample X4 post-process
  67959. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67960. // Create bright pass post-process
  67961. this._createBrightPassPostProcess(scene, ratio / 2);
  67962. // Create gaussian blur post-processes (down sampling blurs)
  67963. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67964. // Create texture adder post-process
  67965. this._createTextureAdderPostProcess(scene, ratio);
  67966. // Create depth-of-field source post-process
  67967. 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);
  67968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67969. }
  67970. if (this._lensFlareEnabled) {
  67971. // Create lens flare post-process
  67972. this._createLensFlarePostProcess(scene, ratio);
  67973. // Create depth-of-field source post-process post lens-flare and disable it now
  67974. 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);
  67975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67976. }
  67977. if (this._hdrEnabled) {
  67978. // Create luminance
  67979. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67980. // Create HDR
  67981. this._createHdrPostProcess(scene, ratio);
  67982. // Create depth-of-field source post-process post hdr and disable it now
  67983. 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);
  67984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67985. }
  67986. if (this._depthOfFieldEnabled) {
  67987. // Create gaussian blur used by depth-of-field
  67988. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67989. // Create depth-of-field post-process
  67990. this._createDepthOfFieldPostProcess(scene, ratio);
  67991. }
  67992. if (this._motionBlurEnabled) {
  67993. // Create motion blur post-process
  67994. this._createMotionBlurPostProcess(scene, ratio);
  67995. }
  67996. if (this._cameras !== null) {
  67997. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67998. }
  67999. };
  68000. // Down Sample X4 Post-Processs
  68001. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68002. var _this = this;
  68003. var downSampleX4Offsets = new Array(32);
  68004. 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);
  68005. this.downSampleX4PostProcess.onApply = function (effect) {
  68006. var id = 0;
  68007. var width = _this.downSampleX4PostProcess.width;
  68008. var height = _this.downSampleX4PostProcess.height;
  68009. for (var i = -2; i < 2; i++) {
  68010. for (var j = -2; j < 2; j++) {
  68011. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68012. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68013. id += 2;
  68014. }
  68015. }
  68016. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68017. };
  68018. // Add to pipeline
  68019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68020. };
  68021. // Brightpass Post-Process
  68022. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68023. var _this = this;
  68024. var brightOffsets = new Array(8);
  68025. 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);
  68026. this.brightPassPostProcess.onApply = function (effect) {
  68027. var sU = (1.0 / _this.brightPassPostProcess.width);
  68028. var sV = (1.0 / _this.brightPassPostProcess.height);
  68029. brightOffsets[0] = -0.5 * sU;
  68030. brightOffsets[1] = 0.5 * sV;
  68031. brightOffsets[2] = 0.5 * sU;
  68032. brightOffsets[3] = 0.5 * sV;
  68033. brightOffsets[4] = -0.5 * sU;
  68034. brightOffsets[5] = -0.5 * sV;
  68035. brightOffsets[6] = 0.5 * sU;
  68036. brightOffsets[7] = -0.5 * sV;
  68037. effect.setArray2("dsOffsets", brightOffsets);
  68038. effect.setFloat("brightThreshold", _this.brightThreshold);
  68039. };
  68040. // Add to pipeline
  68041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68042. };
  68043. // Create blur H&V post-processes
  68044. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68045. var _this = this;
  68046. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68047. var engine = scene.getEngine();
  68048. 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);
  68049. 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);
  68050. blurX.onActivateObservable.add(function () {
  68051. var dw = blurX.width / engine.getRenderWidth();
  68052. blurX.kernel = _this[blurWidthKey] * dw;
  68053. });
  68054. blurY.onActivateObservable.add(function () {
  68055. var dw = blurY.height / engine.getRenderHeight();
  68056. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68057. });
  68058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68059. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68060. this.blurHPostProcesses.push(blurX);
  68061. this.blurVPostProcesses.push(blurY);
  68062. };
  68063. // Create texture adder post-process
  68064. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68065. var _this = this;
  68066. 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);
  68067. this.textureAdderPostProcess.onApply = function (effect) {
  68068. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68069. effect.setTexture("lensSampler", _this.lensTexture);
  68070. effect.setFloat("exposure", _this.exposure);
  68071. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68072. };
  68073. // Add to pipeline
  68074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68075. };
  68076. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68077. var _this = this;
  68078. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68079. geometryRenderer.enablePosition = true;
  68080. var geometry = geometryRenderer.getGBuffer();
  68081. // Base post-process
  68082. 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));
  68083. var depthValues = BABYLON.Vector2.Zero();
  68084. this.volumetricLightPostProcess.onApply = function (effect) {
  68085. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68086. var generator = _this.sourceLight.getShadowGenerator();
  68087. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68088. effect.setTexture("positionSampler", geometry.textures[2]);
  68089. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68090. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68091. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68092. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68093. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68094. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68095. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68096. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68097. effect.setVector2("depthValues", depthValues);
  68098. }
  68099. };
  68100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68101. // Smooth
  68102. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68103. // Merge
  68104. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68105. this.volumetricLightMergePostProces.onApply = function (effect) {
  68106. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68107. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68108. };
  68109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68110. };
  68111. // Create luminance
  68112. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68113. var _this = this;
  68114. // Create luminance
  68115. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68116. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68117. var offsets = [];
  68118. this.luminancePostProcess.onApply = function (effect) {
  68119. var sU = (1.0 / _this.luminancePostProcess.width);
  68120. var sV = (1.0 / _this.luminancePostProcess.height);
  68121. offsets[0] = -0.5 * sU;
  68122. offsets[1] = 0.5 * sV;
  68123. offsets[2] = 0.5 * sU;
  68124. offsets[3] = 0.5 * sV;
  68125. offsets[4] = -0.5 * sU;
  68126. offsets[5] = -0.5 * sV;
  68127. offsets[6] = 0.5 * sU;
  68128. offsets[7] = -0.5 * sV;
  68129. effect.setArray2("lumOffsets", offsets);
  68130. };
  68131. // Add to pipeline
  68132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68133. // Create down sample luminance
  68134. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68135. var size = Math.pow(3, i);
  68136. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68137. if (i === 0) {
  68138. defines += "#define FINAL_DOWN_SAMPLER";
  68139. }
  68140. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68141. this.luminanceDownSamplePostProcesses.push(postProcess);
  68142. }
  68143. // Create callbacks and add effects
  68144. var lastLuminance = this.luminancePostProcess;
  68145. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68146. var downSampleOffsets = new Array(18);
  68147. pp.onApply = function (effect) {
  68148. if (!lastLuminance) {
  68149. return;
  68150. }
  68151. var id = 0;
  68152. for (var x = -1; x < 2; x++) {
  68153. for (var y = -1; y < 2; y++) {
  68154. downSampleOffsets[id] = x / lastLuminance.width;
  68155. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68156. id += 2;
  68157. }
  68158. }
  68159. effect.setArray2("dsOffsets", downSampleOffsets);
  68160. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68161. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68162. lastLuminance = _this.luminancePostProcess;
  68163. }
  68164. else {
  68165. lastLuminance = pp;
  68166. }
  68167. };
  68168. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68169. pp.onAfterRender = function (effect) {
  68170. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68171. 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);
  68172. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68173. };
  68174. }
  68175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68176. });
  68177. };
  68178. // Create HDR post-process
  68179. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68180. var _this = this;
  68181. 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);
  68182. var outputLiminance = 1;
  68183. var time = 0;
  68184. var lastTime = 0;
  68185. this.hdrPostProcess.onApply = function (effect) {
  68186. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68187. time += scene.getEngine().getDeltaTime();
  68188. if (outputLiminance < 0) {
  68189. outputLiminance = _this._hdrCurrentLuminance;
  68190. }
  68191. else {
  68192. var dt = (lastTime - time) / 1000.0;
  68193. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68194. outputLiminance += _this.hdrDecreaseRate * dt;
  68195. }
  68196. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68197. outputLiminance -= _this.hdrIncreaseRate * dt;
  68198. }
  68199. else {
  68200. outputLiminance = _this._hdrCurrentLuminance;
  68201. }
  68202. }
  68203. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68204. effect.setFloat("averageLuminance", outputLiminance);
  68205. lastTime = time;
  68206. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68207. };
  68208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68209. };
  68210. // Create lens flare post-process
  68211. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68212. var _this = this;
  68213. 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);
  68214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68215. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68216. 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);
  68217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68218. var resolution = new BABYLON.Vector2(0, 0);
  68219. // Lens flare
  68220. this.lensFlarePostProcess.onApply = function (effect) {
  68221. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68222. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68223. effect.setFloat("strength", _this.lensFlareStrength);
  68224. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68225. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68226. // Shift
  68227. resolution.x = _this.lensFlarePostProcess.width;
  68228. resolution.y = _this.lensFlarePostProcess.height;
  68229. effect.setVector2("resolution", resolution);
  68230. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68231. };
  68232. // Compose
  68233. 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);
  68234. 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);
  68235. this.lensFlareComposePostProcess.onApply = function (effect) {
  68236. if (!_this._scene.activeCamera) {
  68237. return;
  68238. }
  68239. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68240. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68241. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68242. // Lens start rotation matrix
  68243. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68244. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68245. 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));
  68246. camRot *= 4.0;
  68247. 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);
  68248. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68249. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68250. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68251. };
  68252. };
  68253. // Create depth-of-field post-process
  68254. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68255. var _this = this;
  68256. 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);
  68257. this.depthOfFieldPostProcess.onApply = function (effect) {
  68258. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68259. effect.setTexture("depthSampler", _this._getDepthTexture());
  68260. effect.setFloat("distance", _this.depthOfFieldDistance);
  68261. };
  68262. // Add to pipeline
  68263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68264. };
  68265. // Create motion blur post-process
  68266. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68267. var _this = this;
  68268. 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);
  68269. var motionScale = 0;
  68270. var prevViewProjection = BABYLON.Matrix.Identity();
  68271. var invViewProjection = BABYLON.Matrix.Identity();
  68272. var viewProjection = BABYLON.Matrix.Identity();
  68273. var screenSize = BABYLON.Vector2.Zero();
  68274. this.motionBlurPostProcess.onApply = function (effect) {
  68275. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68276. viewProjection.invertToRef(invViewProjection);
  68277. effect.setMatrix("inverseViewProjection", invViewProjection);
  68278. effect.setMatrix("prevViewProjection", prevViewProjection);
  68279. prevViewProjection = viewProjection;
  68280. screenSize.x = _this.motionBlurPostProcess.width;
  68281. screenSize.y = _this.motionBlurPostProcess.height;
  68282. effect.setVector2("screenSize", screenSize);
  68283. motionScale = scene.getEngine().getFps() / 60.0;
  68284. effect.setFloat("motionScale", motionScale);
  68285. effect.setFloat("motionStrength", _this.motionStrength);
  68286. effect.setTexture("depthSampler", _this._getDepthTexture());
  68287. };
  68288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68289. };
  68290. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68291. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68292. var renderer = this._scene.enableGeometryBufferRenderer();
  68293. return renderer.getGBuffer().textures[0];
  68294. }
  68295. return this._scene.enableDepthRenderer().getDepthMap();
  68296. };
  68297. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68298. for (var i = 0; i < this._cameras.length; i++) {
  68299. var camera = this._cameras[i];
  68300. if (this.originalPostProcess) {
  68301. this.originalPostProcess.dispose(camera);
  68302. }
  68303. if (this.downSampleX4PostProcess) {
  68304. this.downSampleX4PostProcess.dispose(camera);
  68305. }
  68306. if (this.brightPassPostProcess) {
  68307. this.brightPassPostProcess.dispose(camera);
  68308. }
  68309. if (this.textureAdderPostProcess) {
  68310. this.textureAdderPostProcess.dispose(camera);
  68311. }
  68312. if (this.textureAdderFinalPostProcess) {
  68313. this.textureAdderFinalPostProcess.dispose(camera);
  68314. }
  68315. if (this.volumetricLightPostProcess) {
  68316. this.volumetricLightPostProcess.dispose(camera);
  68317. }
  68318. if (this.volumetricLightSmoothXPostProcess) {
  68319. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68320. }
  68321. if (this.volumetricLightSmoothYPostProcess) {
  68322. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68323. }
  68324. if (this.volumetricLightMergePostProces) {
  68325. this.volumetricLightMergePostProces.dispose(camera);
  68326. }
  68327. if (this.volumetricLightFinalPostProcess) {
  68328. this.volumetricLightFinalPostProcess.dispose(camera);
  68329. }
  68330. if (this.lensFlarePostProcess) {
  68331. this.lensFlarePostProcess.dispose(camera);
  68332. }
  68333. if (this.lensFlareComposePostProcess) {
  68334. this.lensFlareComposePostProcess.dispose(camera);
  68335. }
  68336. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68337. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68338. }
  68339. if (this.luminancePostProcess) {
  68340. this.luminancePostProcess.dispose(camera);
  68341. }
  68342. if (this.hdrPostProcess) {
  68343. this.hdrPostProcess.dispose(camera);
  68344. }
  68345. if (this.hdrFinalPostProcess) {
  68346. this.hdrFinalPostProcess.dispose(camera);
  68347. }
  68348. if (this.depthOfFieldPostProcess) {
  68349. this.depthOfFieldPostProcess.dispose(camera);
  68350. }
  68351. if (this.motionBlurPostProcess) {
  68352. this.motionBlurPostProcess.dispose(camera);
  68353. }
  68354. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68355. this.blurHPostProcesses[j].dispose(camera);
  68356. }
  68357. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68358. this.blurVPostProcesses[j].dispose(camera);
  68359. }
  68360. }
  68361. this.originalPostProcess = null;
  68362. this.downSampleX4PostProcess = null;
  68363. this.brightPassPostProcess = null;
  68364. this.textureAdderPostProcess = null;
  68365. this.textureAdderFinalPostProcess = null;
  68366. this.volumetricLightPostProcess = null;
  68367. this.volumetricLightSmoothXPostProcess = null;
  68368. this.volumetricLightSmoothYPostProcess = null;
  68369. this.volumetricLightMergePostProces = null;
  68370. this.volumetricLightFinalPostProcess = null;
  68371. this.lensFlarePostProcess = null;
  68372. this.lensFlareComposePostProcess = null;
  68373. this.luminancePostProcess = null;
  68374. this.hdrPostProcess = null;
  68375. this.hdrFinalPostProcess = null;
  68376. this.depthOfFieldPostProcess = null;
  68377. this.motionBlurPostProcess = null;
  68378. this.luminanceDownSamplePostProcesses = [];
  68379. this.blurHPostProcesses = [];
  68380. this.blurVPostProcesses = [];
  68381. };
  68382. // Dispose
  68383. StandardRenderingPipeline.prototype.dispose = function () {
  68384. this._disposePostProcesses();
  68385. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68386. _super.prototype.dispose.call(this);
  68387. };
  68388. // Serialize rendering pipeline
  68389. StandardRenderingPipeline.prototype.serialize = function () {
  68390. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68391. serializationObject.customType = "StandardRenderingPipeline";
  68392. return serializationObject;
  68393. };
  68394. /**
  68395. * Static members
  68396. */
  68397. // Parse serialized pipeline
  68398. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68399. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68400. };
  68401. // Luminance steps
  68402. StandardRenderingPipeline.LuminanceSteps = 6;
  68403. __decorate([
  68404. BABYLON.serialize()
  68405. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68406. __decorate([
  68407. BABYLON.serialize()
  68408. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68409. __decorate([
  68410. BABYLON.serialize()
  68411. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68412. __decorate([
  68413. BABYLON.serialize()
  68414. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68415. __decorate([
  68416. BABYLON.serializeAsTexture("lensTexture")
  68417. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68418. __decorate([
  68419. BABYLON.serialize()
  68420. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68421. __decorate([
  68422. BABYLON.serialize()
  68423. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68424. __decorate([
  68425. BABYLON.serialize()
  68426. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68427. __decorate([
  68428. BABYLON.serialize()
  68429. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68430. __decorate([
  68431. BABYLON.serialize()
  68432. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68433. __decorate([
  68434. BABYLON.serialize()
  68435. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68436. __decorate([
  68437. BABYLON.serializeAsTexture("lensColorTexture")
  68438. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68439. __decorate([
  68440. BABYLON.serialize()
  68441. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68442. __decorate([
  68443. BABYLON.serialize()
  68444. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68445. __decorate([
  68446. BABYLON.serialize()
  68447. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68448. __decorate([
  68449. BABYLON.serialize()
  68450. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68451. __decorate([
  68452. BABYLON.serializeAsTexture("lensStarTexture")
  68453. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68454. __decorate([
  68455. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68456. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68457. __decorate([
  68458. BABYLON.serialize()
  68459. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68460. __decorate([
  68461. BABYLON.serialize()
  68462. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68463. __decorate([
  68464. BABYLON.serialize()
  68465. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68466. __decorate([
  68467. BABYLON.serialize()
  68468. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68469. __decorate([
  68470. BABYLON.serialize()
  68471. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68472. __decorate([
  68473. BABYLON.serialize()
  68474. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68475. __decorate([
  68476. BABYLON.serialize()
  68477. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68478. __decorate([
  68479. BABYLON.serialize()
  68480. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68481. __decorate([
  68482. BABYLON.serialize()
  68483. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68484. __decorate([
  68485. BABYLON.serialize()
  68486. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68487. __decorate([
  68488. BABYLON.serialize()
  68489. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68490. __decorate([
  68491. BABYLON.serialize()
  68492. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68493. return StandardRenderingPipeline;
  68494. }(BABYLON.PostProcessRenderPipeline));
  68495. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68496. })(BABYLON || (BABYLON = {}));
  68497. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68498. var BABYLON;
  68499. (function (BABYLON) {
  68500. var FxaaPostProcess = /** @class */ (function (_super) {
  68501. __extends(FxaaPostProcess, _super);
  68502. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68503. if (camera === void 0) { camera = null; }
  68504. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68505. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68506. _this.onApplyObservable.add(function (effect) {
  68507. var texelSize = _this.texelSize;
  68508. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68509. });
  68510. return _this;
  68511. }
  68512. return FxaaPostProcess;
  68513. }(BABYLON.PostProcess));
  68514. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68515. })(BABYLON || (BABYLON = {}));
  68516. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68517. var BABYLON;
  68518. (function (BABYLON) {
  68519. /**
  68520. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68521. */
  68522. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68523. __extends(ChromaticAberrationPostProcess, _super);
  68524. /**
  68525. * Creates a new instance of @see ChromaticAberrationPostProcess
  68526. * @param name The name of the effect.
  68527. * @param screenWidth The width of the screen to apply the effect on.
  68528. * @param screenHeight The height of the screen to apply the effect on.
  68529. * @param options The required width/height ratio to downsize to before computing the render pass.
  68530. * @param camera The camera to apply the render pass to.
  68531. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68532. * @param engine The engine which the post process will be applied. (default: current engine)
  68533. * @param reusable If the post process can be reused on the same frame. (default: false)
  68534. * @param textureType Type of textures used when performing the post process. (default: 0)
  68535. */
  68536. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  68537. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68538. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68539. /**
  68540. * The amount of seperation of rgb channels (default: 0)
  68541. */
  68542. _this.aberrationAmount = 0;
  68543. /**
  68544. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68545. */
  68546. _this.radialIntensity = 0;
  68547. /**
  68548. * 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))
  68549. */
  68550. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68551. /**
  68552. * 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))
  68553. */
  68554. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68555. _this.onApplyObservable.add(function (effect) {
  68556. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68557. effect.setFloat('screen_width', screenWidth);
  68558. effect.setFloat('screen_height', screenHeight);
  68559. effect.setFloat('radialIntensity', _this.radialIntensity);
  68560. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68561. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68562. });
  68563. return _this;
  68564. }
  68565. return ChromaticAberrationPostProcess;
  68566. }(BABYLON.PostProcess));
  68567. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68568. })(BABYLON || (BABYLON = {}));
  68569. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68570. var BABYLON;
  68571. (function (BABYLON) {
  68572. /**
  68573. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68574. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68575. */
  68576. var SharpenPostProcess = /** @class */ (function (_super) {
  68577. __extends(SharpenPostProcess, _super);
  68578. /**
  68579. * Creates a new instance of @see ConvolutionPostProcess
  68580. * @param name The name of the effect.
  68581. * @param options The required width/height ratio to downsize to before computing the render pass.
  68582. * @param camera The camera to apply the render pass to.
  68583. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68584. * @param engine The engine which the post process will be applied. (default: current engine)
  68585. * @param reusable If the post process can be reused on the same frame. (default: false)
  68586. * @param textureType Type of textures used when performing the post process. (default: 0)
  68587. */
  68588. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68589. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68590. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68591. /**
  68592. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68593. */
  68594. _this.colorAmount = 1.0;
  68595. /**
  68596. * How much sharpness should be applied (default: 0.3)
  68597. */
  68598. _this.edgeAmount = 0.3;
  68599. _this.onApply = function (effect) {
  68600. effect.setFloat2("screenSize", _this.width, _this.height);
  68601. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68602. };
  68603. return _this;
  68604. }
  68605. return SharpenPostProcess;
  68606. }(BABYLON.PostProcess));
  68607. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68608. })(BABYLON || (BABYLON = {}));
  68609. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68610. var BABYLON;
  68611. (function (BABYLON) {
  68612. /**
  68613. * The Blur Post Process which blurs an image based on a kernel and direction.
  68614. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68615. */
  68616. var BlurPostProcess = /** @class */ (function (_super) {
  68617. __extends(BlurPostProcess, _super);
  68618. /**
  68619. * Creates a new instance of @see BlurPostProcess
  68620. * @param name The name of the effect.
  68621. * @param direction The direction in which to blur the image.
  68622. * @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.
  68623. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68624. * @param camera The camera to apply the render pass to.
  68625. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68626. * @param engine The engine which the post process will be applied. (default: current engine)
  68627. * @param reusable If the post process can be reused on the same frame. (default: false)
  68628. * @param textureType Type of textures used when performing the post process. (default: 0)
  68629. */
  68630. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68632. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68633. if (defines === void 0) { defines = ""; }
  68634. 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;
  68635. _this.direction = direction;
  68636. _this._packedFloat = false;
  68637. _this._staticDefines = "";
  68638. _this._staticDefines = defines;
  68639. _this.onApplyObservable.add(function (effect) {
  68640. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68641. });
  68642. _this.kernel = kernel;
  68643. return _this;
  68644. }
  68645. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68646. /**
  68647. * Gets the length in pixels of the blur sample region
  68648. */
  68649. get: function () {
  68650. return this._idealKernel;
  68651. },
  68652. /**
  68653. * Sets the length in pixels of the blur sample region
  68654. */
  68655. set: function (v) {
  68656. if (this._idealKernel === v) {
  68657. return;
  68658. }
  68659. v = Math.max(v, 1);
  68660. this._idealKernel = v;
  68661. this._kernel = this._nearestBestKernel(v);
  68662. this._updateParameters();
  68663. },
  68664. enumerable: true,
  68665. configurable: true
  68666. });
  68667. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68668. /**
  68669. * Gets wether or not the blur is unpacking/repacking floats
  68670. */
  68671. get: function () {
  68672. return this._packedFloat;
  68673. },
  68674. /**
  68675. * Sets wether or not the blur needs to unpack/repack floats
  68676. */
  68677. set: function (v) {
  68678. if (this._packedFloat === v) {
  68679. return;
  68680. }
  68681. this._packedFloat = v;
  68682. this._updateParameters();
  68683. },
  68684. enumerable: true,
  68685. configurable: true
  68686. });
  68687. BlurPostProcess.prototype._updateParameters = function () {
  68688. // Generate sampling offsets and weights
  68689. var N = this._kernel;
  68690. var centerIndex = (N - 1) / 2;
  68691. // Generate Gaussian sampling weights over kernel
  68692. var offsets = [];
  68693. var weights = [];
  68694. var totalWeight = 0;
  68695. for (var i = 0; i < N; i++) {
  68696. var u = i / (N - 1);
  68697. var w = this._gaussianWeight(u * 2.0 - 1);
  68698. offsets[i] = (i - centerIndex);
  68699. weights[i] = w;
  68700. totalWeight += w;
  68701. }
  68702. // Normalize weights
  68703. for (var i = 0; i < weights.length; i++) {
  68704. weights[i] /= totalWeight;
  68705. }
  68706. // Optimize: combine samples to take advantage of hardware linear sampling
  68707. // Walk from left to center, combining pairs (symmetrically)
  68708. var linearSamplingWeights = [];
  68709. var linearSamplingOffsets = [];
  68710. var linearSamplingMap = [];
  68711. for (var i = 0; i <= centerIndex; i += 2) {
  68712. var j = Math.min(i + 1, Math.floor(centerIndex));
  68713. var singleCenterSample = i === j;
  68714. if (singleCenterSample) {
  68715. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68716. }
  68717. else {
  68718. var sharedCell = j === centerIndex;
  68719. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68720. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68721. if (offsetLinear === 0) {
  68722. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68723. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68724. }
  68725. else {
  68726. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68727. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68728. }
  68729. }
  68730. }
  68731. for (var i = 0; i < linearSamplingMap.length; i++) {
  68732. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68733. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68734. }
  68735. // Replace with optimized
  68736. offsets = linearSamplingOffsets;
  68737. weights = linearSamplingWeights;
  68738. // Generate shaders
  68739. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68740. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68741. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68742. var defines = "";
  68743. defines += this._staticDefines;
  68744. for (var i = 0; i < varyingCount; i++) {
  68745. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68746. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68747. }
  68748. var depCount = 0;
  68749. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68750. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68751. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68752. depCount++;
  68753. }
  68754. if (this.packedFloat) {
  68755. defines += "#define PACKEDFLOAT 1";
  68756. }
  68757. this.updateEffect(defines, null, null, {
  68758. varyingCount: varyingCount,
  68759. depCount: depCount
  68760. });
  68761. };
  68762. /**
  68763. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68764. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68765. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68766. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68767. * The gaps between physical kernels are compensated for in the weighting of the samples
  68768. * @param idealKernel Ideal blur kernel.
  68769. * @return Nearest best kernel.
  68770. */
  68771. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68772. var v = Math.round(idealKernel);
  68773. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68774. var k = _a[_i];
  68775. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68776. return Math.max(k, 3);
  68777. }
  68778. }
  68779. return Math.max(v, 3);
  68780. };
  68781. /**
  68782. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68783. * @param x The point on the Gaussian distribution to sample.
  68784. * @return the value of the Gaussian function at x.
  68785. */
  68786. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68787. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68788. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68789. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68790. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68791. // truncated at around 1.3% of peak strength.
  68792. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68793. var sigma = (1 / 3);
  68794. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68795. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68796. var weight = (1.0 / denominator) * Math.exp(exponent);
  68797. return weight;
  68798. };
  68799. /**
  68800. * Generates a string that can be used as a floating point number in GLSL.
  68801. * @param x Value to print.
  68802. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68803. * @return GLSL float string.
  68804. */
  68805. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68806. if (decimalFigures === void 0) { decimalFigures = 8; }
  68807. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68808. };
  68809. return BlurPostProcess;
  68810. }(BABYLON.PostProcess));
  68811. BABYLON.BlurPostProcess = BlurPostProcess;
  68812. })(BABYLON || (BABYLON = {}));
  68813. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68814. var BABYLON;
  68815. (function (BABYLON) {
  68816. /**
  68817. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68818. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68819. * based on samples that have a large difference in distance than the center pixel.
  68820. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68821. */
  68822. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68823. __extends(DepthOfFieldBlurPostProcess, _super);
  68824. /**
  68825. * Creates a new instance of @see CircleOfConfusionPostProcess
  68826. * @param name The name of the effect.
  68827. * @param scene The scene the effect belongs to.
  68828. * @param direction The direction the blur should be applied.
  68829. * @param kernel The size of the kernel used to blur.
  68830. * @param options The required width/height ratio to downsize to before computing the render pass.
  68831. * @param camera The camera to apply the render pass to.
  68832. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68833. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68834. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68835. * @param engine The engine which the post process will be applied. (default: current engine)
  68836. * @param reusable If the post process can be reused on the same frame. (default: false)
  68837. * @param textureType Type of textures used when performing the post process. (default: 0)
  68838. */
  68839. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  68840. if (imageToBlur === void 0) { imageToBlur = null; }
  68841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68843. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n") || this;
  68844. _this.direction = direction;
  68845. _this.onApplyObservable.add(function (effect) {
  68846. if (imageToBlur != null) {
  68847. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68848. }
  68849. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68850. if (scene.activeCamera) {
  68851. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68852. }
  68853. });
  68854. return _this;
  68855. }
  68856. return DepthOfFieldBlurPostProcess;
  68857. }(BABYLON.BlurPostProcess));
  68858. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68859. })(BABYLON || (BABYLON = {}));
  68860. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68861. var BABYLON;
  68862. (function (BABYLON) {
  68863. /**
  68864. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68865. */
  68866. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68867. __extends(DepthOfFieldMergePostProcess, _super);
  68868. /**
  68869. * Creates a new instance of @see CircleOfConfusionPostProcess
  68870. * @param name The name of the effect.
  68871. * @param original The non-blurred image to be modified
  68872. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68873. * @param blurSteps Incrimental bluring post processes.
  68874. * @param options The required width/height ratio to downsize to before computing the render pass.
  68875. * @param camera The camera to apply the render pass to.
  68876. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68877. * @param engine The engine which the post process will be applied. (default: current engine)
  68878. * @param reusable If the post process can be reused on the same frame. (default: false)
  68879. * @param textureType Type of textures used when performing the post process. (default: 0)
  68880. */
  68881. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68882. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68883. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68884. _this.onApplyObservable.add(function (effect) {
  68885. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68886. effect.setTextureFromPostProcess("originalSampler", original);
  68887. blurSteps.forEach(function (step, index) {
  68888. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68889. });
  68890. });
  68891. return _this;
  68892. }
  68893. return DepthOfFieldMergePostProcess;
  68894. }(BABYLON.PostProcess));
  68895. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68896. })(BABYLON || (BABYLON = {}));
  68897. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68898. var BABYLON;
  68899. (function (BABYLON) {
  68900. /**
  68901. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68902. */
  68903. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68904. __extends(CircleOfConfusionPostProcess, _super);
  68905. /**
  68906. * Creates a new instance of @see CircleOfConfusionPostProcess
  68907. * @param name The name of the effect.
  68908. * @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.
  68909. * @param options The required width/height ratio to downsize to before computing the render pass.
  68910. * @param camera The camera to apply the render pass to.
  68911. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68912. * @param engine The engine which the post process will be applied. (default: current engine)
  68913. * @param reusable If the post process can be reused on the same frame. (default: false)
  68914. * @param textureType Type of textures used when performing the post process. (default: 0)
  68915. */
  68916. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68918. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68919. /**
  68920. * 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.
  68921. */
  68922. _this.lensSize = 50;
  68923. /**
  68924. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68925. */
  68926. _this.fStop = 1.4;
  68927. /**
  68928. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68929. */
  68930. _this.focusDistance = 2000;
  68931. /**
  68932. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68933. */
  68934. _this.focalLength = 50;
  68935. _this._depthTexture = null;
  68936. _this._depthTexture = depthTexture;
  68937. _this.onApplyObservable.add(function (effect) {
  68938. if (!_this._depthTexture) {
  68939. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68940. return;
  68941. }
  68942. effect.setTexture("depthSampler", _this._depthTexture);
  68943. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68944. var aperture = _this.lensSize / _this.fStop;
  68945. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68946. effect.setFloat('focusDistance', _this.focusDistance);
  68947. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68948. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68949. });
  68950. return _this;
  68951. }
  68952. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68953. /**
  68954. * 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.
  68955. */
  68956. set: function (value) {
  68957. this._depthTexture = value;
  68958. },
  68959. enumerable: true,
  68960. configurable: true
  68961. });
  68962. return CircleOfConfusionPostProcess;
  68963. }(BABYLON.PostProcess));
  68964. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68965. })(BABYLON || (BABYLON = {}));
  68966. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68967. var BABYLON;
  68968. (function (BABYLON) {
  68969. /**
  68970. * Specifies the level of max blur that should be applied when using the depth of field effect
  68971. */
  68972. var DepthOfFieldEffectBlurLevel;
  68973. (function (DepthOfFieldEffectBlurLevel) {
  68974. /**
  68975. * Subtle blur
  68976. */
  68977. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68978. /**
  68979. * Medium blur
  68980. */
  68981. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68982. /**
  68983. * Large blur
  68984. */
  68985. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68986. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68987. ;
  68988. /**
  68989. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68990. */
  68991. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68992. __extends(DepthOfFieldEffect, _super);
  68993. /**
  68994. * Creates a new instance of @see DepthOfFieldEffect
  68995. * @param scene The scene the effect belongs to.
  68996. * @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.
  68997. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68998. */
  68999. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  69000. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69001. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69002. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69003. return _this._effects;
  69004. }, true) || this;
  69005. _this._effects = [];
  69006. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69007. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  69008. // Capture circle of confusion texture
  69009. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  69010. _this._depthOfFieldPass.autoClear = false;
  69011. // 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)
  69012. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69013. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69014. _this._depthOfFieldBlurY = [];
  69015. _this._depthOfFieldBlurX = [];
  69016. var blurCount = 1;
  69017. var kernelSize = 15;
  69018. switch (blurLevel) {
  69019. case DepthOfFieldEffectBlurLevel.High: {
  69020. blurCount = 3;
  69021. kernelSize = 51;
  69022. break;
  69023. }
  69024. case DepthOfFieldEffectBlurLevel.Medium: {
  69025. blurCount = 2;
  69026. kernelSize = 31;
  69027. break;
  69028. }
  69029. default: {
  69030. kernelSize = 15;
  69031. blurCount = 1;
  69032. break;
  69033. }
  69034. }
  69035. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69036. for (var i = 0; i < blurCount; i++) {
  69037. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  69038. blurY.autoClear = false;
  69039. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  69040. blurX.autoClear = false;
  69041. _this._depthOfFieldBlurY.push(blurY);
  69042. _this._depthOfFieldBlurX.push(blurX);
  69043. }
  69044. // Merge blurred images with original image based on circleOfConfusion
  69045. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  69046. _this._depthOfFieldMerge.autoClear = false;
  69047. // Set all post processes on the effect.
  69048. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69049. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69050. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69051. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69052. }
  69053. _this._effects.push(_this._depthOfFieldMerge);
  69054. return _this;
  69055. }
  69056. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69057. get: function () {
  69058. return this._circleOfConfusion.focalLength;
  69059. },
  69060. /**
  69061. * The focal the length of the camera used in the effect
  69062. */
  69063. set: function (value) {
  69064. this._circleOfConfusion.focalLength = value;
  69065. },
  69066. enumerable: true,
  69067. configurable: true
  69068. });
  69069. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69070. get: function () {
  69071. return this._circleOfConfusion.fStop;
  69072. },
  69073. /**
  69074. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69075. */
  69076. set: function (value) {
  69077. this._circleOfConfusion.fStop = value;
  69078. },
  69079. enumerable: true,
  69080. configurable: true
  69081. });
  69082. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69083. get: function () {
  69084. return this._circleOfConfusion.focusDistance;
  69085. },
  69086. /**
  69087. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69088. */
  69089. set: function (value) {
  69090. this._circleOfConfusion.focusDistance = value;
  69091. },
  69092. enumerable: true,
  69093. configurable: true
  69094. });
  69095. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69096. get: function () {
  69097. return this._circleOfConfusion.lensSize;
  69098. },
  69099. /**
  69100. * 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.
  69101. */
  69102. set: function (value) {
  69103. this._circleOfConfusion.lensSize = value;
  69104. },
  69105. enumerable: true,
  69106. configurable: true
  69107. });
  69108. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69109. /**
  69110. * 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.
  69111. */
  69112. set: function (value) {
  69113. this._circleOfConfusion.depthTexture = value;
  69114. },
  69115. enumerable: true,
  69116. configurable: true
  69117. });
  69118. /**
  69119. * Disposes each of the internal effects for a given camera.
  69120. * @param camera The camera to dispose the effect on.
  69121. */
  69122. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69123. this._depthOfFieldPass.dispose(camera);
  69124. this._circleOfConfusion.dispose(camera);
  69125. this._depthOfFieldBlurX.forEach(function (element) {
  69126. element.dispose(camera);
  69127. });
  69128. this._depthOfFieldBlurY.forEach(function (element) {
  69129. element.dispose(camera);
  69130. });
  69131. this._depthOfFieldMerge.dispose(camera);
  69132. };
  69133. return DepthOfFieldEffect;
  69134. }(BABYLON.PostProcessRenderEffect));
  69135. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69136. })(BABYLON || (BABYLON = {}));
  69137. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69138. var BABYLON;
  69139. (function (BABYLON) {
  69140. /**
  69141. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69142. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69143. */
  69144. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69145. __extends(DefaultRenderingPipeline, _super);
  69146. /**
  69147. * @constructor
  69148. * @param {string} name - The rendering pipeline name
  69149. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69150. * @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)
  69151. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69152. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69153. */
  69154. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69155. if (automaticBuild === void 0) { automaticBuild = true; }
  69156. var _this = _super.call(this, scene.getEngine(), name) || this;
  69157. _this._originalCameras = [];
  69158. /**
  69159. * ID of the sharpen post process,
  69160. */
  69161. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69162. /**
  69163. * ID of the pass post process used for bloom,
  69164. */
  69165. _this.PassPostProcessId = "PassPostProcessEffect";
  69166. /**
  69167. * ID of the highlight post process used for bloom,
  69168. */
  69169. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69170. /**
  69171. * ID of the blurX post process used for bloom,
  69172. */
  69173. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69174. /**
  69175. * ID of the blurY post process used for bloom,
  69176. */
  69177. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69178. /**
  69179. * ID of the copy back post process used for bloom,
  69180. */
  69181. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69182. /**
  69183. * ID of the image processing post process;
  69184. */
  69185. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69186. /**
  69187. * ID of the Fast Approximate Anti-Aliasing post process;
  69188. */
  69189. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69190. /**
  69191. * ID of the final merge post process;
  69192. */
  69193. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69194. /**
  69195. * ID of the chromatic aberration post process,
  69196. */
  69197. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69198. /**
  69199. * Animations which can be used to tweak settings over a period of time
  69200. */
  69201. _this.animations = [];
  69202. // Values
  69203. _this._sharpenEnabled = false;
  69204. _this._bloomEnabled = false;
  69205. _this._depthOfFieldEnabled = false;
  69206. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69207. _this._fxaaEnabled = false;
  69208. _this._msaaEnabled = false;
  69209. _this._imageProcessingEnabled = true;
  69210. _this._bloomScale = 0.6;
  69211. _this._chromaticAberrationEnabled = false;
  69212. _this._buildAllowed = true;
  69213. /**
  69214. * Specifies the size of the bloom blur kernel, relative to the final output size
  69215. */
  69216. _this.bloomKernel = 64;
  69217. /**
  69218. * Specifies the weight of the bloom in the final rendering
  69219. */
  69220. _this._bloomWeight = 0.15;
  69221. _this._prevPostProcess = null;
  69222. _this._prevPrevPostProcess = null;
  69223. _this._cameras = cameras || [];
  69224. _this._originalCameras = _this._cameras.slice();
  69225. _this._buildAllowed = automaticBuild;
  69226. // Initialize
  69227. _this._scene = scene;
  69228. var caps = _this._scene.getEngine().getCaps();
  69229. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69230. // Misc
  69231. if (_this._hdr) {
  69232. if (caps.textureHalfFloatRender) {
  69233. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69234. }
  69235. else if (caps.textureFloatRender) {
  69236. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69237. }
  69238. }
  69239. else {
  69240. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69241. }
  69242. // Attach
  69243. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69244. var engine = _this._scene.getEngine();
  69245. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  69246. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69247. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType);
  69248. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType);
  69249. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69250. _this._buildPipeline();
  69251. return _this;
  69252. }
  69253. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69254. get: function () {
  69255. return this._sharpenEnabled;
  69256. },
  69257. /**
  69258. * Enable or disable the sharpen process from the pipeline
  69259. */
  69260. set: function (enabled) {
  69261. if (this._sharpenEnabled === enabled) {
  69262. return;
  69263. }
  69264. this._sharpenEnabled = enabled;
  69265. this._buildPipeline();
  69266. },
  69267. enumerable: true,
  69268. configurable: true
  69269. });
  69270. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69271. get: function () {
  69272. return this._bloomWeight;
  69273. },
  69274. /**
  69275. * The strength of the bloom.
  69276. */
  69277. set: function (value) {
  69278. if (this._bloomWeight === value) {
  69279. return;
  69280. }
  69281. this._bloomWeight = value;
  69282. if (this._hdr && this.copyBack) {
  69283. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69284. }
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69290. get: function () {
  69291. return this._bloomScale;
  69292. },
  69293. /**
  69294. * The scale of the bloom, lower value will provide better performance.
  69295. */
  69296. set: function (value) {
  69297. if (this._bloomScale === value) {
  69298. return;
  69299. }
  69300. this._bloomScale = value;
  69301. this._buildPipeline();
  69302. },
  69303. enumerable: true,
  69304. configurable: true
  69305. });
  69306. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69307. get: function () {
  69308. return this._bloomEnabled;
  69309. },
  69310. /**
  69311. * Enable or disable the bloom from the pipeline
  69312. */
  69313. set: function (enabled) {
  69314. if (this._bloomEnabled === enabled) {
  69315. return;
  69316. }
  69317. this._bloomEnabled = enabled;
  69318. this._buildPipeline();
  69319. },
  69320. enumerable: true,
  69321. configurable: true
  69322. });
  69323. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69324. /**
  69325. * If the depth of field is enabled.
  69326. */
  69327. get: function () {
  69328. return this._depthOfFieldEnabled;
  69329. },
  69330. set: function (enabled) {
  69331. if (this._depthOfFieldEnabled === enabled) {
  69332. return;
  69333. }
  69334. this._depthOfFieldEnabled = enabled;
  69335. this._buildPipeline();
  69336. },
  69337. enumerable: true,
  69338. configurable: true
  69339. });
  69340. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69341. /**
  69342. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69343. */
  69344. get: function () {
  69345. return this._depthOfFieldBlurLevel;
  69346. },
  69347. set: function (value) {
  69348. if (this._depthOfFieldBlurLevel === value) {
  69349. return;
  69350. }
  69351. this._depthOfFieldBlurLevel = value;
  69352. // recreate dof and dispose old as this setting is not dynamic
  69353. var oldDof = this.depthOfField;
  69354. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69355. this.depthOfField.focalLength = oldDof.focalLength;
  69356. this.depthOfField.focusDistance = oldDof.focusDistance;
  69357. this.depthOfField.fStop = oldDof.fStop;
  69358. this.depthOfField.lensSize = oldDof.lensSize;
  69359. for (var i = 0; i < this._cameras.length; i++) {
  69360. oldDof.disposeEffects(this._cameras[i]);
  69361. }
  69362. this._buildPipeline();
  69363. },
  69364. enumerable: true,
  69365. configurable: true
  69366. });
  69367. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69368. get: function () {
  69369. return this._fxaaEnabled;
  69370. },
  69371. /**
  69372. * If the anti aliasing is enabled.
  69373. */
  69374. set: function (enabled) {
  69375. if (this._fxaaEnabled === enabled) {
  69376. return;
  69377. }
  69378. this._fxaaEnabled = enabled;
  69379. this._buildPipeline();
  69380. },
  69381. enumerable: true,
  69382. configurable: true
  69383. });
  69384. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69385. get: function () {
  69386. return this._msaaEnabled;
  69387. },
  69388. /**
  69389. * If the multisample anti-aliasing is enabled.
  69390. */
  69391. set: function (enabled) {
  69392. if (this._msaaEnabled === enabled) {
  69393. return;
  69394. }
  69395. this._msaaEnabled = enabled;
  69396. this._buildPipeline();
  69397. },
  69398. enumerable: true,
  69399. configurable: true
  69400. });
  69401. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69402. get: function () {
  69403. return this._imageProcessingEnabled;
  69404. },
  69405. /**
  69406. * If image processing is enabled.
  69407. */
  69408. set: function (enabled) {
  69409. if (this._imageProcessingEnabled === enabled) {
  69410. return;
  69411. }
  69412. this._imageProcessingEnabled = enabled;
  69413. this._buildPipeline();
  69414. },
  69415. enumerable: true,
  69416. configurable: true
  69417. });
  69418. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69419. get: function () {
  69420. return this._chromaticAberrationEnabled;
  69421. },
  69422. /**
  69423. * Enable or disable the chromaticAberration process from the pipeline
  69424. */
  69425. set: function (enabled) {
  69426. if (this._chromaticAberrationEnabled === enabled) {
  69427. return;
  69428. }
  69429. this._chromaticAberrationEnabled = enabled;
  69430. this._buildPipeline();
  69431. },
  69432. enumerable: true,
  69433. configurable: true
  69434. });
  69435. /**
  69436. * Force the compilation of the entire pipeline.
  69437. */
  69438. DefaultRenderingPipeline.prototype.prepare = function () {
  69439. var previousState = this._buildAllowed;
  69440. this._buildAllowed = true;
  69441. this._buildPipeline();
  69442. this._buildAllowed = previousState;
  69443. };
  69444. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69445. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69446. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69447. postProcess.autoClear = false;
  69448. }
  69449. else {
  69450. postProcess.autoClear = true;
  69451. }
  69452. if (!skipTextureSharing) {
  69453. if (this._prevPrevPostProcess) {
  69454. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69455. }
  69456. else {
  69457. postProcess.useOwnOutput();
  69458. }
  69459. if (this._prevPostProcess) {
  69460. this._prevPrevPostProcess = this._prevPostProcess;
  69461. }
  69462. this._prevPostProcess = postProcess;
  69463. }
  69464. };
  69465. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69466. var _this = this;
  69467. if (!this._buildAllowed) {
  69468. return;
  69469. }
  69470. var engine = this._scene.getEngine();
  69471. this._disposePostProcesses();
  69472. if (this._cameras !== null) {
  69473. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69474. // get back cameras to be used to reattach pipeline
  69475. this._cameras = this._originalCameras.slice();
  69476. }
  69477. this._reset();
  69478. this._prevPostProcess = null;
  69479. this._prevPrevPostProcess = null;
  69480. if (this.sharpenEnabled) {
  69481. this.addEffect(this._sharpenEffect);
  69482. this._setAutoClearAndTextureSharing(this.sharpen);
  69483. }
  69484. if (this.depthOfFieldEnabled) {
  69485. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69486. this.depthOfField.depthTexture = depthTexture;
  69487. this.addEffect(this.depthOfField);
  69488. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69489. }
  69490. if (this.bloomEnabled) {
  69491. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69492. this._setAutoClearAndTextureSharing(this.pass, true);
  69493. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69494. if (!this._hdr) {
  69495. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69496. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69497. this.highlights.autoClear = false;
  69498. this.highlights.alwaysForcePOT = true;
  69499. }
  69500. 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);
  69501. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69502. this.blurX.alwaysForcePOT = true;
  69503. this.blurX.autoClear = false;
  69504. this.blurX.onActivateObservable.add(function () {
  69505. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69506. _this.blurX.kernel = _this.bloomKernel * dw;
  69507. });
  69508. 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);
  69509. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69510. this.blurY.alwaysForcePOT = true;
  69511. this.blurY.autoClear = false;
  69512. this.blurY.onActivateObservable.add(function () {
  69513. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69514. _this.blurY.kernel = _this.bloomKernel * dh;
  69515. });
  69516. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69517. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69518. this.copyBack.alwaysForcePOT = true;
  69519. if (this._hdr) {
  69520. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69521. var w = this.bloomWeight;
  69522. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69523. }
  69524. else {
  69525. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69526. }
  69527. this.copyBack.autoClear = false;
  69528. }
  69529. if (this._imageProcessingEnabled) {
  69530. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69531. if (this._hdr) {
  69532. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69533. }
  69534. else {
  69535. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69536. }
  69537. }
  69538. if (this._hdr && this.imageProcessing) {
  69539. this.finalMerge = this.imageProcessing;
  69540. }
  69541. else {
  69542. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69543. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69544. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69545. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69546. }
  69547. if (this.bloomEnabled) {
  69548. if (this._hdr) {
  69549. this.copyBack.shareOutputWith(this.blurX);
  69550. if (this.imageProcessing) {
  69551. this.imageProcessing.shareOutputWith(this.pass);
  69552. this.imageProcessing.autoClear = false;
  69553. }
  69554. else {
  69555. this.finalMerge.shareOutputWith(this.pass);
  69556. }
  69557. }
  69558. else {
  69559. this.finalMerge.shareOutputWith(this.pass);
  69560. }
  69561. }
  69562. if (this.fxaaEnabled) {
  69563. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69564. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69565. this._setAutoClearAndTextureSharing(this.fxaa);
  69566. }
  69567. if (this.chromaticAberrationEnabled) {
  69568. this.addEffect(this._chromaticAberrationEffect);
  69569. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69570. }
  69571. if (this._cameras !== null) {
  69572. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69573. }
  69574. if (this.msaaEnabled) {
  69575. if (!this._enableMSAAOnFirstPostProcess()) {
  69576. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69577. }
  69578. }
  69579. };
  69580. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69581. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69582. for (var i = 0; i < this._cameras.length; i++) {
  69583. var camera = this._cameras[i];
  69584. if (this.pass) {
  69585. this.pass.dispose(camera);
  69586. }
  69587. if (this.highlights) {
  69588. this.highlights.dispose(camera);
  69589. }
  69590. if (this.blurX) {
  69591. this.blurX.dispose(camera);
  69592. }
  69593. if (this.blurY) {
  69594. this.blurY.dispose(camera);
  69595. }
  69596. if (this.copyBack) {
  69597. this.copyBack.dispose(camera);
  69598. }
  69599. if (this.imageProcessing) {
  69600. this.imageProcessing.dispose(camera);
  69601. }
  69602. if (this.fxaa) {
  69603. this.fxaa.dispose(camera);
  69604. }
  69605. if (this.finalMerge) {
  69606. this.finalMerge.dispose(camera);
  69607. }
  69608. // These are created in the constructor and should not be disposed on every pipeline change
  69609. if (disposeNonRecreated) {
  69610. if (this.sharpen) {
  69611. this.sharpen.dispose(camera);
  69612. }
  69613. if (this.depthOfField) {
  69614. this.depthOfField.disposeEffects(camera);
  69615. }
  69616. if (this.chromaticAberration) {
  69617. this.chromaticAberration.dispose(camera);
  69618. }
  69619. }
  69620. }
  69621. this.pass = null;
  69622. this.highlights = null;
  69623. this.blurX = null;
  69624. this.blurY = null;
  69625. this.copyBack = null;
  69626. this.imageProcessing = null;
  69627. this.fxaa = null;
  69628. this.finalMerge = null;
  69629. if (disposeNonRecreated) {
  69630. this.sharpen = null;
  69631. this.depthOfField = null;
  69632. this.chromaticAberration = null;
  69633. }
  69634. };
  69635. /**
  69636. * Dispose of the pipeline and stop all post processes
  69637. */
  69638. DefaultRenderingPipeline.prototype.dispose = function () {
  69639. this._disposePostProcesses(true);
  69640. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69641. _super.prototype.dispose.call(this);
  69642. };
  69643. /**
  69644. * Serialize the rendering pipeline (Used when exporting)
  69645. * @returns the serialized object
  69646. */
  69647. DefaultRenderingPipeline.prototype.serialize = function () {
  69648. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69649. serializationObject.customType = "DefaultRenderingPipeline";
  69650. return serializationObject;
  69651. };
  69652. /**
  69653. * Parse the serialized pipeline
  69654. * @param source Source pipeline.
  69655. * @param scene The scene to load the pipeline to.
  69656. * @param rootUrl The URL of the serialized pipeline.
  69657. * @returns An instantiated pipeline from the serialized object.
  69658. */
  69659. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69660. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69661. };
  69662. __decorate([
  69663. BABYLON.serialize()
  69664. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69665. __decorate([
  69666. BABYLON.serialize()
  69667. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69668. __decorate([
  69669. BABYLON.serialize()
  69670. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69671. __decorate([
  69672. BABYLON.serialize()
  69673. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69674. __decorate([
  69675. BABYLON.serialize()
  69676. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69677. __decorate([
  69678. BABYLON.serialize()
  69679. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69680. __decorate([
  69681. BABYLON.serialize()
  69682. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69683. __decorate([
  69684. BABYLON.serialize()
  69685. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69686. __decorate([
  69687. BABYLON.serialize()
  69688. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69689. __decorate([
  69690. BABYLON.serialize()
  69691. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69692. __decorate([
  69693. BABYLON.serialize()
  69694. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69695. __decorate([
  69696. BABYLON.serialize()
  69697. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69698. __decorate([
  69699. BABYLON.serialize()
  69700. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69701. return DefaultRenderingPipeline;
  69702. }(BABYLON.PostProcessRenderPipeline));
  69703. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69704. })(BABYLON || (BABYLON = {}));
  69705. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69706. var BABYLON;
  69707. (function (BABYLON) {
  69708. /**
  69709. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69710. */
  69711. var GeometryBufferRenderer = /** @class */ (function () {
  69712. /**
  69713. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69714. * @param scene The scene the buffer belongs to
  69715. * @param ratio How big is the buffer related to the main canvas.
  69716. */
  69717. function GeometryBufferRenderer(scene, ratio) {
  69718. if (ratio === void 0) { ratio = 1; }
  69719. this._enablePosition = false;
  69720. this._scene = scene;
  69721. this._ratio = ratio;
  69722. // Render target
  69723. this._createRenderTargets();
  69724. }
  69725. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69726. /**
  69727. * Set the render list (meshes to be rendered) used in the G buffer.
  69728. */
  69729. set: function (meshes) {
  69730. this._multiRenderTarget.renderList = meshes;
  69731. },
  69732. enumerable: true,
  69733. configurable: true
  69734. });
  69735. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69736. /**
  69737. * Gets wether or not G buffer are supported by the running hardware.
  69738. * This requires draw buffer supports
  69739. */
  69740. get: function () {
  69741. return this._multiRenderTarget.isSupported;
  69742. },
  69743. enumerable: true,
  69744. configurable: true
  69745. });
  69746. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69747. /**
  69748. * Gets wether or not position are enabled for the G buffer.
  69749. */
  69750. get: function () {
  69751. return this._enablePosition;
  69752. },
  69753. /**
  69754. * Sets wether or not position are enabled for the G buffer.
  69755. */
  69756. set: function (enable) {
  69757. this._enablePosition = enable;
  69758. this.dispose();
  69759. this._createRenderTargets();
  69760. },
  69761. enumerable: true,
  69762. configurable: true
  69763. });
  69764. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69765. /**
  69766. * Gets the scene associated with the buffer.
  69767. */
  69768. get: function () {
  69769. return this._scene;
  69770. },
  69771. enumerable: true,
  69772. configurable: true
  69773. });
  69774. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69775. /**
  69776. * Gets the ratio used by the buffer during its creation.
  69777. * How big is the buffer related to the main canvas.
  69778. */
  69779. get: function () {
  69780. return this._ratio;
  69781. },
  69782. enumerable: true,
  69783. configurable: true
  69784. });
  69785. /**
  69786. * Checks wether everything is ready to render a submesh to the G buffer.
  69787. * @param subMesh the submesh to check readiness for
  69788. * @param useInstances is the mesh drawn using instance or not
  69789. * @returns true if ready otherwise false
  69790. */
  69791. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69792. var material = subMesh.getMaterial();
  69793. if (material && material.disableDepthWrite) {
  69794. return false;
  69795. }
  69796. var defines = [];
  69797. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69798. var mesh = subMesh.getMesh();
  69799. // Alpha test
  69800. if (material && material.needAlphaTesting()) {
  69801. defines.push("#define ALPHATEST");
  69802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69803. attribs.push(BABYLON.VertexBuffer.UVKind);
  69804. defines.push("#define UV1");
  69805. }
  69806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69807. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69808. defines.push("#define UV2");
  69809. }
  69810. }
  69811. // Buffers
  69812. if (this._enablePosition) {
  69813. defines.push("#define POSITION");
  69814. }
  69815. // Bones
  69816. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69819. if (mesh.numBoneInfluencers > 4) {
  69820. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69821. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69822. }
  69823. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69824. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69825. }
  69826. else {
  69827. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69828. }
  69829. // Instances
  69830. if (useInstances) {
  69831. defines.push("#define INSTANCES");
  69832. attribs.push("world0");
  69833. attribs.push("world1");
  69834. attribs.push("world2");
  69835. attribs.push("world3");
  69836. }
  69837. // Get correct effect
  69838. var join = defines.join("\n");
  69839. if (this._cachedDefines !== join) {
  69840. this._cachedDefines = join;
  69841. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69842. }
  69843. return this._effect.isReady();
  69844. };
  69845. /**
  69846. * Gets the current underlying G Buffer.
  69847. * @returns the buffer
  69848. */
  69849. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69850. return this._multiRenderTarget;
  69851. };
  69852. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69853. /**
  69854. * Gets the number of samples used to render the buffer (anti aliasing).
  69855. */
  69856. get: function () {
  69857. return this._multiRenderTarget.samples;
  69858. },
  69859. /**
  69860. * Sets the number of samples used to render the buffer (anti aliasing).
  69861. */
  69862. set: function (value) {
  69863. this._multiRenderTarget.samples = value;
  69864. },
  69865. enumerable: true,
  69866. configurable: true
  69867. });
  69868. /**
  69869. * Disposes the renderer and frees up associated resources.
  69870. */
  69871. GeometryBufferRenderer.prototype.dispose = function () {
  69872. this.getGBuffer().dispose();
  69873. };
  69874. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69875. var _this = this;
  69876. var engine = this._scene.getEngine();
  69877. var count = this._enablePosition ? 3 : 2;
  69878. 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 });
  69879. if (!this.isSupported) {
  69880. return;
  69881. }
  69882. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69883. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69884. this._multiRenderTarget.refreshRate = 1;
  69885. this._multiRenderTarget.renderParticles = false;
  69886. this._multiRenderTarget.renderList = null;
  69887. // set default depth value to 1.0 (far away)
  69888. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69889. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69890. });
  69891. // Custom render function
  69892. var renderSubMesh = function (subMesh) {
  69893. var mesh = subMesh.getRenderingMesh();
  69894. var scene = _this._scene;
  69895. var engine = scene.getEngine();
  69896. var material = subMesh.getMaterial();
  69897. if (!material) {
  69898. return;
  69899. }
  69900. // Culling
  69901. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69902. // Managing instances
  69903. var batch = mesh._getInstancesRenderList(subMesh._id);
  69904. if (batch.mustReturn) {
  69905. return;
  69906. }
  69907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69908. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69909. engine.enableEffect(_this._effect);
  69910. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69911. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69912. _this._effect.setMatrix("view", scene.getViewMatrix());
  69913. // Alpha test
  69914. if (material && material.needAlphaTesting()) {
  69915. var alphaTexture = material.getAlphaTestTexture();
  69916. if (alphaTexture) {
  69917. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69918. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69919. }
  69920. }
  69921. // Bones
  69922. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69923. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69924. }
  69925. // Draw
  69926. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69927. }
  69928. };
  69929. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69930. var index;
  69931. if (depthOnlySubMeshes.length) {
  69932. engine.setColorWrite(false);
  69933. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69934. renderSubMesh(depthOnlySubMeshes.data[index]);
  69935. }
  69936. engine.setColorWrite(true);
  69937. }
  69938. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69939. renderSubMesh(opaqueSubMeshes.data[index]);
  69940. }
  69941. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69942. renderSubMesh(alphaTestSubMeshes.data[index]);
  69943. }
  69944. };
  69945. };
  69946. return GeometryBufferRenderer;
  69947. }());
  69948. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69949. })(BABYLON || (BABYLON = {}));
  69950. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69951. var BABYLON;
  69952. (function (BABYLON) {
  69953. var RefractionPostProcess = /** @class */ (function (_super) {
  69954. __extends(RefractionPostProcess, _super);
  69955. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69956. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69957. _this.color = color;
  69958. _this.depth = depth;
  69959. _this.colorLevel = colorLevel;
  69960. _this._ownRefractionTexture = true;
  69961. _this.onActivateObservable.add(function (cam) {
  69962. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69963. });
  69964. _this.onApplyObservable.add(function (effect) {
  69965. effect.setColor3("baseColor", _this.color);
  69966. effect.setFloat("depth", _this.depth);
  69967. effect.setFloat("colorLevel", _this.colorLevel);
  69968. effect.setTexture("refractionSampler", _this._refTexture);
  69969. });
  69970. return _this;
  69971. }
  69972. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69973. /**
  69974. * Gets or sets the refraction texture
  69975. * Please note that you are responsible for disposing the texture if you set it manually
  69976. */
  69977. get: function () {
  69978. return this._refTexture;
  69979. },
  69980. set: function (value) {
  69981. if (this._refTexture && this._ownRefractionTexture) {
  69982. this._refTexture.dispose();
  69983. }
  69984. this._refTexture = value;
  69985. this._ownRefractionTexture = false;
  69986. },
  69987. enumerable: true,
  69988. configurable: true
  69989. });
  69990. // Methods
  69991. RefractionPostProcess.prototype.dispose = function (camera) {
  69992. if (this._refTexture && this._ownRefractionTexture) {
  69993. this._refTexture.dispose();
  69994. this._refTexture = null;
  69995. }
  69996. _super.prototype.dispose.call(this, camera);
  69997. };
  69998. return RefractionPostProcess;
  69999. }(BABYLON.PostProcess));
  70000. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70001. })(BABYLON || (BABYLON = {}));
  70002. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70003. var BABYLON;
  70004. (function (BABYLON) {
  70005. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70006. __extends(BlackAndWhitePostProcess, _super);
  70007. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70008. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70009. _this.degree = 1;
  70010. _this.onApplyObservable.add(function (effect) {
  70011. effect.setFloat("degree", _this.degree);
  70012. });
  70013. return _this;
  70014. }
  70015. return BlackAndWhitePostProcess;
  70016. }(BABYLON.PostProcess));
  70017. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70018. })(BABYLON || (BABYLON = {}));
  70019. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70020. var BABYLON;
  70021. (function (BABYLON) {
  70022. /**
  70023. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70024. * input texture to perform effects such as edge detection or sharpening
  70025. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70026. */
  70027. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70028. __extends(ConvolutionPostProcess, _super);
  70029. /**
  70030. * Creates a new instance of @see ConvolutionPostProcess
  70031. * @param name The name of the effect.
  70032. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  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. */
  70040. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70041. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70042. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70043. _this.kernel = kernel;
  70044. _this.onApply = function (effect) {
  70045. effect.setFloat2("screenSize", _this.width, _this.height);
  70046. effect.setArray("kernel", _this.kernel);
  70047. };
  70048. return _this;
  70049. }
  70050. // Statics
  70051. /**
  70052. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70053. */
  70054. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70055. /**
  70056. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70057. */
  70058. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70059. /**
  70060. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70061. */
  70062. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70063. /**
  70064. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70065. */
  70066. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70067. /**
  70068. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70069. */
  70070. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70071. /**
  70072. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70073. */
  70074. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70075. return ConvolutionPostProcess;
  70076. }(BABYLON.PostProcess));
  70077. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70078. })(BABYLON || (BABYLON = {}));
  70079. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70080. var BABYLON;
  70081. (function (BABYLON) {
  70082. var FilterPostProcess = /** @class */ (function (_super) {
  70083. __extends(FilterPostProcess, _super);
  70084. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70085. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70086. _this.kernelMatrix = kernelMatrix;
  70087. _this.onApply = function (effect) {
  70088. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70089. };
  70090. return _this;
  70091. }
  70092. return FilterPostProcess;
  70093. }(BABYLON.PostProcess));
  70094. BABYLON.FilterPostProcess = FilterPostProcess;
  70095. })(BABYLON || (BABYLON = {}));
  70096. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70097. var BABYLON;
  70098. (function (BABYLON) {
  70099. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70100. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70101. __extends(VolumetricLightScatteringPostProcess, _super);
  70102. /**
  70103. * @constructor
  70104. * @param {string} name - The post-process name
  70105. * @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)
  70106. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70107. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70108. * @param {number} samples - The post-process quality, default 100
  70109. * @param {number} samplingMode - The post-process filtering mode
  70110. * @param {BABYLON.Engine} engine - The babylon engine
  70111. * @param {boolean} reusable - If the post-process is reusable
  70112. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70113. */
  70114. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70115. if (samples === void 0) { samples = 100; }
  70116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70117. 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;
  70118. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70119. /**
  70120. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70121. * @type {Vector3}
  70122. */
  70123. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70124. /**
  70125. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70126. * @type {boolean}
  70127. */
  70128. _this.useCustomMeshPosition = false;
  70129. /**
  70130. * If the post-process should inverse the light scattering direction
  70131. * @type {boolean}
  70132. */
  70133. _this.invert = true;
  70134. /**
  70135. * Array containing the excluded meshes not rendered in the internal pass
  70136. */
  70137. _this.excludedMeshes = new Array();
  70138. /**
  70139. * Controls the overall intensity of the post-process
  70140. * @type {number}
  70141. */
  70142. _this.exposure = 0.3;
  70143. /**
  70144. * Dissipates each sample's contribution in range [0, 1]
  70145. * @type {number}
  70146. */
  70147. _this.decay = 0.96815;
  70148. /**
  70149. * Controls the overall intensity of each sample
  70150. * @type {number}
  70151. */
  70152. _this.weight = 0.58767;
  70153. /**
  70154. * Controls the density of each sample
  70155. * @type {number}
  70156. */
  70157. _this.density = 0.926;
  70158. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70159. engine = scene.getEngine();
  70160. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70161. // Configure mesh
  70162. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70163. // Configure
  70164. _this._createPass(scene, ratio.passRatio || ratio);
  70165. _this.onActivate = function (camera) {
  70166. if (!_this.isSupported) {
  70167. _this.dispose(camera);
  70168. }
  70169. _this.onActivate = null;
  70170. };
  70171. _this.onApplyObservable.add(function (effect) {
  70172. _this._updateMeshScreenCoordinates(scene);
  70173. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70174. effect.setFloat("exposure", _this.exposure);
  70175. effect.setFloat("decay", _this.decay);
  70176. effect.setFloat("weight", _this.weight);
  70177. effect.setFloat("density", _this.density);
  70178. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70179. });
  70180. return _this;
  70181. }
  70182. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70183. get: function () {
  70184. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70185. return false;
  70186. },
  70187. set: function (useDiffuseColor) {
  70188. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70189. },
  70190. enumerable: true,
  70191. configurable: true
  70192. });
  70193. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70194. return "VolumetricLightScatteringPostProcess";
  70195. };
  70196. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70197. var mesh = subMesh.getMesh();
  70198. // Render this.mesh as default
  70199. if (mesh === this.mesh && mesh.material) {
  70200. return mesh.material.isReady(mesh);
  70201. }
  70202. var defines = [];
  70203. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70204. var material = subMesh.getMaterial();
  70205. // Alpha test
  70206. if (material) {
  70207. if (material.needAlphaTesting()) {
  70208. defines.push("#define ALPHATEST");
  70209. }
  70210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70211. attribs.push(BABYLON.VertexBuffer.UVKind);
  70212. defines.push("#define UV1");
  70213. }
  70214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70215. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70216. defines.push("#define UV2");
  70217. }
  70218. }
  70219. // Bones
  70220. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70221. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70222. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70224. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70225. }
  70226. else {
  70227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70228. }
  70229. // Instances
  70230. if (useInstances) {
  70231. defines.push("#define INSTANCES");
  70232. attribs.push("world0");
  70233. attribs.push("world1");
  70234. attribs.push("world2");
  70235. attribs.push("world3");
  70236. }
  70237. // Get correct effect
  70238. var join = defines.join("\n");
  70239. if (this._cachedDefines !== join) {
  70240. this._cachedDefines = join;
  70241. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70242. }
  70243. return this._volumetricLightScatteringPass.isReady();
  70244. };
  70245. /**
  70246. * Sets the new light position for light scattering effect
  70247. * @param {BABYLON.Vector3} The new custom light position
  70248. */
  70249. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70250. this.customMeshPosition = position;
  70251. };
  70252. /**
  70253. * Returns the light position for light scattering effect
  70254. * @return {BABYLON.Vector3} The custom light position
  70255. */
  70256. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70257. return this.customMeshPosition;
  70258. };
  70259. /**
  70260. * Disposes the internal assets and detaches the post-process from the camera
  70261. */
  70262. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70263. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70264. if (rttIndex !== -1) {
  70265. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70266. }
  70267. this._volumetricLightScatteringRTT.dispose();
  70268. _super.prototype.dispose.call(this, camera);
  70269. };
  70270. /**
  70271. * Returns the render target texture used by the post-process
  70272. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70273. */
  70274. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70275. return this._volumetricLightScatteringRTT;
  70276. };
  70277. // Private methods
  70278. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70279. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70280. return true;
  70281. }
  70282. return false;
  70283. };
  70284. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70285. var _this = this;
  70286. var engine = scene.getEngine();
  70287. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70288. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70289. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70290. this._volumetricLightScatteringRTT.renderList = null;
  70291. this._volumetricLightScatteringRTT.renderParticles = false;
  70292. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70293. var camera = this.getCamera();
  70294. if (camera) {
  70295. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70296. }
  70297. else {
  70298. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70299. }
  70300. // Custom render function for submeshes
  70301. var renderSubMesh = function (subMesh) {
  70302. var mesh = subMesh.getRenderingMesh();
  70303. if (_this._meshExcluded(mesh)) {
  70304. return;
  70305. }
  70306. var material = subMesh.getMaterial();
  70307. if (!material) {
  70308. return;
  70309. }
  70310. var scene = mesh.getScene();
  70311. var engine = scene.getEngine();
  70312. // Culling
  70313. engine.setState(material.backFaceCulling);
  70314. // Managing instances
  70315. var batch = mesh._getInstancesRenderList(subMesh._id);
  70316. if (batch.mustReturn) {
  70317. return;
  70318. }
  70319. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70320. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70321. var effect = _this._volumetricLightScatteringPass;
  70322. if (mesh === _this.mesh) {
  70323. if (subMesh.effect) {
  70324. effect = subMesh.effect;
  70325. }
  70326. else {
  70327. effect = material.getEffect();
  70328. }
  70329. }
  70330. engine.enableEffect(effect);
  70331. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70332. if (mesh === _this.mesh) {
  70333. material.bind(mesh.getWorldMatrix(), mesh);
  70334. }
  70335. else {
  70336. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70337. // Alpha test
  70338. if (material && material.needAlphaTesting()) {
  70339. var alphaTexture = material.getAlphaTestTexture();
  70340. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70341. if (alphaTexture) {
  70342. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70343. }
  70344. }
  70345. // Bones
  70346. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70347. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70348. }
  70349. }
  70350. // Draw
  70351. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70352. }
  70353. };
  70354. // Render target texture callbacks
  70355. var savedSceneClearColor;
  70356. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70357. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70358. savedSceneClearColor = scene.clearColor;
  70359. scene.clearColor = sceneClearColor;
  70360. });
  70361. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70362. scene.clearColor = savedSceneClearColor;
  70363. });
  70364. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70365. var engine = scene.getEngine();
  70366. var index;
  70367. if (depthOnlySubMeshes.length) {
  70368. engine.setColorWrite(false);
  70369. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70370. renderSubMesh(depthOnlySubMeshes.data[index]);
  70371. }
  70372. engine.setColorWrite(true);
  70373. }
  70374. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70375. renderSubMesh(opaqueSubMeshes.data[index]);
  70376. }
  70377. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70378. renderSubMesh(alphaTestSubMeshes.data[index]);
  70379. }
  70380. if (transparentSubMeshes.length) {
  70381. // Sort sub meshes
  70382. for (index = 0; index < transparentSubMeshes.length; index++) {
  70383. var submesh = transparentSubMeshes.data[index];
  70384. var boundingInfo = submesh.getBoundingInfo();
  70385. if (boundingInfo && scene.activeCamera) {
  70386. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70387. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70388. }
  70389. }
  70390. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70391. sortedArray.sort(function (a, b) {
  70392. // Alpha index first
  70393. if (a._alphaIndex > b._alphaIndex) {
  70394. return 1;
  70395. }
  70396. if (a._alphaIndex < b._alphaIndex) {
  70397. return -1;
  70398. }
  70399. // Then distance to camera
  70400. if (a._distanceToCamera < b._distanceToCamera) {
  70401. return 1;
  70402. }
  70403. if (a._distanceToCamera > b._distanceToCamera) {
  70404. return -1;
  70405. }
  70406. return 0;
  70407. });
  70408. // Render sub meshes
  70409. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70410. for (index = 0; index < sortedArray.length; index++) {
  70411. renderSubMesh(sortedArray[index]);
  70412. }
  70413. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70414. }
  70415. };
  70416. };
  70417. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70418. var transform = scene.getTransformMatrix();
  70419. var meshPosition;
  70420. if (this.useCustomMeshPosition) {
  70421. meshPosition = this.customMeshPosition;
  70422. }
  70423. else if (this.attachedNode) {
  70424. meshPosition = this.attachedNode.position;
  70425. }
  70426. else {
  70427. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70428. }
  70429. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70430. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70431. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70432. if (this.invert)
  70433. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70434. };
  70435. // Static methods
  70436. /**
  70437. * Creates a default mesh for the Volumeric Light Scattering post-process
  70438. * @param {string} The mesh name
  70439. * @param {BABYLON.Scene} The scene where to create the mesh
  70440. * @return {BABYLON.Mesh} the default mesh
  70441. */
  70442. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70443. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70444. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70445. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70446. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70447. mesh.material = material;
  70448. return mesh;
  70449. };
  70450. __decorate([
  70451. BABYLON.serializeAsVector3()
  70452. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70453. __decorate([
  70454. BABYLON.serialize()
  70455. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70456. __decorate([
  70457. BABYLON.serialize()
  70458. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70459. __decorate([
  70460. BABYLON.serializeAsMeshReference()
  70461. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70462. __decorate([
  70463. BABYLON.serialize()
  70464. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70465. __decorate([
  70466. BABYLON.serialize()
  70467. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70468. __decorate([
  70469. BABYLON.serialize()
  70470. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70471. __decorate([
  70472. BABYLON.serialize()
  70473. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70474. __decorate([
  70475. BABYLON.serialize()
  70476. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70477. return VolumetricLightScatteringPostProcess;
  70478. }(BABYLON.PostProcess));
  70479. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70480. })(BABYLON || (BABYLON = {}));
  70481. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70482. //
  70483. // This post-process allows the modification of rendered colors by using
  70484. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70485. //
  70486. // The object needs to be provided an url to a texture containing the color
  70487. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70488. // Use an image editing software to tweak the LUT to match your needs.
  70489. //
  70490. // For an example of a color LUT, see here:
  70491. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70492. // For explanations on color grading, see here:
  70493. // http://udn.epicgames.com/Three/ColorGrading.html
  70494. //
  70495. var BABYLON;
  70496. (function (BABYLON) {
  70497. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70498. __extends(ColorCorrectionPostProcess, _super);
  70499. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70500. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70501. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70502. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70503. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70504. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70505. _this.onApply = function (effect) {
  70506. effect.setTexture("colorTable", _this._colorTableTexture);
  70507. };
  70508. return _this;
  70509. }
  70510. return ColorCorrectionPostProcess;
  70511. }(BABYLON.PostProcess));
  70512. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70513. })(BABYLON || (BABYLON = {}));
  70514. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70515. var BABYLON;
  70516. (function (BABYLON) {
  70517. var TonemappingOperator;
  70518. (function (TonemappingOperator) {
  70519. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70520. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70521. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70522. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70523. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70524. ;
  70525. var TonemapPostProcess = /** @class */ (function (_super) {
  70526. __extends(TonemapPostProcess, _super);
  70527. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70529. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70530. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70531. _this._operator = _operator;
  70532. _this.exposureAdjustment = exposureAdjustment;
  70533. var defines = "#define ";
  70534. if (_this._operator === TonemappingOperator.Hable)
  70535. defines += "HABLE_TONEMAPPING";
  70536. else if (_this._operator === TonemappingOperator.Reinhard)
  70537. defines += "REINHARD_TONEMAPPING";
  70538. else if (_this._operator === TonemappingOperator.HejiDawson)
  70539. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70540. else if (_this._operator === TonemappingOperator.Photographic)
  70541. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70542. //sadly a second call to create the effect.
  70543. _this.updateEffect(defines);
  70544. _this.onApply = function (effect) {
  70545. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70546. };
  70547. return _this;
  70548. }
  70549. return TonemapPostProcess;
  70550. }(BABYLON.PostProcess));
  70551. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70552. })(BABYLON || (BABYLON = {}));
  70553. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70554. var BABYLON;
  70555. (function (BABYLON) {
  70556. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70557. __extends(DisplayPassPostProcess, _super);
  70558. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70559. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70560. }
  70561. return DisplayPassPostProcess;
  70562. }(BABYLON.PostProcess));
  70563. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70564. })(BABYLON || (BABYLON = {}));
  70565. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70566. var BABYLON;
  70567. (function (BABYLON) {
  70568. var HighlightsPostProcess = /** @class */ (function (_super) {
  70569. __extends(HighlightsPostProcess, _super);
  70570. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70572. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70573. }
  70574. return HighlightsPostProcess;
  70575. }(BABYLON.PostProcess));
  70576. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70577. })(BABYLON || (BABYLON = {}));
  70578. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70579. var BABYLON;
  70580. (function (BABYLON) {
  70581. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70582. __extends(ImageProcessingPostProcess, _super);
  70583. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70584. if (camera === void 0) { camera = null; }
  70585. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70586. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70587. _this._fromLinearSpace = true;
  70588. /**
  70589. * Defines cache preventing GC.
  70590. */
  70591. _this._defines = {
  70592. IMAGEPROCESSING: false,
  70593. VIGNETTE: false,
  70594. VIGNETTEBLENDMODEMULTIPLY: false,
  70595. VIGNETTEBLENDMODEOPAQUE: false,
  70596. TONEMAPPING: false,
  70597. CONTRAST: false,
  70598. COLORCURVES: false,
  70599. COLORGRADING: false,
  70600. COLORGRADING3D: false,
  70601. FROMLINEARSPACE: false,
  70602. SAMPLER3DGREENDEPTH: false,
  70603. SAMPLER3DBGRMAP: false,
  70604. IMAGEPROCESSINGPOSTPROCESS: false,
  70605. EXPOSURE: false,
  70606. GRAIN: false,
  70607. };
  70608. // Setup the configuration as forced by the constructor. This would then not force the
  70609. // scene materials output in linear space and let untouched the default forward pass.
  70610. if (imageProcessingConfiguration) {
  70611. imageProcessingConfiguration.applyByPostProcess = true;
  70612. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70613. // This will cause the shader to be compiled
  70614. _this.fromLinearSpace = false;
  70615. }
  70616. else {
  70617. _this._attachImageProcessingConfiguration(null, true);
  70618. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70619. }
  70620. _this.onApply = function (effect) {
  70621. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70622. };
  70623. return _this;
  70624. }
  70625. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70626. /**
  70627. * Gets the image processing configuration used either in this material.
  70628. */
  70629. get: function () {
  70630. return this._imageProcessingConfiguration;
  70631. },
  70632. /**
  70633. * Sets the Default image processing configuration used either in the this material.
  70634. *
  70635. * If sets to null, the scene one is in use.
  70636. */
  70637. set: function (value) {
  70638. this._attachImageProcessingConfiguration(value);
  70639. },
  70640. enumerable: true,
  70641. configurable: true
  70642. });
  70643. /**
  70644. * Attaches a new image processing configuration to the PBR Material.
  70645. * @param configuration
  70646. */
  70647. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70648. var _this = this;
  70649. if (doNotBuild === void 0) { doNotBuild = false; }
  70650. if (configuration === this._imageProcessingConfiguration) {
  70651. return;
  70652. }
  70653. // Detaches observer.
  70654. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70655. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70656. }
  70657. // Pick the scene configuration if needed.
  70658. if (!configuration) {
  70659. var scene = null;
  70660. var engine = this.getEngine();
  70661. var camera = this.getCamera();
  70662. if (camera) {
  70663. scene = camera.getScene();
  70664. }
  70665. else if (engine && engine.scenes) {
  70666. var scenes = engine.scenes;
  70667. scene = scenes[scenes.length - 1];
  70668. }
  70669. else {
  70670. scene = BABYLON.Engine.LastCreatedScene;
  70671. }
  70672. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70673. }
  70674. else {
  70675. this._imageProcessingConfiguration = configuration;
  70676. }
  70677. // Attaches observer.
  70678. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70679. _this._updateParameters();
  70680. });
  70681. // Ensure the effect will be rebuilt.
  70682. if (!doNotBuild) {
  70683. this._updateParameters();
  70684. }
  70685. };
  70686. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70687. /**
  70688. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70689. */
  70690. get: function () {
  70691. return this.imageProcessingConfiguration.colorCurves;
  70692. },
  70693. /**
  70694. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70695. */
  70696. set: function (value) {
  70697. this.imageProcessingConfiguration.colorCurves = value;
  70698. },
  70699. enumerable: true,
  70700. configurable: true
  70701. });
  70702. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70703. /**
  70704. * Gets wether the color curves effect is enabled.
  70705. */
  70706. get: function () {
  70707. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70708. },
  70709. /**
  70710. * Sets wether the color curves effect is enabled.
  70711. */
  70712. set: function (value) {
  70713. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70714. },
  70715. enumerable: true,
  70716. configurable: true
  70717. });
  70718. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70719. /**
  70720. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70721. */
  70722. get: function () {
  70723. return this.imageProcessingConfiguration.colorGradingTexture;
  70724. },
  70725. /**
  70726. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70727. */
  70728. set: function (value) {
  70729. this.imageProcessingConfiguration.colorGradingTexture = value;
  70730. },
  70731. enumerable: true,
  70732. configurable: true
  70733. });
  70734. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70735. /**
  70736. * Gets wether the color grading effect is enabled.
  70737. */
  70738. get: function () {
  70739. return this.imageProcessingConfiguration.colorGradingEnabled;
  70740. },
  70741. /**
  70742. * Gets wether the color grading effect is enabled.
  70743. */
  70744. set: function (value) {
  70745. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70746. },
  70747. enumerable: true,
  70748. configurable: true
  70749. });
  70750. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70751. /**
  70752. * Gets exposure used in the effect.
  70753. */
  70754. get: function () {
  70755. return this.imageProcessingConfiguration.exposure;
  70756. },
  70757. /**
  70758. * Sets exposure used in the effect.
  70759. */
  70760. set: function (value) {
  70761. this.imageProcessingConfiguration.exposure = value;
  70762. },
  70763. enumerable: true,
  70764. configurable: true
  70765. });
  70766. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70767. /**
  70768. * Gets wether tonemapping is enabled or not.
  70769. */
  70770. get: function () {
  70771. return this._imageProcessingConfiguration.toneMappingEnabled;
  70772. },
  70773. /**
  70774. * Sets wether tonemapping is enabled or not
  70775. */
  70776. set: function (value) {
  70777. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70778. },
  70779. enumerable: true,
  70780. configurable: true
  70781. });
  70782. ;
  70783. ;
  70784. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70785. /**
  70786. * Gets contrast used in the effect.
  70787. */
  70788. get: function () {
  70789. return this.imageProcessingConfiguration.contrast;
  70790. },
  70791. /**
  70792. * Sets contrast used in the effect.
  70793. */
  70794. set: function (value) {
  70795. this.imageProcessingConfiguration.contrast = value;
  70796. },
  70797. enumerable: true,
  70798. configurable: true
  70799. });
  70800. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70801. /**
  70802. * Gets Vignette stretch size.
  70803. */
  70804. get: function () {
  70805. return this.imageProcessingConfiguration.vignetteStretch;
  70806. },
  70807. /**
  70808. * Sets Vignette stretch size.
  70809. */
  70810. set: function (value) {
  70811. this.imageProcessingConfiguration.vignetteStretch = value;
  70812. },
  70813. enumerable: true,
  70814. configurable: true
  70815. });
  70816. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70817. /**
  70818. * Gets Vignette centre X Offset.
  70819. */
  70820. get: function () {
  70821. return this.imageProcessingConfiguration.vignetteCentreX;
  70822. },
  70823. /**
  70824. * Sets Vignette centre X Offset.
  70825. */
  70826. set: function (value) {
  70827. this.imageProcessingConfiguration.vignetteCentreX = value;
  70828. },
  70829. enumerable: true,
  70830. configurable: true
  70831. });
  70832. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70833. /**
  70834. * Gets Vignette centre Y Offset.
  70835. */
  70836. get: function () {
  70837. return this.imageProcessingConfiguration.vignetteCentreY;
  70838. },
  70839. /**
  70840. * Sets Vignette centre Y Offset.
  70841. */
  70842. set: function (value) {
  70843. this.imageProcessingConfiguration.vignetteCentreY = value;
  70844. },
  70845. enumerable: true,
  70846. configurable: true
  70847. });
  70848. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70849. /**
  70850. * Gets Vignette weight or intensity of the vignette effect.
  70851. */
  70852. get: function () {
  70853. return this.imageProcessingConfiguration.vignetteWeight;
  70854. },
  70855. /**
  70856. * Sets Vignette weight or intensity of the vignette effect.
  70857. */
  70858. set: function (value) {
  70859. this.imageProcessingConfiguration.vignetteWeight = value;
  70860. },
  70861. enumerable: true,
  70862. configurable: true
  70863. });
  70864. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70865. /**
  70866. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70867. * if vignetteEnabled is set to true.
  70868. */
  70869. get: function () {
  70870. return this.imageProcessingConfiguration.vignetteColor;
  70871. },
  70872. /**
  70873. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70874. * if vignetteEnabled is set to true.
  70875. */
  70876. set: function (value) {
  70877. this.imageProcessingConfiguration.vignetteColor = value;
  70878. },
  70879. enumerable: true,
  70880. configurable: true
  70881. });
  70882. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70883. /**
  70884. * Gets Camera field of view used by the Vignette effect.
  70885. */
  70886. get: function () {
  70887. return this.imageProcessingConfiguration.vignetteCameraFov;
  70888. },
  70889. /**
  70890. * Sets Camera field of view used by the Vignette effect.
  70891. */
  70892. set: function (value) {
  70893. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70894. },
  70895. enumerable: true,
  70896. configurable: true
  70897. });
  70898. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70899. /**
  70900. * Gets the vignette blend mode allowing different kind of effect.
  70901. */
  70902. get: function () {
  70903. return this.imageProcessingConfiguration.vignetteBlendMode;
  70904. },
  70905. /**
  70906. * Sets the vignette blend mode allowing different kind of effect.
  70907. */
  70908. set: function (value) {
  70909. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70910. },
  70911. enumerable: true,
  70912. configurable: true
  70913. });
  70914. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70915. /**
  70916. * Gets wether the vignette effect is enabled.
  70917. */
  70918. get: function () {
  70919. return this.imageProcessingConfiguration.vignetteEnabled;
  70920. },
  70921. /**
  70922. * Sets wether the vignette effect is enabled.
  70923. */
  70924. set: function (value) {
  70925. this.imageProcessingConfiguration.vignetteEnabled = value;
  70926. },
  70927. enumerable: true,
  70928. configurable: true
  70929. });
  70930. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70931. /**
  70932. * Gets wether the grain effect is enabled.
  70933. */
  70934. get: function () {
  70935. return this.imageProcessingConfiguration.grainEnabled;
  70936. },
  70937. /**
  70938. * Sets wether the grain effect is enabled.
  70939. */
  70940. set: function (value) {
  70941. this.imageProcessingConfiguration.grainEnabled = value;
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70947. /**
  70948. * Gets the grain effect's intensity.
  70949. */
  70950. get: function () {
  70951. return this.imageProcessingConfiguration.grainIntensity;
  70952. },
  70953. /**
  70954. * Sets the grain effect's intensity.
  70955. */
  70956. set: function (value) {
  70957. this.imageProcessingConfiguration.grainIntensity = value;
  70958. },
  70959. enumerable: true,
  70960. configurable: true
  70961. });
  70962. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70963. /**
  70964. * Gets wether the grain effect is animated.
  70965. */
  70966. get: function () {
  70967. return this.imageProcessingConfiguration.grainAnimated;
  70968. },
  70969. /**
  70970. * Sets wether the grain effect is animated.
  70971. */
  70972. set: function (value) {
  70973. this.imageProcessingConfiguration.grainAnimated = value;
  70974. },
  70975. enumerable: true,
  70976. configurable: true
  70977. });
  70978. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70979. /**
  70980. * Gets wether the input of the processing is in Gamma or Linear Space.
  70981. */
  70982. get: function () {
  70983. return this._fromLinearSpace;
  70984. },
  70985. /**
  70986. * Sets wether the input of the processing is in Gamma or Linear Space.
  70987. */
  70988. set: function (value) {
  70989. if (this._fromLinearSpace === value) {
  70990. return;
  70991. }
  70992. this._fromLinearSpace = value;
  70993. this._updateParameters();
  70994. },
  70995. enumerable: true,
  70996. configurable: true
  70997. });
  70998. ImageProcessingPostProcess.prototype.getClassName = function () {
  70999. return "ImageProcessingPostProcess";
  71000. };
  71001. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71002. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71003. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71004. var defines = "";
  71005. for (var define in this._defines) {
  71006. if (this._defines[define]) {
  71007. defines += "#define " + define + ";\r\n";
  71008. }
  71009. }
  71010. var samplers = ["textureSampler"];
  71011. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71012. var uniforms = ["scale"];
  71013. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71014. this.updateEffect(defines, uniforms, samplers);
  71015. };
  71016. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71017. _super.prototype.dispose.call(this, camera);
  71018. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71019. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71020. }
  71021. this.imageProcessingConfiguration.applyByPostProcess = false;
  71022. };
  71023. __decorate([
  71024. BABYLON.serialize()
  71025. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71026. return ImageProcessingPostProcess;
  71027. }(BABYLON.PostProcess));
  71028. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71029. })(BABYLON || (BABYLON = {}));
  71030. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71031. var BABYLON;
  71032. (function (BABYLON) {
  71033. var Bone = /** @class */ (function (_super) {
  71034. __extends(Bone, _super);
  71035. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71036. if (parentBone === void 0) { parentBone = null; }
  71037. if (localMatrix === void 0) { localMatrix = null; }
  71038. if (restPose === void 0) { restPose = null; }
  71039. if (baseMatrix === void 0) { baseMatrix = null; }
  71040. if (index === void 0) { index = null; }
  71041. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71042. _this.name = name;
  71043. _this.children = new Array();
  71044. _this.animations = new Array();
  71045. // Set this value to map this bone to a different index in the transform matrices.
  71046. // Set this value to -1 to exclude the bone from the transform matrices.
  71047. _this._index = null;
  71048. _this._worldTransform = new BABYLON.Matrix();
  71049. _this._absoluteTransform = new BABYLON.Matrix();
  71050. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71051. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71052. _this._scaleVector = BABYLON.Vector3.One();
  71053. _this._negateScaleChildren = BABYLON.Vector3.One();
  71054. _this._scalingDeterminant = 1;
  71055. _this._skeleton = skeleton;
  71056. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71057. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71058. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71059. _this._index = index;
  71060. skeleton.bones.push(_this);
  71061. _this.setParent(parentBone, false);
  71062. _this._updateDifferenceMatrix();
  71063. return _this;
  71064. }
  71065. Object.defineProperty(Bone.prototype, "_matrix", {
  71066. get: function () {
  71067. return this._localMatrix;
  71068. },
  71069. set: function (val) {
  71070. if (this._localMatrix) {
  71071. this._localMatrix.copyFrom(val);
  71072. }
  71073. else {
  71074. this._localMatrix = val;
  71075. }
  71076. },
  71077. enumerable: true,
  71078. configurable: true
  71079. });
  71080. // Members
  71081. Bone.prototype.getSkeleton = function () {
  71082. return this._skeleton;
  71083. };
  71084. Bone.prototype.getParent = function () {
  71085. return this._parent;
  71086. };
  71087. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71088. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71089. if (this._parent === parent) {
  71090. return;
  71091. }
  71092. if (this._parent) {
  71093. var index = this._parent.children.indexOf(this);
  71094. if (index !== -1) {
  71095. this._parent.children.splice(index, 1);
  71096. }
  71097. }
  71098. this._parent = parent;
  71099. if (this._parent) {
  71100. this._parent.children.push(this);
  71101. }
  71102. if (updateDifferenceMatrix) {
  71103. this._updateDifferenceMatrix();
  71104. }
  71105. };
  71106. Bone.prototype.getLocalMatrix = function () {
  71107. return this._localMatrix;
  71108. };
  71109. Bone.prototype.getBaseMatrix = function () {
  71110. return this._baseMatrix;
  71111. };
  71112. Bone.prototype.getRestPose = function () {
  71113. return this._restPose;
  71114. };
  71115. Bone.prototype.returnToRest = function () {
  71116. this.updateMatrix(this._restPose.clone());
  71117. };
  71118. Bone.prototype.getWorldMatrix = function () {
  71119. return this._worldTransform;
  71120. };
  71121. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71122. return this._invertedAbsoluteTransform;
  71123. };
  71124. Bone.prototype.getAbsoluteTransform = function () {
  71125. return this._absoluteTransform;
  71126. };
  71127. Object.defineProperty(Bone.prototype, "position", {
  71128. // Properties (matches AbstractMesh properties)
  71129. get: function () {
  71130. return this.getPosition();
  71131. },
  71132. set: function (newPosition) {
  71133. this.setPosition(newPosition);
  71134. },
  71135. enumerable: true,
  71136. configurable: true
  71137. });
  71138. Object.defineProperty(Bone.prototype, "rotation", {
  71139. get: function () {
  71140. return this.getRotation();
  71141. },
  71142. set: function (newRotation) {
  71143. this.setRotation(newRotation);
  71144. },
  71145. enumerable: true,
  71146. configurable: true
  71147. });
  71148. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71149. get: function () {
  71150. return this.getRotationQuaternion();
  71151. },
  71152. set: function (newRotation) {
  71153. this.setRotationQuaternion(newRotation);
  71154. },
  71155. enumerable: true,
  71156. configurable: true
  71157. });
  71158. Object.defineProperty(Bone.prototype, "scaling", {
  71159. get: function () {
  71160. return this.getScale();
  71161. },
  71162. set: function (newScaling) {
  71163. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71164. },
  71165. enumerable: true,
  71166. configurable: true
  71167. });
  71168. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71169. /**
  71170. * Gets the animation properties override
  71171. */
  71172. get: function () {
  71173. return this._skeleton.animationPropertiesOverride;
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. // Methods
  71179. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71180. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71181. this._baseMatrix = matrix.clone();
  71182. this._localMatrix = matrix.clone();
  71183. this._skeleton._markAsDirty();
  71184. if (updateDifferenceMatrix) {
  71185. this._updateDifferenceMatrix();
  71186. }
  71187. };
  71188. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71189. if (!rootMatrix) {
  71190. rootMatrix = this._baseMatrix;
  71191. }
  71192. if (this._parent) {
  71193. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71194. }
  71195. else {
  71196. this._absoluteTransform.copyFrom(rootMatrix);
  71197. }
  71198. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71199. for (var index = 0; index < this.children.length; index++) {
  71200. this.children[index]._updateDifferenceMatrix();
  71201. }
  71202. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71203. };
  71204. Bone.prototype.markAsDirty = function () {
  71205. this._currentRenderId++;
  71206. this._skeleton._markAsDirty();
  71207. };
  71208. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71209. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71210. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71211. // all animation may be coming from a library skeleton, so may need to create animation
  71212. if (this.animations.length === 0) {
  71213. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71214. this.animations[0].setKeys([]);
  71215. }
  71216. // get animation info / verify there is such a range from the source bone
  71217. var sourceRange = source.animations[0].getRange(rangeName);
  71218. if (!sourceRange) {
  71219. return false;
  71220. }
  71221. var from = sourceRange.from;
  71222. var to = sourceRange.to;
  71223. var sourceKeys = source.animations[0].getKeys();
  71224. // rescaling prep
  71225. var sourceBoneLength = source.length;
  71226. var sourceParent = source.getParent();
  71227. var parent = this.getParent();
  71228. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71229. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71230. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71231. var destKeys = this.animations[0].getKeys();
  71232. // loop vars declaration
  71233. var orig;
  71234. var origTranslation;
  71235. var mat;
  71236. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71237. orig = sourceKeys[key];
  71238. if (orig.frame >= from && orig.frame <= to) {
  71239. if (rescaleAsRequired) {
  71240. mat = orig.value.clone();
  71241. // scale based on parent ratio, when bone has parent
  71242. if (parentScalingReqd) {
  71243. origTranslation = mat.getTranslation();
  71244. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71245. // scale based on skeleton dimension ratio when root bone, and value is passed
  71246. }
  71247. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71248. origTranslation = mat.getTranslation();
  71249. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71250. // use original when root bone, and no data for skelDimensionsRatio
  71251. }
  71252. else {
  71253. mat = orig.value;
  71254. }
  71255. }
  71256. else {
  71257. mat = orig.value;
  71258. }
  71259. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71260. }
  71261. }
  71262. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71263. return true;
  71264. };
  71265. /**
  71266. * Translate the bone in local or world space.
  71267. * @param vec The amount to translate the bone.
  71268. * @param space The space that the translation is in.
  71269. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71270. */
  71271. Bone.prototype.translate = function (vec, space, mesh) {
  71272. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71273. var lm = this.getLocalMatrix();
  71274. if (space == BABYLON.Space.LOCAL) {
  71275. lm.m[12] += vec.x;
  71276. lm.m[13] += vec.y;
  71277. lm.m[14] += vec.z;
  71278. }
  71279. else {
  71280. var wm = null;
  71281. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71282. if (mesh) {
  71283. wm = mesh.getWorldMatrix();
  71284. }
  71285. this._skeleton.computeAbsoluteTransforms();
  71286. var tmat = Bone._tmpMats[0];
  71287. var tvec = Bone._tmpVecs[0];
  71288. if (this._parent) {
  71289. if (mesh && wm) {
  71290. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71291. tmat.multiplyToRef(wm, tmat);
  71292. }
  71293. else {
  71294. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71295. }
  71296. }
  71297. tmat.m[12] = 0;
  71298. tmat.m[13] = 0;
  71299. tmat.m[14] = 0;
  71300. tmat.invert();
  71301. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71302. lm.m[12] += tvec.x;
  71303. lm.m[13] += tvec.y;
  71304. lm.m[14] += tvec.z;
  71305. }
  71306. this.markAsDirty();
  71307. };
  71308. /**
  71309. * Set the postion of the bone in local or world space.
  71310. * @param position The position to set the bone.
  71311. * @param space The space that the position is in.
  71312. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71313. */
  71314. Bone.prototype.setPosition = function (position, space, mesh) {
  71315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71316. var lm = this.getLocalMatrix();
  71317. if (space == BABYLON.Space.LOCAL) {
  71318. lm.m[12] = position.x;
  71319. lm.m[13] = position.y;
  71320. lm.m[14] = position.z;
  71321. }
  71322. else {
  71323. var wm = null;
  71324. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71325. if (mesh) {
  71326. wm = mesh.getWorldMatrix();
  71327. }
  71328. this._skeleton.computeAbsoluteTransforms();
  71329. var tmat = Bone._tmpMats[0];
  71330. var vec = Bone._tmpVecs[0];
  71331. if (this._parent) {
  71332. if (mesh && wm) {
  71333. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71334. tmat.multiplyToRef(wm, tmat);
  71335. }
  71336. else {
  71337. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71338. }
  71339. }
  71340. tmat.invert();
  71341. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71342. lm.m[12] = vec.x;
  71343. lm.m[13] = vec.y;
  71344. lm.m[14] = vec.z;
  71345. }
  71346. this.markAsDirty();
  71347. };
  71348. /**
  71349. * Set the absolute postion of the bone (world space).
  71350. * @param position The position to set the bone.
  71351. * @param mesh The mesh that this bone is attached to.
  71352. */
  71353. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71354. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71355. };
  71356. /**
  71357. * Set the scale of the bone on the x, y and z axes.
  71358. * @param x The scale of the bone on the x axis.
  71359. * @param x The scale of the bone on the y axis.
  71360. * @param z The scale of the bone on the z axis.
  71361. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71362. */
  71363. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71364. if (scaleChildren === void 0) { scaleChildren = false; }
  71365. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71366. if (!scaleChildren) {
  71367. this._negateScaleChildren.x = 1 / x;
  71368. this._negateScaleChildren.y = 1 / y;
  71369. this._negateScaleChildren.z = 1 / z;
  71370. }
  71371. this._syncScaleVector();
  71372. }
  71373. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71374. };
  71375. /**
  71376. * Scale the bone on the x, y and z axes.
  71377. * @param x The amount to scale the bone on the x axis.
  71378. * @param x The amount to scale the bone on the y axis.
  71379. * @param z The amount to scale the bone on the z axis.
  71380. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71381. */
  71382. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71383. if (scaleChildren === void 0) { scaleChildren = false; }
  71384. var locMat = this.getLocalMatrix();
  71385. var origLocMat = Bone._tmpMats[0];
  71386. origLocMat.copyFrom(locMat);
  71387. var origLocMatInv = Bone._tmpMats[1];
  71388. origLocMatInv.copyFrom(origLocMat);
  71389. origLocMatInv.invert();
  71390. var scaleMat = Bone._tmpMats[2];
  71391. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71392. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71393. this._scaleVector.x *= x;
  71394. this._scaleVector.y *= y;
  71395. this._scaleVector.z *= z;
  71396. locMat.multiplyToRef(origLocMatInv, locMat);
  71397. locMat.multiplyToRef(scaleMat, locMat);
  71398. locMat.multiplyToRef(origLocMat, locMat);
  71399. var parent = this.getParent();
  71400. if (parent) {
  71401. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71402. }
  71403. else {
  71404. this.getAbsoluteTransform().copyFrom(locMat);
  71405. }
  71406. var len = this.children.length;
  71407. scaleMat.invert();
  71408. for (var i = 0; i < len; i++) {
  71409. var child = this.children[i];
  71410. var cm = child.getLocalMatrix();
  71411. cm.multiplyToRef(scaleMat, cm);
  71412. var lm = child.getLocalMatrix();
  71413. lm.m[12] *= x;
  71414. lm.m[13] *= y;
  71415. lm.m[14] *= z;
  71416. }
  71417. this.computeAbsoluteTransforms();
  71418. if (scaleChildren) {
  71419. for (var i = 0; i < len; i++) {
  71420. this.children[i].scale(x, y, z, scaleChildren);
  71421. }
  71422. }
  71423. this.markAsDirty();
  71424. };
  71425. /**
  71426. * Set the yaw, pitch, and roll of the bone in local or world space.
  71427. * @param yaw The rotation of the bone on the y axis.
  71428. * @param pitch The rotation of the bone on the x axis.
  71429. * @param roll The rotation of the bone on the z axis.
  71430. * @param space The space that the axes of rotation are in.
  71431. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71432. */
  71433. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71434. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71435. var rotMat = Bone._tmpMats[0];
  71436. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71437. var rotMatInv = Bone._tmpMats[1];
  71438. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71439. rotMatInv.multiplyToRef(rotMat, rotMat);
  71440. this._rotateWithMatrix(rotMat, space, mesh);
  71441. };
  71442. /**
  71443. * Rotate the bone on an axis in local or world space.
  71444. * @param axis The axis to rotate the bone on.
  71445. * @param amount The amount to rotate the bone.
  71446. * @param space The space that the axis is in.
  71447. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71448. */
  71449. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71450. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71451. var rmat = Bone._tmpMats[0];
  71452. rmat.m[12] = 0;
  71453. rmat.m[13] = 0;
  71454. rmat.m[14] = 0;
  71455. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71456. this._rotateWithMatrix(rmat, space, mesh);
  71457. };
  71458. /**
  71459. * Set the rotation of the bone to a particular axis angle in local or world space.
  71460. * @param axis The axis to rotate the bone on.
  71461. * @param angle The angle that the bone should be rotated to.
  71462. * @param space The space that the axis is in.
  71463. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71464. */
  71465. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71467. var rotMat = Bone._tmpMats[0];
  71468. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71469. var rotMatInv = Bone._tmpMats[1];
  71470. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71471. rotMatInv.multiplyToRef(rotMat, rotMat);
  71472. this._rotateWithMatrix(rotMat, space, mesh);
  71473. };
  71474. /**
  71475. * Set the euler rotation of the bone in local of world space.
  71476. * @param rotation The euler rotation that the bone should be set to.
  71477. * @param space The space that the rotation is in.
  71478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71479. */
  71480. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71481. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71482. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71483. };
  71484. /**
  71485. * Set the quaternion rotation of the bone in local of world space.
  71486. * @param quat The quaternion rotation that the bone should be set to.
  71487. * @param space The space that the rotation is in.
  71488. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71489. */
  71490. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71492. var rotMatInv = Bone._tmpMats[0];
  71493. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71494. var rotMat = Bone._tmpMats[1];
  71495. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71496. rotMatInv.multiplyToRef(rotMat, rotMat);
  71497. this._rotateWithMatrix(rotMat, space, mesh);
  71498. };
  71499. /**
  71500. * Set the rotation matrix of the bone in local of world space.
  71501. * @param rotMat The rotation matrix that the bone should be set to.
  71502. * @param space The space that the rotation is in.
  71503. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71504. */
  71505. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71507. var rotMatInv = Bone._tmpMats[0];
  71508. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71509. var rotMat2 = Bone._tmpMats[1];
  71510. rotMat2.copyFrom(rotMat);
  71511. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71512. this._rotateWithMatrix(rotMat2, space, mesh);
  71513. };
  71514. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71516. var lmat = this.getLocalMatrix();
  71517. var lx = lmat.m[12];
  71518. var ly = lmat.m[13];
  71519. var lz = lmat.m[14];
  71520. var parent = this.getParent();
  71521. var parentScale = Bone._tmpMats[3];
  71522. var parentScaleInv = Bone._tmpMats[4];
  71523. if (parent) {
  71524. if (space == BABYLON.Space.WORLD) {
  71525. if (mesh) {
  71526. parentScale.copyFrom(mesh.getWorldMatrix());
  71527. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71528. }
  71529. else {
  71530. parentScale.copyFrom(parent.getAbsoluteTransform());
  71531. }
  71532. }
  71533. else {
  71534. parentScale = parent._scaleMatrix;
  71535. }
  71536. parentScaleInv.copyFrom(parentScale);
  71537. parentScaleInv.invert();
  71538. lmat.multiplyToRef(parentScale, lmat);
  71539. lmat.multiplyToRef(rmat, lmat);
  71540. lmat.multiplyToRef(parentScaleInv, lmat);
  71541. }
  71542. else {
  71543. if (space == BABYLON.Space.WORLD && mesh) {
  71544. parentScale.copyFrom(mesh.getWorldMatrix());
  71545. parentScaleInv.copyFrom(parentScale);
  71546. parentScaleInv.invert();
  71547. lmat.multiplyToRef(parentScale, lmat);
  71548. lmat.multiplyToRef(rmat, lmat);
  71549. lmat.multiplyToRef(parentScaleInv, lmat);
  71550. }
  71551. else {
  71552. lmat.multiplyToRef(rmat, lmat);
  71553. }
  71554. }
  71555. lmat.m[12] = lx;
  71556. lmat.m[13] = ly;
  71557. lmat.m[14] = lz;
  71558. this.computeAbsoluteTransforms();
  71559. this.markAsDirty();
  71560. };
  71561. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71562. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71563. if (space == BABYLON.Space.WORLD) {
  71564. var scaleMatrix = Bone._tmpMats[2];
  71565. scaleMatrix.copyFrom(this._scaleMatrix);
  71566. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71567. if (mesh) {
  71568. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71569. var meshScale = Bone._tmpMats[3];
  71570. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71571. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71572. }
  71573. rotMatInv.invert();
  71574. scaleMatrix.m[0] *= this._scalingDeterminant;
  71575. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71576. }
  71577. else {
  71578. rotMatInv.copyFrom(this.getLocalMatrix());
  71579. rotMatInv.invert();
  71580. var scaleMatrix = Bone._tmpMats[2];
  71581. scaleMatrix.copyFrom(this._scaleMatrix);
  71582. if (this._parent) {
  71583. var pscaleMatrix = Bone._tmpMats[3];
  71584. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71585. pscaleMatrix.invert();
  71586. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71587. }
  71588. else {
  71589. scaleMatrix.m[0] *= this._scalingDeterminant;
  71590. }
  71591. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71592. }
  71593. };
  71594. /**
  71595. * Get the scale of the bone
  71596. * @returns the scale of the bone
  71597. */
  71598. Bone.prototype.getScale = function () {
  71599. return this._scaleVector.clone();
  71600. };
  71601. /**
  71602. * Copy the scale of the bone to a vector3.
  71603. * @param result The vector3 to copy the scale to
  71604. */
  71605. Bone.prototype.getScaleToRef = function (result) {
  71606. result.copyFrom(this._scaleVector);
  71607. };
  71608. /**
  71609. * Get the position of the bone in local or world space.
  71610. * @param space The space that the returned position is in.
  71611. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71612. * @returns The position of the bone
  71613. */
  71614. Bone.prototype.getPosition = function (space, mesh) {
  71615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71616. if (mesh === void 0) { mesh = null; }
  71617. var pos = BABYLON.Vector3.Zero();
  71618. this.getPositionToRef(space, mesh, pos);
  71619. return pos;
  71620. };
  71621. /**
  71622. * Copy the position of the bone to a vector3 in local or world space.
  71623. * @param space The space that the returned position is in.
  71624. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71625. * @param result The vector3 to copy the position to.
  71626. */
  71627. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71629. if (space == BABYLON.Space.LOCAL) {
  71630. var lm = this.getLocalMatrix();
  71631. result.x = lm.m[12];
  71632. result.y = lm.m[13];
  71633. result.z = lm.m[14];
  71634. }
  71635. else {
  71636. var wm = null;
  71637. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71638. if (mesh) {
  71639. wm = mesh.getWorldMatrix();
  71640. }
  71641. this._skeleton.computeAbsoluteTransforms();
  71642. var tmat = Bone._tmpMats[0];
  71643. if (mesh && wm) {
  71644. tmat.copyFrom(this.getAbsoluteTransform());
  71645. tmat.multiplyToRef(wm, tmat);
  71646. }
  71647. else {
  71648. tmat = this.getAbsoluteTransform();
  71649. }
  71650. result.x = tmat.m[12];
  71651. result.y = tmat.m[13];
  71652. result.z = tmat.m[14];
  71653. }
  71654. };
  71655. /**
  71656. * Get the absolute position of the bone (world space).
  71657. * @param mesh The mesh that this bone is attached to.
  71658. * @returns The absolute position of the bone
  71659. */
  71660. Bone.prototype.getAbsolutePosition = function (mesh) {
  71661. if (mesh === void 0) { mesh = null; }
  71662. var pos = BABYLON.Vector3.Zero();
  71663. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71664. return pos;
  71665. };
  71666. /**
  71667. * Copy the absolute position of the bone (world space) to the result param.
  71668. * @param mesh The mesh that this bone is attached to.
  71669. * @param result The vector3 to copy the absolute position to.
  71670. */
  71671. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71672. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71673. };
  71674. /**
  71675. * Compute the absolute transforms of this bone and its children.
  71676. */
  71677. Bone.prototype.computeAbsoluteTransforms = function () {
  71678. if (this._parent) {
  71679. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71680. }
  71681. else {
  71682. this._absoluteTransform.copyFrom(this._localMatrix);
  71683. var poseMatrix = this._skeleton.getPoseMatrix();
  71684. if (poseMatrix) {
  71685. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71686. }
  71687. }
  71688. var children = this.children;
  71689. var len = children.length;
  71690. for (var i = 0; i < len; i++) {
  71691. children[i].computeAbsoluteTransforms();
  71692. }
  71693. };
  71694. Bone.prototype._syncScaleVector = function () {
  71695. var lm = this.getLocalMatrix();
  71696. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71697. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71698. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71699. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71700. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71701. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71702. this._scaleVector.x = xs * Math.sqrt(xsq);
  71703. this._scaleVector.y = ys * Math.sqrt(ysq);
  71704. this._scaleVector.z = zs * Math.sqrt(zsq);
  71705. if (this._parent) {
  71706. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71707. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71708. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71709. }
  71710. 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);
  71711. };
  71712. /**
  71713. * Get the world direction from an axis that is in the local space of the bone.
  71714. * @param localAxis The local direction that is used to compute the world direction.
  71715. * @param mesh The mesh that this bone is attached to.
  71716. * @returns The world direction
  71717. */
  71718. Bone.prototype.getDirection = function (localAxis, mesh) {
  71719. if (mesh === void 0) { mesh = null; }
  71720. var result = BABYLON.Vector3.Zero();
  71721. this.getDirectionToRef(localAxis, mesh, result);
  71722. return result;
  71723. };
  71724. /**
  71725. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71726. * @param localAxis The local direction that is used to compute the world direction.
  71727. * @param mesh The mesh that this bone is attached to.
  71728. * @param result The vector3 that the world direction will be copied to.
  71729. */
  71730. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71731. if (mesh === void 0) { mesh = null; }
  71732. var wm = null;
  71733. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71734. if (mesh) {
  71735. wm = mesh.getWorldMatrix();
  71736. }
  71737. this._skeleton.computeAbsoluteTransforms();
  71738. var mat = Bone._tmpMats[0];
  71739. mat.copyFrom(this.getAbsoluteTransform());
  71740. if (mesh && wm) {
  71741. mat.multiplyToRef(wm, mat);
  71742. }
  71743. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71744. result.normalize();
  71745. };
  71746. /**
  71747. * Get the euler rotation of the bone in local or world space.
  71748. * @param space The space that the rotation should be in.
  71749. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71750. * @returns The euler rotation
  71751. */
  71752. Bone.prototype.getRotation = function (space, mesh) {
  71753. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71754. if (mesh === void 0) { mesh = null; }
  71755. var result = BABYLON.Vector3.Zero();
  71756. this.getRotationToRef(space, mesh, result);
  71757. return result;
  71758. };
  71759. /**
  71760. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71761. * @param space The space that the rotation should be in.
  71762. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71763. * @param result The vector3 that the rotation should be copied to.
  71764. */
  71765. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71767. if (mesh === void 0) { mesh = null; }
  71768. var quat = Bone._tmpQuat;
  71769. this.getRotationQuaternionToRef(space, mesh, quat);
  71770. quat.toEulerAnglesToRef(result);
  71771. };
  71772. /**
  71773. * Get the quaternion rotation of the bone in either local or world space.
  71774. * @param space The space that the rotation should be in.
  71775. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71776. * @returns The quaternion rotation
  71777. */
  71778. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71780. if (mesh === void 0) { mesh = null; }
  71781. var result = BABYLON.Quaternion.Identity();
  71782. this.getRotationQuaternionToRef(space, mesh, result);
  71783. return result;
  71784. };
  71785. /**
  71786. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71787. * @param space The space that the rotation should be in.
  71788. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71789. * @param result The quaternion that the rotation should be copied to.
  71790. */
  71791. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71793. if (mesh === void 0) { mesh = null; }
  71794. if (space == BABYLON.Space.LOCAL) {
  71795. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71796. }
  71797. else {
  71798. var mat = Bone._tmpMats[0];
  71799. var amat = this.getAbsoluteTransform();
  71800. if (mesh) {
  71801. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71802. }
  71803. else {
  71804. mat.copyFrom(amat);
  71805. }
  71806. mat.m[0] *= this._scalingDeterminant;
  71807. mat.m[1] *= this._scalingDeterminant;
  71808. mat.m[2] *= this._scalingDeterminant;
  71809. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71810. }
  71811. };
  71812. /**
  71813. * Get the rotation matrix of the bone in local or world space.
  71814. * @param space The space that the rotation should be in.
  71815. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71816. * @returns The rotation matrix
  71817. */
  71818. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71820. var result = BABYLON.Matrix.Identity();
  71821. this.getRotationMatrixToRef(space, mesh, result);
  71822. return result;
  71823. };
  71824. /**
  71825. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71826. * @param space The space that the rotation should be in.
  71827. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71828. * @param result The quaternion that the rotation should be copied to.
  71829. */
  71830. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71831. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71832. if (space == BABYLON.Space.LOCAL) {
  71833. this.getLocalMatrix().getRotationMatrixToRef(result);
  71834. }
  71835. else {
  71836. var mat = Bone._tmpMats[0];
  71837. var amat = this.getAbsoluteTransform();
  71838. if (mesh) {
  71839. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71840. }
  71841. else {
  71842. mat.copyFrom(amat);
  71843. }
  71844. mat.m[0] *= this._scalingDeterminant;
  71845. mat.m[1] *= this._scalingDeterminant;
  71846. mat.m[2] *= this._scalingDeterminant;
  71847. mat.getRotationMatrixToRef(result);
  71848. }
  71849. };
  71850. /**
  71851. * Get the world position of a point that is in the local space of the bone.
  71852. * @param position The local position
  71853. * @param mesh The mesh that this bone is attached to.
  71854. * @returns The world position
  71855. */
  71856. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71857. if (mesh === void 0) { mesh = null; }
  71858. var result = BABYLON.Vector3.Zero();
  71859. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71860. return result;
  71861. };
  71862. /**
  71863. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71864. * @param position The local position
  71865. * @param mesh The mesh that this bone is attached to.
  71866. * @param result The vector3 that the world position should be copied to.
  71867. */
  71868. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71869. if (mesh === void 0) { mesh = null; }
  71870. var wm = null;
  71871. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71872. if (mesh) {
  71873. wm = mesh.getWorldMatrix();
  71874. }
  71875. this._skeleton.computeAbsoluteTransforms();
  71876. var tmat = Bone._tmpMats[0];
  71877. if (mesh && wm) {
  71878. tmat.copyFrom(this.getAbsoluteTransform());
  71879. tmat.multiplyToRef(wm, tmat);
  71880. }
  71881. else {
  71882. tmat = this.getAbsoluteTransform();
  71883. }
  71884. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71885. };
  71886. /**
  71887. * Get the local position of a point that is in world space.
  71888. * @param position The world position
  71889. * @param mesh The mesh that this bone is attached to.
  71890. * @returns The local position
  71891. */
  71892. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71893. if (mesh === void 0) { mesh = null; }
  71894. var result = BABYLON.Vector3.Zero();
  71895. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71896. return result;
  71897. };
  71898. /**
  71899. * Get the local position of a point that is in world space and copy it to the result param.
  71900. * @param position The world position
  71901. * @param mesh The mesh that this bone is attached to.
  71902. * @param result The vector3 that the local position should be copied to.
  71903. */
  71904. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71905. if (mesh === void 0) { mesh = null; }
  71906. var wm = null;
  71907. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71908. if (mesh) {
  71909. wm = mesh.getWorldMatrix();
  71910. }
  71911. this._skeleton.computeAbsoluteTransforms();
  71912. var tmat = Bone._tmpMats[0];
  71913. tmat.copyFrom(this.getAbsoluteTransform());
  71914. if (mesh && wm) {
  71915. tmat.multiplyToRef(wm, tmat);
  71916. }
  71917. tmat.invert();
  71918. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71919. };
  71920. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71921. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71922. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71923. return Bone;
  71924. }(BABYLON.Node));
  71925. BABYLON.Bone = Bone;
  71926. })(BABYLON || (BABYLON = {}));
  71927. //# sourceMappingURL=babylon.bone.js.map
  71928. var BABYLON;
  71929. (function (BABYLON) {
  71930. var BoneIKController = /** @class */ (function () {
  71931. function BoneIKController(mesh, bone, options) {
  71932. this.targetPosition = BABYLON.Vector3.Zero();
  71933. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71934. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71935. this.poleAngle = 0;
  71936. this.slerpAmount = 1;
  71937. this._bone1Quat = BABYLON.Quaternion.Identity();
  71938. this._bone1Mat = BABYLON.Matrix.Identity();
  71939. this._bone2Ang = Math.PI;
  71940. this._maxAngle = Math.PI;
  71941. this._rightHandedSystem = false;
  71942. this._bendAxis = BABYLON.Vector3.Right();
  71943. this._slerping = false;
  71944. this._adjustRoll = 0;
  71945. this._bone2 = bone;
  71946. this._bone1 = bone.getParent();
  71947. if (!this._bone1) {
  71948. return;
  71949. }
  71950. this.mesh = mesh;
  71951. var bonePos = bone.getPosition();
  71952. if (bone.getAbsoluteTransform().determinant() > 0) {
  71953. this._rightHandedSystem = true;
  71954. this._bendAxis.x = 0;
  71955. this._bendAxis.y = 0;
  71956. this._bendAxis.z = -1;
  71957. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71958. this._adjustRoll = Math.PI * .5;
  71959. this._bendAxis.z = 1;
  71960. }
  71961. }
  71962. if (this._bone1.length) {
  71963. var boneScale1 = this._bone1.getScale();
  71964. var boneScale2 = this._bone2.getScale();
  71965. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71966. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71967. }
  71968. else if (this._bone1.children[0]) {
  71969. mesh.computeWorldMatrix(true);
  71970. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71971. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71972. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71973. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71974. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71975. }
  71976. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71977. this.maxAngle = Math.PI;
  71978. if (options) {
  71979. if (options.targetMesh) {
  71980. this.targetMesh = options.targetMesh;
  71981. this.targetMesh.computeWorldMatrix(true);
  71982. }
  71983. if (options.poleTargetMesh) {
  71984. this.poleTargetMesh = options.poleTargetMesh;
  71985. this.poleTargetMesh.computeWorldMatrix(true);
  71986. }
  71987. else if (options.poleTargetBone) {
  71988. this.poleTargetBone = options.poleTargetBone;
  71989. }
  71990. else if (this._bone1.getParent()) {
  71991. this.poleTargetBone = this._bone1.getParent();
  71992. }
  71993. if (options.poleTargetLocalOffset) {
  71994. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71995. }
  71996. if (options.poleAngle) {
  71997. this.poleAngle = options.poleAngle;
  71998. }
  71999. if (options.bendAxis) {
  72000. this._bendAxis.copyFrom(options.bendAxis);
  72001. }
  72002. if (options.maxAngle) {
  72003. this.maxAngle = options.maxAngle;
  72004. }
  72005. if (options.slerpAmount) {
  72006. this.slerpAmount = options.slerpAmount;
  72007. }
  72008. }
  72009. }
  72010. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72011. get: function () {
  72012. return this._maxAngle;
  72013. },
  72014. set: function (value) {
  72015. this._setMaxAngle(value);
  72016. },
  72017. enumerable: true,
  72018. configurable: true
  72019. });
  72020. BoneIKController.prototype._setMaxAngle = function (ang) {
  72021. if (ang < 0) {
  72022. ang = 0;
  72023. }
  72024. if (ang > Math.PI || ang == undefined) {
  72025. ang = Math.PI;
  72026. }
  72027. this._maxAngle = ang;
  72028. var a = this._bone1Length;
  72029. var b = this._bone2Length;
  72030. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72031. };
  72032. BoneIKController.prototype.update = function () {
  72033. var bone1 = this._bone1;
  72034. if (!bone1) {
  72035. return;
  72036. }
  72037. var target = this.targetPosition;
  72038. var poleTarget = this.poleTargetPosition;
  72039. var mat1 = BoneIKController._tmpMats[0];
  72040. var mat2 = BoneIKController._tmpMats[1];
  72041. if (this.targetMesh) {
  72042. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72043. }
  72044. if (this.poleTargetBone) {
  72045. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72046. }
  72047. else if (this.poleTargetMesh) {
  72048. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72049. }
  72050. var bonePos = BoneIKController._tmpVecs[0];
  72051. var zaxis = BoneIKController._tmpVecs[1];
  72052. var xaxis = BoneIKController._tmpVecs[2];
  72053. var yaxis = BoneIKController._tmpVecs[3];
  72054. var upAxis = BoneIKController._tmpVecs[4];
  72055. var _tmpQuat = BoneIKController._tmpQuat;
  72056. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72057. poleTarget.subtractToRef(bonePos, upAxis);
  72058. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72059. upAxis.y = 1;
  72060. }
  72061. else {
  72062. upAxis.normalize();
  72063. }
  72064. target.subtractToRef(bonePos, yaxis);
  72065. yaxis.normalize();
  72066. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72067. zaxis.normalize();
  72068. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72069. xaxis.normalize();
  72070. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72071. var a = this._bone1Length;
  72072. var b = this._bone2Length;
  72073. var c = BABYLON.Vector3.Distance(bonePos, target);
  72074. if (this._maxReach > 0) {
  72075. c = Math.min(this._maxReach, c);
  72076. }
  72077. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72078. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72079. if (acosa > 1) {
  72080. acosa = 1;
  72081. }
  72082. if (acosb > 1) {
  72083. acosb = 1;
  72084. }
  72085. if (acosa < -1) {
  72086. acosa = -1;
  72087. }
  72088. if (acosb < -1) {
  72089. acosb = -1;
  72090. }
  72091. var angA = Math.acos(acosa);
  72092. var angB = Math.acos(acosb);
  72093. var angC = -angA - angB;
  72094. if (this._rightHandedSystem) {
  72095. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72096. mat2.multiplyToRef(mat1, mat1);
  72097. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72098. mat2.multiplyToRef(mat1, mat1);
  72099. }
  72100. else {
  72101. var _tmpVec = BoneIKController._tmpVecs[5];
  72102. _tmpVec.copyFrom(this._bendAxis);
  72103. _tmpVec.x *= -1;
  72104. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72105. mat2.multiplyToRef(mat1, mat1);
  72106. }
  72107. if (this.poleAngle) {
  72108. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72109. mat1.multiplyToRef(mat2, mat1);
  72110. }
  72111. if (this._bone1) {
  72112. if (this.slerpAmount < 1) {
  72113. if (!this._slerping) {
  72114. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72115. }
  72116. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72117. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72118. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72119. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72120. this._slerping = true;
  72121. }
  72122. else {
  72123. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72124. this._bone1Mat.copyFrom(mat1);
  72125. this._slerping = false;
  72126. }
  72127. }
  72128. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72129. this._bone2Ang = angC;
  72130. };
  72131. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72132. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72133. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72134. return BoneIKController;
  72135. }());
  72136. BABYLON.BoneIKController = BoneIKController;
  72137. })(BABYLON || (BABYLON = {}));
  72138. //# sourceMappingURL=babylon.boneIKController.js.map
  72139. var BABYLON;
  72140. (function (BABYLON) {
  72141. var BoneLookController = /** @class */ (function () {
  72142. /**
  72143. * Create a BoneLookController
  72144. * @param mesh the mesh that the bone belongs to
  72145. * @param bone the bone that will be looking to the target
  72146. * @param target the target Vector3 to look at
  72147. * @param settings optional settings:
  72148. * - maxYaw: the maximum angle the bone will yaw to
  72149. * - minYaw: the minimum angle the bone will yaw to
  72150. * - maxPitch: the maximum angle the bone will pitch to
  72151. * - minPitch: the minimum angle the bone will yaw to
  72152. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72153. * - upAxis: the up axis of the coordinate system
  72154. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72155. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72156. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72157. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72158. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72159. * - adjustRoll: used to make an adjustment to the roll of the bone
  72160. **/
  72161. function BoneLookController(mesh, bone, target, options) {
  72162. /**
  72163. * The up axis of the coordinate system that is used when the bone is rotated.
  72164. */
  72165. this.upAxis = BABYLON.Vector3.Up();
  72166. /**
  72167. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72168. */
  72169. this.upAxisSpace = BABYLON.Space.LOCAL;
  72170. /**
  72171. * Used to make an adjustment to the yaw of the bone.
  72172. */
  72173. this.adjustYaw = 0;
  72174. /**
  72175. * Used to make an adjustment to the pitch of the bone.
  72176. */
  72177. this.adjustPitch = 0;
  72178. /**
  72179. * Used to make an adjustment to the roll of the bone.
  72180. */
  72181. this.adjustRoll = 0;
  72182. /**
  72183. * 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).
  72184. */
  72185. this.slerpAmount = 1;
  72186. this._boneQuat = BABYLON.Quaternion.Identity();
  72187. this._slerping = false;
  72188. this._firstFrameSkipped = false;
  72189. this._fowardAxis = BABYLON.Vector3.Forward();
  72190. this.mesh = mesh;
  72191. this.bone = bone;
  72192. this.target = target;
  72193. if (options) {
  72194. if (options.adjustYaw) {
  72195. this.adjustYaw = options.adjustYaw;
  72196. }
  72197. if (options.adjustPitch) {
  72198. this.adjustPitch = options.adjustPitch;
  72199. }
  72200. if (options.adjustRoll) {
  72201. this.adjustRoll = options.adjustRoll;
  72202. }
  72203. if (options.maxYaw != null) {
  72204. this.maxYaw = options.maxYaw;
  72205. }
  72206. else {
  72207. this.maxYaw = Math.PI;
  72208. }
  72209. if (options.minYaw != null) {
  72210. this.minYaw = options.minYaw;
  72211. }
  72212. else {
  72213. this.minYaw = -Math.PI;
  72214. }
  72215. if (options.maxPitch != null) {
  72216. this.maxPitch = options.maxPitch;
  72217. }
  72218. else {
  72219. this.maxPitch = Math.PI;
  72220. }
  72221. if (options.minPitch != null) {
  72222. this.minPitch = options.minPitch;
  72223. }
  72224. else {
  72225. this.minPitch = -Math.PI;
  72226. }
  72227. if (options.slerpAmount != null) {
  72228. this.slerpAmount = options.slerpAmount;
  72229. }
  72230. if (options.upAxis != null) {
  72231. this.upAxis = options.upAxis;
  72232. }
  72233. if (options.upAxisSpace != null) {
  72234. this.upAxisSpace = options.upAxisSpace;
  72235. }
  72236. if (options.yawAxis != null || options.pitchAxis != null) {
  72237. var newYawAxis = BABYLON.Axis.Y;
  72238. var newPitchAxis = BABYLON.Axis.X;
  72239. if (options.yawAxis != null) {
  72240. newYawAxis = options.yawAxis.clone();
  72241. newYawAxis.normalize();
  72242. }
  72243. if (options.pitchAxis != null) {
  72244. newPitchAxis = options.pitchAxis.clone();
  72245. newPitchAxis.normalize();
  72246. }
  72247. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72248. this._transformYawPitch = BABYLON.Matrix.Identity();
  72249. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72250. this._transformYawPitchInv = this._transformYawPitch.clone();
  72251. this._transformYawPitch.invert();
  72252. }
  72253. }
  72254. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72255. this.upAxisSpace = BABYLON.Space.LOCAL;
  72256. }
  72257. }
  72258. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72259. /**
  72260. * Get/set the minimum yaw angle that the bone can look to.
  72261. */
  72262. get: function () {
  72263. return this._minYaw;
  72264. },
  72265. set: function (value) {
  72266. this._minYaw = value;
  72267. this._minYawSin = Math.sin(value);
  72268. this._minYawCos = Math.cos(value);
  72269. if (this._maxYaw != null) {
  72270. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72271. this._yawRange = this._maxYaw - this._minYaw;
  72272. }
  72273. },
  72274. enumerable: true,
  72275. configurable: true
  72276. });
  72277. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72278. /**
  72279. * Get/set the maximum yaw angle that the bone can look to.
  72280. */
  72281. get: function () {
  72282. return this._maxYaw;
  72283. },
  72284. set: function (value) {
  72285. this._maxYaw = value;
  72286. this._maxYawSin = Math.sin(value);
  72287. this._maxYawCos = Math.cos(value);
  72288. if (this._minYaw != null) {
  72289. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72290. this._yawRange = this._maxYaw - this._minYaw;
  72291. }
  72292. },
  72293. enumerable: true,
  72294. configurable: true
  72295. });
  72296. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72297. /**
  72298. * Get/set the minimum pitch angle that the bone can look to.
  72299. */
  72300. get: function () {
  72301. return this._minPitch;
  72302. },
  72303. set: function (value) {
  72304. this._minPitch = value;
  72305. this._minPitchTan = Math.tan(value);
  72306. },
  72307. enumerable: true,
  72308. configurable: true
  72309. });
  72310. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72311. /**
  72312. * Get/set the maximum pitch angle that the bone can look to.
  72313. */
  72314. get: function () {
  72315. return this._maxPitch;
  72316. },
  72317. set: function (value) {
  72318. this._maxPitch = value;
  72319. this._maxPitchTan = Math.tan(value);
  72320. },
  72321. enumerable: true,
  72322. configurable: true
  72323. });
  72324. /**
  72325. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72326. */
  72327. BoneLookController.prototype.update = function () {
  72328. //skip the first frame when slerping so that the mesh rotation is correct
  72329. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72330. this._firstFrameSkipped = true;
  72331. return;
  72332. }
  72333. var bone = this.bone;
  72334. var bonePos = BoneLookController._tmpVecs[0];
  72335. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72336. var target = this.target;
  72337. var _tmpMat1 = BoneLookController._tmpMats[0];
  72338. var _tmpMat2 = BoneLookController._tmpMats[1];
  72339. var mesh = this.mesh;
  72340. var parentBone = bone.getParent();
  72341. var upAxis = BoneLookController._tmpVecs[1];
  72342. upAxis.copyFrom(this.upAxis);
  72343. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72344. if (this._transformYawPitch) {
  72345. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72346. }
  72347. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72348. }
  72349. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72350. mesh.getDirectionToRef(upAxis, upAxis);
  72351. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72352. upAxis.normalize();
  72353. }
  72354. }
  72355. var checkYaw = false;
  72356. var checkPitch = false;
  72357. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72358. checkYaw = true;
  72359. }
  72360. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72361. checkPitch = true;
  72362. }
  72363. if (checkYaw || checkPitch) {
  72364. var spaceMat = BoneLookController._tmpMats[2];
  72365. var spaceMatInv = BoneLookController._tmpMats[3];
  72366. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72367. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72368. }
  72369. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72370. spaceMat.copyFrom(mesh.getWorldMatrix());
  72371. }
  72372. else {
  72373. var forwardAxis = BoneLookController._tmpVecs[2];
  72374. forwardAxis.copyFrom(this._fowardAxis);
  72375. if (this._transformYawPitch) {
  72376. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72377. }
  72378. if (parentBone) {
  72379. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72380. }
  72381. else {
  72382. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72383. }
  72384. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72385. rightAxis.normalize();
  72386. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72387. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72388. }
  72389. spaceMat.invertToRef(spaceMatInv);
  72390. var xzlen = null;
  72391. if (checkPitch) {
  72392. var localTarget = BoneLookController._tmpVecs[3];
  72393. target.subtractToRef(bonePos, localTarget);
  72394. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72395. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72396. var pitch = Math.atan2(localTarget.y, xzlen);
  72397. var newPitch = pitch;
  72398. if (pitch > this._maxPitch) {
  72399. localTarget.y = this._maxPitchTan * xzlen;
  72400. newPitch = this._maxPitch;
  72401. }
  72402. else if (pitch < this._minPitch) {
  72403. localTarget.y = this._minPitchTan * xzlen;
  72404. newPitch = this._minPitch;
  72405. }
  72406. if (pitch != newPitch) {
  72407. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72408. localTarget.addInPlace(bonePos);
  72409. target = localTarget;
  72410. }
  72411. }
  72412. if (checkYaw) {
  72413. var localTarget = BoneLookController._tmpVecs[4];
  72414. target.subtractToRef(bonePos, localTarget);
  72415. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72416. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72417. var newYaw = yaw;
  72418. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72419. if (xzlen == null) {
  72420. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72421. }
  72422. if (this._yawRange > Math.PI) {
  72423. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72424. localTarget.z = this._maxYawCos * xzlen;
  72425. localTarget.x = this._maxYawSin * xzlen;
  72426. newYaw = this._maxYaw;
  72427. }
  72428. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72429. localTarget.z = this._minYawCos * xzlen;
  72430. localTarget.x = this._minYawSin * xzlen;
  72431. newYaw = this._minYaw;
  72432. }
  72433. }
  72434. else {
  72435. if (yaw > this._maxYaw) {
  72436. localTarget.z = this._maxYawCos * xzlen;
  72437. localTarget.x = this._maxYawSin * xzlen;
  72438. newYaw = this._maxYaw;
  72439. }
  72440. else if (yaw < this._minYaw) {
  72441. localTarget.z = this._minYawCos * xzlen;
  72442. localTarget.x = this._minYawSin * xzlen;
  72443. newYaw = this._minYaw;
  72444. }
  72445. }
  72446. }
  72447. if (this._slerping && this._yawRange > Math.PI) {
  72448. //are we going to be crossing into the min/max region?
  72449. var boneFwd = BoneLookController._tmpVecs[8];
  72450. boneFwd.copyFrom(BABYLON.Axis.Z);
  72451. if (this._transformYawPitch) {
  72452. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72453. }
  72454. var boneRotMat = BoneLookController._tmpMats[4];
  72455. this._boneQuat.toRotationMatrix(boneRotMat);
  72456. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72457. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72458. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72459. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72460. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72461. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72462. if (angBtwTar > angBtwMidYaw) {
  72463. if (xzlen == null) {
  72464. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72465. }
  72466. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72467. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72468. if (angBtwMin < angBtwMax) {
  72469. newYaw = boneYaw + Math.PI * .75;
  72470. localTarget.z = Math.cos(newYaw) * xzlen;
  72471. localTarget.x = Math.sin(newYaw) * xzlen;
  72472. }
  72473. else {
  72474. newYaw = boneYaw - Math.PI * .75;
  72475. localTarget.z = Math.cos(newYaw) * xzlen;
  72476. localTarget.x = Math.sin(newYaw) * xzlen;
  72477. }
  72478. }
  72479. }
  72480. if (yaw != newYaw) {
  72481. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72482. localTarget.addInPlace(bonePos);
  72483. target = localTarget;
  72484. }
  72485. }
  72486. }
  72487. var zaxis = BoneLookController._tmpVecs[5];
  72488. var xaxis = BoneLookController._tmpVecs[6];
  72489. var yaxis = BoneLookController._tmpVecs[7];
  72490. var _tmpQuat = BoneLookController._tmpQuat;
  72491. target.subtractToRef(bonePos, zaxis);
  72492. zaxis.normalize();
  72493. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72494. xaxis.normalize();
  72495. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72496. yaxis.normalize();
  72497. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72498. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72499. return;
  72500. }
  72501. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72502. return;
  72503. }
  72504. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72505. return;
  72506. }
  72507. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72508. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72509. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72510. }
  72511. if (this.slerpAmount < 1) {
  72512. if (!this._slerping) {
  72513. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72514. }
  72515. if (this._transformYawPitch) {
  72516. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72517. }
  72518. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72519. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72520. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72521. this._slerping = true;
  72522. }
  72523. else {
  72524. if (this._transformYawPitch) {
  72525. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72526. }
  72527. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72528. this._slerping = false;
  72529. }
  72530. };
  72531. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72532. var angDiff = ang2 - ang1;
  72533. angDiff %= Math.PI * 2;
  72534. if (angDiff > Math.PI) {
  72535. angDiff -= Math.PI * 2;
  72536. }
  72537. else if (angDiff < -Math.PI) {
  72538. angDiff += Math.PI * 2;
  72539. }
  72540. return angDiff;
  72541. };
  72542. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72543. ang1 %= (2 * Math.PI);
  72544. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72545. ang2 %= (2 * Math.PI);
  72546. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72547. var ab = 0;
  72548. if (ang1 < ang2) {
  72549. ab = ang2 - ang1;
  72550. }
  72551. else {
  72552. ab = ang1 - ang2;
  72553. }
  72554. if (ab > Math.PI) {
  72555. ab = Math.PI * 2 - ab;
  72556. }
  72557. return ab;
  72558. };
  72559. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72560. ang %= (2 * Math.PI);
  72561. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72562. ang1 %= (2 * Math.PI);
  72563. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72564. ang2 %= (2 * Math.PI);
  72565. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72566. if (ang1 < ang2) {
  72567. if (ang > ang1 && ang < ang2) {
  72568. return true;
  72569. }
  72570. }
  72571. else {
  72572. if (ang > ang2 && ang < ang1) {
  72573. return true;
  72574. }
  72575. }
  72576. return false;
  72577. };
  72578. 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()];
  72579. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72580. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72581. return BoneLookController;
  72582. }());
  72583. BABYLON.BoneLookController = BoneLookController;
  72584. })(BABYLON || (BABYLON = {}));
  72585. //# sourceMappingURL=babylon.boneLookController.js.map
  72586. var BABYLON;
  72587. (function (BABYLON) {
  72588. var Skeleton = /** @class */ (function () {
  72589. function Skeleton(name, id, scene) {
  72590. this.name = name;
  72591. this.id = id;
  72592. this.bones = new Array();
  72593. this.needInitialSkinMatrix = false;
  72594. this._isDirty = true;
  72595. this._meshesWithPoseMatrix = new Array();
  72596. this._identity = BABYLON.Matrix.Identity();
  72597. this._ranges = {};
  72598. this._lastAbsoluteTransformsUpdateId = -1;
  72599. /**
  72600. * Specifies if the skeleton should be serialized.
  72601. */
  72602. this.doNotSerialize = false;
  72603. // Events
  72604. /**
  72605. * An event triggered before computing the skeleton's matrices
  72606. * @type {BABYLON.Observable}
  72607. */
  72608. this.onBeforeComputeObservable = new BABYLON.Observable();
  72609. this.bones = [];
  72610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72611. scene.skeletons.push(this);
  72612. //make sure it will recalculate the matrix next time prepare is called.
  72613. this._isDirty = true;
  72614. }
  72615. // Members
  72616. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72617. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72618. return mesh._bonesTransformMatrices;
  72619. }
  72620. if (!this._transformMatrices) {
  72621. this.prepare();
  72622. }
  72623. return this._transformMatrices;
  72624. };
  72625. Skeleton.prototype.getScene = function () {
  72626. return this._scene;
  72627. };
  72628. // Methods
  72629. /**
  72630. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72631. */
  72632. Skeleton.prototype.toString = function (fullDetails) {
  72633. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72634. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72635. if (fullDetails) {
  72636. ret += ", Ranges: {";
  72637. var first = true;
  72638. for (var name_1 in this._ranges) {
  72639. if (first) {
  72640. ret += ", ";
  72641. first = false;
  72642. }
  72643. ret += name_1;
  72644. }
  72645. ret += "}";
  72646. }
  72647. return ret;
  72648. };
  72649. /**
  72650. * Get bone's index searching by name
  72651. * @param {string} name is bone's name to search for
  72652. * @return {number} Indice of the bone. Returns -1 if not found
  72653. */
  72654. Skeleton.prototype.getBoneIndexByName = function (name) {
  72655. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72656. if (this.bones[boneIndex].name === name) {
  72657. return boneIndex;
  72658. }
  72659. }
  72660. return -1;
  72661. };
  72662. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72663. // check name not already in use
  72664. if (!this._ranges[name]) {
  72665. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72666. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72667. if (this.bones[i].animations[0]) {
  72668. this.bones[i].animations[0].createRange(name, from, to);
  72669. }
  72670. }
  72671. }
  72672. };
  72673. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72674. if (deleteFrames === void 0) { deleteFrames = true; }
  72675. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72676. if (this.bones[i].animations[0]) {
  72677. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72678. }
  72679. }
  72680. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72681. };
  72682. Skeleton.prototype.getAnimationRange = function (name) {
  72683. return this._ranges[name];
  72684. };
  72685. /**
  72686. * Returns as an Array, all AnimationRanges defined on this skeleton
  72687. */
  72688. Skeleton.prototype.getAnimationRanges = function () {
  72689. var animationRanges = [];
  72690. var name;
  72691. var i = 0;
  72692. for (name in this._ranges) {
  72693. animationRanges[i] = this._ranges[name];
  72694. i++;
  72695. }
  72696. return animationRanges;
  72697. };
  72698. /**
  72699. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72700. */
  72701. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72702. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72703. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72704. return false;
  72705. }
  72706. var ret = true;
  72707. var frameOffset = this._getHighestAnimationFrame() + 1;
  72708. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72709. var boneDict = {};
  72710. var sourceBones = source.bones;
  72711. var nBones;
  72712. var i;
  72713. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72714. boneDict[sourceBones[i].name] = sourceBones[i];
  72715. }
  72716. if (this.bones.length !== sourceBones.length) {
  72717. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72718. ret = false;
  72719. }
  72720. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72721. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72722. var boneName = this.bones[i].name;
  72723. var sourceBone = boneDict[boneName];
  72724. if (sourceBone) {
  72725. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72726. }
  72727. else {
  72728. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72729. ret = false;
  72730. }
  72731. }
  72732. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72733. var range = source.getAnimationRange(name);
  72734. if (range) {
  72735. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72736. }
  72737. return ret;
  72738. };
  72739. Skeleton.prototype.returnToRest = function () {
  72740. for (var index = 0; index < this.bones.length; index++) {
  72741. this.bones[index].returnToRest();
  72742. }
  72743. };
  72744. Skeleton.prototype._getHighestAnimationFrame = function () {
  72745. var ret = 0;
  72746. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72747. if (this.bones[i].animations[0]) {
  72748. var highest = this.bones[i].animations[0].getHighestFrame();
  72749. if (ret < highest) {
  72750. ret = highest;
  72751. }
  72752. }
  72753. }
  72754. return ret;
  72755. };
  72756. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72757. var range = this.getAnimationRange(name);
  72758. if (!range) {
  72759. return null;
  72760. }
  72761. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72762. };
  72763. Skeleton.prototype._markAsDirty = function () {
  72764. this._isDirty = true;
  72765. };
  72766. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72767. this._meshesWithPoseMatrix.push(mesh);
  72768. };
  72769. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72770. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72771. if (index > -1) {
  72772. this._meshesWithPoseMatrix.splice(index, 1);
  72773. }
  72774. };
  72775. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72776. this.onBeforeComputeObservable.notifyObservers(this);
  72777. for (var index = 0; index < this.bones.length; index++) {
  72778. var bone = this.bones[index];
  72779. var parentBone = bone.getParent();
  72780. if (parentBone) {
  72781. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72782. }
  72783. else {
  72784. if (initialSkinMatrix) {
  72785. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72786. }
  72787. else {
  72788. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72789. }
  72790. }
  72791. if (bone._index !== -1) {
  72792. var mappedIndex = bone._index === null ? index : bone._index;
  72793. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72794. }
  72795. }
  72796. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72797. };
  72798. Skeleton.prototype.prepare = function () {
  72799. if (!this._isDirty) {
  72800. return;
  72801. }
  72802. if (this.needInitialSkinMatrix) {
  72803. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72804. var mesh = this._meshesWithPoseMatrix[index];
  72805. var poseMatrix = mesh.getPoseMatrix();
  72806. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72807. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72808. }
  72809. if (this._synchronizedWithMesh !== mesh) {
  72810. this._synchronizedWithMesh = mesh;
  72811. // Prepare bones
  72812. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72813. var bone = this.bones[boneIndex];
  72814. if (!bone.getParent()) {
  72815. var matrix = bone.getBaseMatrix();
  72816. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72817. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72818. }
  72819. }
  72820. }
  72821. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72822. }
  72823. }
  72824. else {
  72825. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72826. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72827. }
  72828. this._computeTransformMatrices(this._transformMatrices, null);
  72829. }
  72830. this._isDirty = false;
  72831. this._scene._activeBones.addCount(this.bones.length, false);
  72832. };
  72833. Skeleton.prototype.getAnimatables = function () {
  72834. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72835. this._animatables = [];
  72836. for (var index = 0; index < this.bones.length; index++) {
  72837. this._animatables.push(this.bones[index]);
  72838. }
  72839. }
  72840. return this._animatables;
  72841. };
  72842. Skeleton.prototype.clone = function (name, id) {
  72843. var result = new Skeleton(name, id || name, this._scene);
  72844. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72845. for (var index = 0; index < this.bones.length; index++) {
  72846. var source = this.bones[index];
  72847. var parentBone = null;
  72848. var parent_1 = source.getParent();
  72849. if (parent_1) {
  72850. var parentIndex = this.bones.indexOf(parent_1);
  72851. parentBone = result.bones[parentIndex];
  72852. }
  72853. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72854. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72855. }
  72856. if (this._ranges) {
  72857. result._ranges = {};
  72858. for (var rangeName in this._ranges) {
  72859. var range = this._ranges[rangeName];
  72860. if (range) {
  72861. result._ranges[rangeName] = range.clone();
  72862. }
  72863. }
  72864. }
  72865. this._isDirty = true;
  72866. return result;
  72867. };
  72868. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72869. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72870. this.bones.forEach(function (bone) {
  72871. bone.animations.forEach(function (animation) {
  72872. animation.enableBlending = true;
  72873. animation.blendingSpeed = blendingSpeed;
  72874. });
  72875. });
  72876. };
  72877. Skeleton.prototype.dispose = function () {
  72878. this._meshesWithPoseMatrix = [];
  72879. // Animations
  72880. this.getScene().stopAnimation(this);
  72881. // Remove from scene
  72882. this.getScene().removeSkeleton(this);
  72883. };
  72884. Skeleton.prototype.serialize = function () {
  72885. var serializationObject = {};
  72886. serializationObject.name = this.name;
  72887. serializationObject.id = this.id;
  72888. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72889. serializationObject.bones = [];
  72890. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72891. for (var index = 0; index < this.bones.length; index++) {
  72892. var bone = this.bones[index];
  72893. var parent_2 = bone.getParent();
  72894. var serializedBone = {
  72895. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72896. name: bone.name,
  72897. matrix: bone.getBaseMatrix().toArray(),
  72898. rest: bone.getRestPose().toArray()
  72899. };
  72900. serializationObject.bones.push(serializedBone);
  72901. if (bone.length) {
  72902. serializedBone.length = bone.length;
  72903. }
  72904. if (bone.animations && bone.animations.length > 0) {
  72905. serializedBone.animation = bone.animations[0].serialize();
  72906. }
  72907. serializationObject.ranges = [];
  72908. for (var name in this._ranges) {
  72909. var source = this._ranges[name];
  72910. if (!source) {
  72911. continue;
  72912. }
  72913. var range = {};
  72914. range.name = name;
  72915. range.from = source.from;
  72916. range.to = source.to;
  72917. serializationObject.ranges.push(range);
  72918. }
  72919. }
  72920. return serializationObject;
  72921. };
  72922. Skeleton.Parse = function (parsedSkeleton, scene) {
  72923. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72924. if (parsedSkeleton.dimensionsAtRest) {
  72925. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72926. }
  72927. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72928. var index;
  72929. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72930. var parsedBone = parsedSkeleton.bones[index];
  72931. var parentBone = null;
  72932. if (parsedBone.parentBoneIndex > -1) {
  72933. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72934. }
  72935. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72936. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72937. if (parsedBone.length) {
  72938. bone.length = parsedBone.length;
  72939. }
  72940. if (parsedBone.animation) {
  72941. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72942. }
  72943. }
  72944. // placed after bones, so createAnimationRange can cascade down
  72945. if (parsedSkeleton.ranges) {
  72946. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72947. var data = parsedSkeleton.ranges[index];
  72948. skeleton.createAnimationRange(data.name, data.from, data.to);
  72949. }
  72950. }
  72951. return skeleton;
  72952. };
  72953. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72954. if (forceUpdate === void 0) { forceUpdate = false; }
  72955. var renderId = this._scene.getRenderId();
  72956. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72957. this.bones[0].computeAbsoluteTransforms();
  72958. this._lastAbsoluteTransformsUpdateId = renderId;
  72959. }
  72960. };
  72961. Skeleton.prototype.getPoseMatrix = function () {
  72962. var poseMatrix = null;
  72963. if (this._meshesWithPoseMatrix.length > 0) {
  72964. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72965. }
  72966. return poseMatrix;
  72967. };
  72968. Skeleton.prototype.sortBones = function () {
  72969. var bones = new Array();
  72970. var visited = new Array(this.bones.length);
  72971. for (var index = 0; index < this.bones.length; index++) {
  72972. this._sortBones(index, bones, visited);
  72973. }
  72974. this.bones = bones;
  72975. };
  72976. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72977. if (visited[index]) {
  72978. return;
  72979. }
  72980. visited[index] = true;
  72981. var bone = this.bones[index];
  72982. if (bone._index === undefined) {
  72983. bone._index = index;
  72984. }
  72985. var parentBone = bone.getParent();
  72986. if (parentBone) {
  72987. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72988. }
  72989. bones.push(bone);
  72990. };
  72991. return Skeleton;
  72992. }());
  72993. BABYLON.Skeleton = Skeleton;
  72994. })(BABYLON || (BABYLON = {}));
  72995. //# sourceMappingURL=babylon.skeleton.js.map
  72996. var BABYLON;
  72997. (function (BABYLON) {
  72998. var SphericalPolynomial = /** @class */ (function () {
  72999. function SphericalPolynomial() {
  73000. this.x = BABYLON.Vector3.Zero();
  73001. this.y = BABYLON.Vector3.Zero();
  73002. this.z = BABYLON.Vector3.Zero();
  73003. this.xx = BABYLON.Vector3.Zero();
  73004. this.yy = BABYLON.Vector3.Zero();
  73005. this.zz = BABYLON.Vector3.Zero();
  73006. this.xy = BABYLON.Vector3.Zero();
  73007. this.yz = BABYLON.Vector3.Zero();
  73008. this.zx = BABYLON.Vector3.Zero();
  73009. }
  73010. SphericalPolynomial.prototype.addAmbient = function (color) {
  73011. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73012. this.xx = this.xx.add(colorVector);
  73013. this.yy = this.yy.add(colorVector);
  73014. this.zz = this.zz.add(colorVector);
  73015. };
  73016. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73017. var result = new SphericalPolynomial();
  73018. result.x = harmonics.L11.scale(1.02333);
  73019. result.y = harmonics.L1_1.scale(1.02333);
  73020. result.z = harmonics.L10.scale(1.02333);
  73021. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73022. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73023. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73024. result.yz = harmonics.L2_1.scale(0.858086);
  73025. result.zx = harmonics.L21.scale(0.858086);
  73026. result.xy = harmonics.L2_2.scale(0.858086);
  73027. result.scale(1.0 / Math.PI);
  73028. return result;
  73029. };
  73030. SphericalPolynomial.prototype.scale = function (scale) {
  73031. this.x = this.x.scale(scale);
  73032. this.y = this.y.scale(scale);
  73033. this.z = this.z.scale(scale);
  73034. this.xx = this.xx.scale(scale);
  73035. this.yy = this.yy.scale(scale);
  73036. this.zz = this.zz.scale(scale);
  73037. this.yz = this.yz.scale(scale);
  73038. this.zx = this.zx.scale(scale);
  73039. this.xy = this.xy.scale(scale);
  73040. };
  73041. return SphericalPolynomial;
  73042. }());
  73043. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73044. var SphericalHarmonics = /** @class */ (function () {
  73045. function SphericalHarmonics() {
  73046. this.L00 = BABYLON.Vector3.Zero();
  73047. this.L1_1 = BABYLON.Vector3.Zero();
  73048. this.L10 = BABYLON.Vector3.Zero();
  73049. this.L11 = BABYLON.Vector3.Zero();
  73050. this.L2_2 = BABYLON.Vector3.Zero();
  73051. this.L2_1 = BABYLON.Vector3.Zero();
  73052. this.L20 = BABYLON.Vector3.Zero();
  73053. this.L21 = BABYLON.Vector3.Zero();
  73054. this.L22 = BABYLON.Vector3.Zero();
  73055. }
  73056. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73057. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73058. var c = colorVector.scale(deltaSolidAngle);
  73059. this.L00 = this.L00.add(c.scale(0.282095));
  73060. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73061. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73062. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73063. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73064. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73065. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73066. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73067. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73068. };
  73069. SphericalHarmonics.prototype.scale = function (scale) {
  73070. this.L00 = this.L00.scale(scale);
  73071. this.L1_1 = this.L1_1.scale(scale);
  73072. this.L10 = this.L10.scale(scale);
  73073. this.L11 = this.L11.scale(scale);
  73074. this.L2_2 = this.L2_2.scale(scale);
  73075. this.L2_1 = this.L2_1.scale(scale);
  73076. this.L20 = this.L20.scale(scale);
  73077. this.L21 = this.L21.scale(scale);
  73078. this.L22 = this.L22.scale(scale);
  73079. };
  73080. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73081. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73082. //
  73083. // E_lm = A_l * L_lm
  73084. //
  73085. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73086. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73087. // the scaling factors are given in equation 9.
  73088. // Constant (Band 0)
  73089. this.L00 = this.L00.scale(3.141593);
  73090. // Linear (Band 1)
  73091. this.L1_1 = this.L1_1.scale(2.094395);
  73092. this.L10 = this.L10.scale(2.094395);
  73093. this.L11 = this.L11.scale(2.094395);
  73094. // Quadratic (Band 2)
  73095. this.L2_2 = this.L2_2.scale(0.785398);
  73096. this.L2_1 = this.L2_1.scale(0.785398);
  73097. this.L20 = this.L20.scale(0.785398);
  73098. this.L21 = this.L21.scale(0.785398);
  73099. this.L22 = this.L22.scale(0.785398);
  73100. };
  73101. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73102. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73103. // L = (1/pi) * E * rho
  73104. //
  73105. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73106. this.scale(1.0 / Math.PI);
  73107. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73108. // (The pixel shader must apply albedo after texture fetches, etc).
  73109. };
  73110. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73111. var result = new SphericalHarmonics();
  73112. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73113. result.L1_1 = polynomial.y.scale(0.977204);
  73114. result.L10 = polynomial.z.scale(0.977204);
  73115. result.L11 = polynomial.x.scale(0.977204);
  73116. result.L2_2 = polynomial.xy.scale(1.16538);
  73117. result.L2_1 = polynomial.yz.scale(1.16538);
  73118. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73119. result.L21 = polynomial.zx.scale(1.16538);
  73120. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73121. result.scale(Math.PI);
  73122. return result;
  73123. };
  73124. return SphericalHarmonics;
  73125. }());
  73126. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73127. })(BABYLON || (BABYLON = {}));
  73128. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73129. var BABYLON;
  73130. (function (BABYLON) {
  73131. var FileFaceOrientation = /** @class */ (function () {
  73132. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73133. this.name = name;
  73134. this.worldAxisForNormal = worldAxisForNormal;
  73135. this.worldAxisForFileX = worldAxisForFileX;
  73136. this.worldAxisForFileY = worldAxisForFileY;
  73137. }
  73138. return FileFaceOrientation;
  73139. }());
  73140. ;
  73141. /**
  73142. * Helper class dealing with the extraction of spherical polynomial dataArray
  73143. * from a cube map.
  73144. */
  73145. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73146. function CubeMapToSphericalPolynomialTools() {
  73147. }
  73148. /**
  73149. * Converts a texture to the according Spherical Polynomial data.
  73150. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73151. *
  73152. * @param texture The texture to extract the information from.
  73153. * @return The Spherical Polynomial data.
  73154. */
  73155. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73156. if (!texture.isCube) {
  73157. // Only supports cube Textures currently.
  73158. return null;
  73159. }
  73160. var size = texture.getSize().width;
  73161. var right = texture.readPixels(0);
  73162. var left = texture.readPixels(1);
  73163. var up;
  73164. var down;
  73165. if (texture.isRenderTarget) {
  73166. up = texture.readPixels(3);
  73167. down = texture.readPixels(2);
  73168. }
  73169. else {
  73170. up = texture.readPixels(2);
  73171. down = texture.readPixels(3);
  73172. }
  73173. var front = texture.readPixels(4);
  73174. var back = texture.readPixels(5);
  73175. var gammaSpace = texture.gammaSpace;
  73176. // Always read as RGBA.
  73177. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73178. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73179. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73180. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73181. }
  73182. var cubeInfo = {
  73183. size: size,
  73184. right: right,
  73185. left: left,
  73186. up: up,
  73187. down: down,
  73188. front: front,
  73189. back: back,
  73190. format: format,
  73191. type: type,
  73192. gammaSpace: gammaSpace,
  73193. };
  73194. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73195. };
  73196. /**
  73197. * Converts a cubemap to the according Spherical Polynomial data.
  73198. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73199. *
  73200. * @param cubeInfo The Cube map to extract the information from.
  73201. * @return The Spherical Polynomial data.
  73202. */
  73203. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73204. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73205. var totalSolidAngle = 0.0;
  73206. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73207. var du = 2.0 / cubeInfo.size;
  73208. var dv = du;
  73209. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73210. var minUV = du * 0.5 - 1.0;
  73211. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73212. var fileFace = this.FileFaces[faceIndex];
  73213. var dataArray = cubeInfo[fileFace.name];
  73214. var v = minUV;
  73215. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73216. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73217. // Because SP is still linear, so summation is fine in that basis.
  73218. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73219. for (var y = 0; y < cubeInfo.size; y++) {
  73220. var u = minUV;
  73221. for (var x = 0; x < cubeInfo.size; x++) {
  73222. // World direction (not normalised)
  73223. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73224. worldDirection.normalize();
  73225. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73226. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73227. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73228. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73229. // Handle Integer types.
  73230. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73231. r /= 255;
  73232. g /= 255;
  73233. b /= 255;
  73234. }
  73235. // Handle Gamma space textures.
  73236. if (cubeInfo.gammaSpace) {
  73237. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73238. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73239. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73240. }
  73241. var color = new BABYLON.Color3(r, g, b);
  73242. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73243. totalSolidAngle += deltaSolidAngle;
  73244. u += du;
  73245. }
  73246. v += dv;
  73247. }
  73248. }
  73249. // Solid angle for entire sphere is 4*pi
  73250. var sphereSolidAngle = 4.0 * Math.PI;
  73251. // Adjust the solid angle to allow for how many faces we processed.
  73252. var facesProcessed = 6.0;
  73253. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73254. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73255. // This is needed because the numerical integration over the cube uses a
  73256. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73257. // and also to compensate for accumulative error due to float precision in the summation.
  73258. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73259. sphericalHarmonics.scale(correctionFactor);
  73260. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73261. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73262. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73263. };
  73264. CubeMapToSphericalPolynomialTools.FileFaces = [
  73265. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73266. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73267. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73268. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73269. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73270. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73271. ];
  73272. return CubeMapToSphericalPolynomialTools;
  73273. }());
  73274. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73275. })(BABYLON || (BABYLON = {}));
  73276. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73277. var BABYLON;
  73278. (function (BABYLON) {
  73279. /**
  73280. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73281. */
  73282. var PanoramaToCubeMapTools = /** @class */ (function () {
  73283. function PanoramaToCubeMapTools() {
  73284. }
  73285. /**
  73286. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73287. *
  73288. * @param float32Array The source data.
  73289. * @param inputWidth The width of the input panorama.
  73290. * @param inputhHeight The height of the input panorama.
  73291. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73292. * @return The cubemap data
  73293. */
  73294. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73295. if (!float32Array) {
  73296. throw "ConvertPanoramaToCubemap: input cannot be null";
  73297. }
  73298. if (float32Array.length != inputWidth * inputHeight * 3) {
  73299. throw "ConvertPanoramaToCubemap: input size is wrong";
  73300. }
  73301. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73302. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73303. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73304. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73305. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73306. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73307. return {
  73308. front: textureFront,
  73309. back: textureBack,
  73310. left: textureLeft,
  73311. right: textureRight,
  73312. up: textureUp,
  73313. down: textureDown,
  73314. size: size,
  73315. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73316. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73317. gammaSpace: false,
  73318. };
  73319. };
  73320. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73321. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73322. var textureArray = new Float32Array(buffer);
  73323. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73324. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73325. var dy = 1 / texSize;
  73326. var fy = 0;
  73327. for (var y = 0; y < texSize; y++) {
  73328. var xv1 = faceData[0];
  73329. var xv2 = faceData[2];
  73330. for (var x = 0; x < texSize; x++) {
  73331. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73332. v.normalize();
  73333. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73334. // 3 channels per pixels
  73335. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73336. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73337. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73338. xv1 = xv1.add(rotDX1);
  73339. xv2 = xv2.add(rotDX2);
  73340. }
  73341. fy += dy;
  73342. }
  73343. return textureArray;
  73344. };
  73345. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73346. var theta = Math.atan2(vDir.z, vDir.x);
  73347. var phi = Math.acos(vDir.y);
  73348. while (theta < -Math.PI)
  73349. theta += 2 * Math.PI;
  73350. while (theta > Math.PI)
  73351. theta -= 2 * Math.PI;
  73352. var dx = theta / Math.PI;
  73353. var dy = phi / Math.PI;
  73354. // recenter.
  73355. dx = dx * 0.5 + 0.5;
  73356. var px = Math.round(dx * inputWidth);
  73357. if (px < 0)
  73358. px = 0;
  73359. else if (px >= inputWidth)
  73360. px = inputWidth - 1;
  73361. var py = Math.round(dy * inputHeight);
  73362. if (py < 0)
  73363. py = 0;
  73364. else if (py >= inputHeight)
  73365. py = inputHeight - 1;
  73366. var inputY = (inputHeight - py - 1);
  73367. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73368. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73369. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73370. return {
  73371. r: r,
  73372. g: g,
  73373. b: b
  73374. };
  73375. };
  73376. PanoramaToCubeMapTools.FACE_FRONT = [
  73377. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73378. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73379. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73380. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73381. ];
  73382. PanoramaToCubeMapTools.FACE_BACK = [
  73383. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73384. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73385. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73386. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73387. ];
  73388. PanoramaToCubeMapTools.FACE_RIGHT = [
  73389. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73390. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73391. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73392. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73393. ];
  73394. PanoramaToCubeMapTools.FACE_LEFT = [
  73395. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73396. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73397. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73398. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73399. ];
  73400. PanoramaToCubeMapTools.FACE_DOWN = [
  73401. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73402. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73403. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73404. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73405. ];
  73406. PanoramaToCubeMapTools.FACE_UP = [
  73407. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73408. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73409. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73410. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73411. ];
  73412. return PanoramaToCubeMapTools;
  73413. }());
  73414. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73415. })(BABYLON || (BABYLON = {}));
  73416. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73417. var BABYLON;
  73418. (function (BABYLON) {
  73419. ;
  73420. /**
  73421. * This groups tools to convert HDR texture to native colors array.
  73422. */
  73423. var HDRTools = /** @class */ (function () {
  73424. function HDRTools() {
  73425. }
  73426. HDRTools.Ldexp = function (mantissa, exponent) {
  73427. if (exponent > 1023) {
  73428. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73429. }
  73430. if (exponent < -1074) {
  73431. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73432. }
  73433. return mantissa * Math.pow(2, exponent);
  73434. };
  73435. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73436. if (exponent > 0) {
  73437. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73438. float32array[index + 0] = red * exponent;
  73439. float32array[index + 1] = green * exponent;
  73440. float32array[index + 2] = blue * exponent;
  73441. }
  73442. else {
  73443. float32array[index + 0] = 0;
  73444. float32array[index + 1] = 0;
  73445. float32array[index + 2] = 0;
  73446. }
  73447. };
  73448. HDRTools.readStringLine = function (uint8array, startIndex) {
  73449. var line = "";
  73450. var character = "";
  73451. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73452. character = String.fromCharCode(uint8array[i]);
  73453. if (character == "\n") {
  73454. break;
  73455. }
  73456. line += character;
  73457. }
  73458. return line;
  73459. };
  73460. /**
  73461. * Reads header information from an RGBE texture stored in a native array.
  73462. * More information on this format are available here:
  73463. * https://en.wikipedia.org/wiki/RGBE_image_format
  73464. *
  73465. * @param uint8array The binary file stored in native array.
  73466. * @return The header information.
  73467. */
  73468. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73469. var height = 0;
  73470. var width = 0;
  73471. var line = this.readStringLine(uint8array, 0);
  73472. if (line[0] != '#' || line[1] != '?') {
  73473. throw "Bad HDR Format.";
  73474. }
  73475. var endOfHeader = false;
  73476. var findFormat = false;
  73477. var lineIndex = 0;
  73478. do {
  73479. lineIndex += (line.length + 1);
  73480. line = this.readStringLine(uint8array, lineIndex);
  73481. if (line == "FORMAT=32-bit_rle_rgbe") {
  73482. findFormat = true;
  73483. }
  73484. else if (line.length == 0) {
  73485. endOfHeader = true;
  73486. }
  73487. } while (!endOfHeader);
  73488. if (!findFormat) {
  73489. throw "HDR Bad header format, unsupported FORMAT";
  73490. }
  73491. lineIndex += (line.length + 1);
  73492. line = this.readStringLine(uint8array, lineIndex);
  73493. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73494. var match = sizeRegexp.exec(line);
  73495. // TODO. Support +Y and -X if needed.
  73496. if (!match || match.length < 3) {
  73497. throw "HDR Bad header format, no size";
  73498. }
  73499. width = parseInt(match[2]);
  73500. height = parseInt(match[1]);
  73501. if (width < 8 || width > 0x7fff) {
  73502. throw "HDR Bad header format, unsupported size";
  73503. }
  73504. lineIndex += (line.length + 1);
  73505. return {
  73506. height: height,
  73507. width: width,
  73508. dataPosition: lineIndex
  73509. };
  73510. };
  73511. /**
  73512. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73513. * This RGBE texture needs to store the information as a panorama.
  73514. *
  73515. * More information on this format are available here:
  73516. * https://en.wikipedia.org/wiki/RGBE_image_format
  73517. *
  73518. * @param buffer The binary file stored in an array buffer.
  73519. * @param size The expected size of the extracted cubemap.
  73520. * @return The Cube Map information.
  73521. */
  73522. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73523. var uint8array = new Uint8Array(buffer);
  73524. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73525. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73526. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73527. return cubeMapData;
  73528. };
  73529. /**
  73530. * Returns the pixels data extracted from an RGBE texture.
  73531. * This pixels will be stored left to right up to down in the R G B order in one array.
  73532. *
  73533. * More information on this format are available here:
  73534. * https://en.wikipedia.org/wiki/RGBE_image_format
  73535. *
  73536. * @param uint8array The binary file stored in an array buffer.
  73537. * @param hdrInfo The header information of the file.
  73538. * @return The pixels data in RGB right to left up to down order.
  73539. */
  73540. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73541. // Keep for multi format supports.
  73542. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73543. };
  73544. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73545. var num_scanlines = hdrInfo.height;
  73546. var scanline_width = hdrInfo.width;
  73547. var a, b, c, d, count;
  73548. var dataIndex = hdrInfo.dataPosition;
  73549. var index = 0, endIndex = 0, i = 0;
  73550. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73551. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73552. // 3 channels of 4 bytes per pixel in float.
  73553. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73554. var resultArray = new Float32Array(resultBuffer);
  73555. // read in each successive scanline
  73556. while (num_scanlines > 0) {
  73557. a = uint8array[dataIndex++];
  73558. b = uint8array[dataIndex++];
  73559. c = uint8array[dataIndex++];
  73560. d = uint8array[dataIndex++];
  73561. if (a != 2 || b != 2 || (c & 0x80)) {
  73562. // this file is not run length encoded
  73563. throw "HDR Bad header format, not RLE";
  73564. }
  73565. if (((c << 8) | d) != scanline_width) {
  73566. throw "HDR Bad header format, wrong scan line width";
  73567. }
  73568. index = 0;
  73569. // read each of the four channels for the scanline into the buffer
  73570. for (i = 0; i < 4; i++) {
  73571. endIndex = (i + 1) * scanline_width;
  73572. while (index < endIndex) {
  73573. a = uint8array[dataIndex++];
  73574. b = uint8array[dataIndex++];
  73575. if (a > 128) {
  73576. // a run of the same value
  73577. count = a - 128;
  73578. if ((count == 0) || (count > endIndex - index)) {
  73579. throw "HDR Bad Format, bad scanline data (run)";
  73580. }
  73581. while (count-- > 0) {
  73582. scanLineArray[index++] = b;
  73583. }
  73584. }
  73585. else {
  73586. // a non-run
  73587. count = a;
  73588. if ((count == 0) || (count > endIndex - index)) {
  73589. throw "HDR Bad Format, bad scanline data (non-run)";
  73590. }
  73591. scanLineArray[index++] = b;
  73592. if (--count > 0) {
  73593. for (var j = 0; j < count; j++) {
  73594. scanLineArray[index++] = uint8array[dataIndex++];
  73595. }
  73596. }
  73597. }
  73598. }
  73599. }
  73600. // now convert data from buffer into floats
  73601. for (i = 0; i < scanline_width; i++) {
  73602. a = scanLineArray[i];
  73603. b = scanLineArray[i + scanline_width];
  73604. c = scanLineArray[i + 2 * scanline_width];
  73605. d = scanLineArray[i + 3 * scanline_width];
  73606. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73607. }
  73608. num_scanlines--;
  73609. }
  73610. return resultArray;
  73611. };
  73612. return HDRTools;
  73613. }());
  73614. BABYLON.HDRTools = HDRTools;
  73615. })(BABYLON || (BABYLON = {}));
  73616. //# sourceMappingURL=babylon.hdr.js.map
  73617. var BABYLON;
  73618. (function (BABYLON) {
  73619. /**
  73620. * This represents a texture coming from an HDR input.
  73621. *
  73622. * The only supported format is currently panorama picture stored in RGBE format.
  73623. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73624. */
  73625. var HDRCubeTexture = /** @class */ (function (_super) {
  73626. __extends(HDRCubeTexture, _super);
  73627. /**
  73628. * Instantiates an HDRTexture from the following parameters.
  73629. *
  73630. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73631. * @param scene The scene the texture will be used in
  73632. * @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.
  73633. * @param noMipmap Forces to not generate the mipmap if true
  73634. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73635. * @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)
  73636. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73637. */
  73638. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73639. if (noMipmap === void 0) { noMipmap = false; }
  73640. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73641. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73642. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73643. if (onLoad === void 0) { onLoad = null; }
  73644. if (onError === void 0) { onError = null; }
  73645. var _this = _super.call(this, scene) || this;
  73646. _this._useInGammaSpace = false;
  73647. _this._generateHarmonics = true;
  73648. _this._isBABYLONPreprocessed = false;
  73649. _this._onLoad = null;
  73650. _this._onError = null;
  73651. /**
  73652. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73653. */
  73654. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73655. /**
  73656. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73657. * This is usefull at run time to apply the good shader.
  73658. */
  73659. _this.isPMREM = false;
  73660. _this._isBlocking = true;
  73661. /**
  73662. * Gets or sets the center of the bounding box associated with the cube texture
  73663. * It must define where the camera used to render the texture was set
  73664. */
  73665. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73666. if (!url) {
  73667. return _this;
  73668. }
  73669. _this.name = url;
  73670. _this.url = url;
  73671. _this.hasAlpha = false;
  73672. _this.isCube = true;
  73673. _this._textureMatrix = BABYLON.Matrix.Identity();
  73674. _this._onLoad = onLoad;
  73675. _this._onError = onError;
  73676. _this.gammaSpace = false;
  73677. var caps = scene.getEngine().getCaps();
  73678. if (size) {
  73679. _this._isBABYLONPreprocessed = false;
  73680. _this._noMipmap = noMipmap;
  73681. _this._size = size;
  73682. _this._useInGammaSpace = useInGammaSpace;
  73683. _this._usePMREMGenerator = usePMREMGenerator &&
  73684. caps.textureLOD &&
  73685. caps.textureFloat &&
  73686. !_this._useInGammaSpace;
  73687. }
  73688. else {
  73689. _this._isBABYLONPreprocessed = true;
  73690. _this._noMipmap = false;
  73691. _this._useInGammaSpace = false;
  73692. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73693. !_this._useInGammaSpace;
  73694. }
  73695. _this.isPMREM = _this._usePMREMGenerator;
  73696. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73697. if (!_this._texture) {
  73698. if (!scene.useDelayedTextureLoading) {
  73699. _this.loadTexture();
  73700. }
  73701. else {
  73702. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73703. }
  73704. }
  73705. return _this;
  73706. }
  73707. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73708. /**
  73709. * Gets wether or not the texture is blocking during loading.
  73710. */
  73711. get: function () {
  73712. return this._isBlocking;
  73713. },
  73714. /**
  73715. * Sets wether or not the texture is blocking during loading.
  73716. */
  73717. set: function (value) {
  73718. this._isBlocking = value;
  73719. },
  73720. enumerable: true,
  73721. configurable: true
  73722. });
  73723. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73724. get: function () {
  73725. return this._boundingBoxSize;
  73726. },
  73727. /**
  73728. * Gets or sets the size of the bounding box associated with the cube texture
  73729. * When defined, the cubemap will switch to local mode
  73730. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73731. * @example https://www.babylonjs-playground.com/#RNASML
  73732. */
  73733. set: function (value) {
  73734. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73735. return;
  73736. }
  73737. this._boundingBoxSize = value;
  73738. var scene = this.getScene();
  73739. if (scene) {
  73740. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73741. }
  73742. },
  73743. enumerable: true,
  73744. configurable: true
  73745. });
  73746. /**
  73747. * Occurs when the file is a preprocessed .babylon.hdr file.
  73748. */
  73749. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73750. var _this = this;
  73751. var mipLevels = 0;
  73752. var floatArrayView = null;
  73753. var scene = this.getScene();
  73754. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73755. var mips = new Array();
  73756. if (!floatArrayView) {
  73757. return mips;
  73758. }
  73759. var startIndex = 30;
  73760. for (var level = 0; level < mipLevels; level++) {
  73761. mips.push([]);
  73762. // Fill each pixel of the mip level.
  73763. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73764. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73765. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73766. mips[level].push(faceData);
  73767. startIndex += faceSize;
  73768. }
  73769. }
  73770. return mips;
  73771. } : null;
  73772. var callback = function (buffer) {
  73773. var scene = _this.getScene();
  73774. if (!scene) {
  73775. return null;
  73776. }
  73777. // Create Native Array Views
  73778. var intArrayView = new Int32Array(buffer);
  73779. floatArrayView = new Float32Array(buffer);
  73780. // Fill header.
  73781. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73782. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73783. // Update Texture Information.
  73784. if (!_this._texture) {
  73785. return null;
  73786. }
  73787. _this._texture.updateSize(_this._size, _this._size);
  73788. // Fill polynomial information.
  73789. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73790. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73791. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73792. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73793. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73794. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73795. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73796. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73797. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73798. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73799. _this.sphericalPolynomial = sphericalPolynomial;
  73800. // Fill pixel data.
  73801. mipLevels = intArrayView[29]; // Number of mip levels.
  73802. var startIndex = 30;
  73803. var data = [];
  73804. var faceSize = Math.pow(_this._size, 2) * 3;
  73805. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73806. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73807. startIndex += faceSize;
  73808. }
  73809. var results = [];
  73810. var byteArray = null;
  73811. // Push each faces.
  73812. for (var k = 0; k < 6; k++) {
  73813. var dataFace = null;
  73814. // To be deprecated.
  73815. if (version === 1) {
  73816. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73817. dataFace = data[j];
  73818. }
  73819. // If special cases.
  73820. if (!mipmapGenerator && dataFace) {
  73821. if (!scene.getEngine().getCaps().textureFloat) {
  73822. // 3 channels of 1 bytes per pixel in bytes.
  73823. var byteBuffer = new ArrayBuffer(faceSize);
  73824. byteArray = new Uint8Array(byteBuffer);
  73825. }
  73826. for (var i = 0; i < _this._size * _this._size; i++) {
  73827. // Put in gamma space if requested.
  73828. if (_this._useInGammaSpace) {
  73829. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73830. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73831. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73832. }
  73833. // Convert to int texture for fallback.
  73834. if (byteArray) {
  73835. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73836. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73837. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73838. // May use luminance instead if the result is not accurate.
  73839. var max = Math.max(Math.max(r, g), b);
  73840. if (max > 255) {
  73841. var scale = 255 / max;
  73842. r *= scale;
  73843. g *= scale;
  73844. b *= scale;
  73845. }
  73846. byteArray[(i * 3) + 0] = r;
  73847. byteArray[(i * 3) + 1] = g;
  73848. byteArray[(i * 3) + 2] = b;
  73849. }
  73850. }
  73851. }
  73852. // Fill the array accordingly.
  73853. if (byteArray) {
  73854. results.push(byteArray);
  73855. }
  73856. else {
  73857. results.push(dataFace);
  73858. }
  73859. }
  73860. return results;
  73861. };
  73862. if (scene) {
  73863. 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);
  73864. }
  73865. };
  73866. /**
  73867. * Occurs when the file is raw .hdr file.
  73868. */
  73869. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73870. var _this = this;
  73871. var callback = function (buffer) {
  73872. var scene = _this.getScene();
  73873. if (!scene) {
  73874. return null;
  73875. }
  73876. // Extract the raw linear data.
  73877. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73878. // Generate harmonics if needed.
  73879. if (_this._generateHarmonics) {
  73880. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73881. _this.sphericalPolynomial = sphericalPolynomial;
  73882. }
  73883. var results = [];
  73884. var byteArray = null;
  73885. // Push each faces.
  73886. for (var j = 0; j < 6; j++) {
  73887. // Create uintarray fallback.
  73888. if (!scene.getEngine().getCaps().textureFloat) {
  73889. // 3 channels of 1 bytes per pixel in bytes.
  73890. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73891. byteArray = new Uint8Array(byteBuffer);
  73892. }
  73893. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73894. // If special cases.
  73895. if (_this._useInGammaSpace || byteArray) {
  73896. for (var i = 0; i < _this._size * _this._size; i++) {
  73897. // Put in gamma space if requested.
  73898. if (_this._useInGammaSpace) {
  73899. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73900. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73901. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73902. }
  73903. // Convert to int texture for fallback.
  73904. if (byteArray) {
  73905. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73906. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73907. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73908. // May use luminance instead if the result is not accurate.
  73909. var max = Math.max(Math.max(r, g), b);
  73910. if (max > 255) {
  73911. var scale = 255 / max;
  73912. r *= scale;
  73913. g *= scale;
  73914. b *= scale;
  73915. }
  73916. byteArray[(i * 3) + 0] = r;
  73917. byteArray[(i * 3) + 1] = g;
  73918. byteArray[(i * 3) + 2] = b;
  73919. }
  73920. }
  73921. }
  73922. if (byteArray) {
  73923. results.push(byteArray);
  73924. }
  73925. else {
  73926. results.push(dataFace);
  73927. }
  73928. }
  73929. return results;
  73930. };
  73931. var mipmapGenerator = null;
  73932. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73933. // if (!this._noMipmap &&
  73934. // this._usePMREMGenerator) {
  73935. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73936. // // Custom setup of the generator matching with the PBR shader values.
  73937. // var generator = new BABYLON.PMREMGenerator(data,
  73938. // this._size,
  73939. // this._size,
  73940. // 0,
  73941. // 3,
  73942. // this.getScene().getEngine().getCaps().textureFloat,
  73943. // 2048,
  73944. // 0.25,
  73945. // false,
  73946. // true);
  73947. // return generator.filterCubeMap();
  73948. // };
  73949. // }
  73950. var scene = this.getScene();
  73951. if (scene) {
  73952. 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);
  73953. }
  73954. };
  73955. /**
  73956. * Starts the loading process of the texture.
  73957. */
  73958. HDRCubeTexture.prototype.loadTexture = function () {
  73959. if (this._isBABYLONPreprocessed) {
  73960. this.loadBabylonTexture();
  73961. }
  73962. else {
  73963. this.loadHDRTexture();
  73964. }
  73965. };
  73966. HDRCubeTexture.prototype.clone = function () {
  73967. var scene = this.getScene();
  73968. if (!scene) {
  73969. return this;
  73970. }
  73971. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73972. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73973. // Base texture
  73974. newTexture.level = this.level;
  73975. newTexture.wrapU = this.wrapU;
  73976. newTexture.wrapV = this.wrapV;
  73977. newTexture.coordinatesIndex = this.coordinatesIndex;
  73978. newTexture.coordinatesMode = this.coordinatesMode;
  73979. return newTexture;
  73980. };
  73981. // Methods
  73982. HDRCubeTexture.prototype.delayLoad = function () {
  73983. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73984. return;
  73985. }
  73986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73987. this._texture = this._getFromCache(this.url, this._noMipmap);
  73988. if (!this._texture) {
  73989. this.loadTexture();
  73990. }
  73991. };
  73992. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73993. return this._textureMatrix;
  73994. };
  73995. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73996. this._textureMatrix = value;
  73997. };
  73998. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73999. var texture = null;
  74000. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74001. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74002. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74003. texture.name = parsedTexture.name;
  74004. texture.hasAlpha = parsedTexture.hasAlpha;
  74005. texture.level = parsedTexture.level;
  74006. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74007. texture.isBlocking = parsedTexture.isBlocking;
  74008. }
  74009. if (texture) {
  74010. if (parsedTexture.boundingBoxPosition) {
  74011. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74012. }
  74013. if (parsedTexture.boundingBoxSize) {
  74014. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74015. }
  74016. }
  74017. return texture;
  74018. };
  74019. HDRCubeTexture.prototype.serialize = function () {
  74020. if (!this.name) {
  74021. return null;
  74022. }
  74023. var serializationObject = {};
  74024. serializationObject.name = this.name;
  74025. serializationObject.hasAlpha = this.hasAlpha;
  74026. serializationObject.isCube = true;
  74027. serializationObject.level = this.level;
  74028. serializationObject.size = this._size;
  74029. serializationObject.coordinatesMode = this.coordinatesMode;
  74030. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74031. serializationObject.generateHarmonics = this._generateHarmonics;
  74032. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74033. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74034. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74035. serializationObject.noMipmap = this._noMipmap;
  74036. serializationObject.isBlocking = this._isBlocking;
  74037. return serializationObject;
  74038. };
  74039. /**
  74040. * Saves as a file the data contained in the texture in a binary format.
  74041. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74042. * as the spherical used in the lighting.
  74043. * @param url The HDR file url.
  74044. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74045. * @param onError Method called if any error happens during download.
  74046. * @return The packed binary data.
  74047. */
  74048. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74049. if (onError === void 0) { onError = null; }
  74050. var callback = function (buffer) {
  74051. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74052. // Returns a URL you can use as a href.
  74053. var objUrl = window.URL.createObjectURL(data);
  74054. // Simulates a link to it and click to dowload.
  74055. var a = document.createElement("a");
  74056. document.body.appendChild(a);
  74057. a.style.display = "none";
  74058. a.href = objUrl;
  74059. a.download = "envmap.babylon.hdr";
  74060. a.click();
  74061. };
  74062. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74063. };
  74064. /**
  74065. * Serializes the data contained in the texture in a binary format.
  74066. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74067. * as the spherical used in the lighting.
  74068. * @param url The HDR file url.
  74069. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74070. * @param onError Method called if any error happens during download.
  74071. * @return The packed binary data.
  74072. */
  74073. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74074. if (onError === void 0) { onError = null; }
  74075. // Needs the url tho create the texture.
  74076. if (!url) {
  74077. return;
  74078. }
  74079. // Check Power of two size.
  74080. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74081. return;
  74082. }
  74083. // Coming Back in 3.x.
  74084. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74085. };
  74086. HDRCubeTexture._facesMapping = [
  74087. "right",
  74088. "left",
  74089. "up",
  74090. "down",
  74091. "front",
  74092. "back"
  74093. ];
  74094. return HDRCubeTexture;
  74095. }(BABYLON.BaseTexture));
  74096. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74097. })(BABYLON || (BABYLON = {}));
  74098. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74099. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74100. // Huge respect for a such great lib.
  74101. // Earcut license:
  74102. // Copyright (c) 2016, Mapbox
  74103. //
  74104. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74105. // with or without fee is hereby granted, provided that the above copyright notice
  74106. // and this permission notice appear in all copies.
  74107. //
  74108. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74109. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74110. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74111. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74112. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74113. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74114. // THIS SOFTWARE.
  74115. var Earcut;
  74116. (function (Earcut) {
  74117. /**
  74118. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74119. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74120. * @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).
  74121. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74122. */
  74123. function earcut(data, holeIndices, dim) {
  74124. dim = dim || 2;
  74125. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74126. if (!outerNode)
  74127. return triangles;
  74128. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74129. if (hasHoles)
  74130. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74131. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74132. if (data.length > 80 * dim) {
  74133. minX = maxX = data[0];
  74134. minY = maxY = data[1];
  74135. for (var i = dim; i < outerLen; i += dim) {
  74136. x = data[i];
  74137. y = data[i + 1];
  74138. if (x < minX)
  74139. minX = x;
  74140. if (y < minY)
  74141. minY = y;
  74142. if (x > maxX)
  74143. maxX = x;
  74144. if (y > maxY)
  74145. maxY = y;
  74146. }
  74147. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74148. size = Math.max(maxX - minX, maxY - minY);
  74149. }
  74150. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74151. return triangles;
  74152. }
  74153. Earcut.earcut = earcut;
  74154. var Node = /** @class */ (function () {
  74155. function Node(i, x, y) {
  74156. this.i = i;
  74157. this.x = x;
  74158. this.y = y;
  74159. this.prev = null;
  74160. this.next = null;
  74161. this.z = null;
  74162. this.prevZ = null;
  74163. this.nextZ = null;
  74164. this.steiner = false;
  74165. }
  74166. return Node;
  74167. }());
  74168. // create a circular doubly linked list from polygon points in the specified winding order
  74169. function linkedList(data, start, end, dim, clockwise) {
  74170. var i, last = null;
  74171. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74172. for (i = start; i < end; i += dim)
  74173. last = insertNode(i, data[i], data[i + 1], last);
  74174. }
  74175. else {
  74176. for (i = end - dim; i >= start; i -= dim)
  74177. last = insertNode(i, data[i], data[i + 1], last);
  74178. }
  74179. if (last && equals(last, last.next)) {
  74180. removeNode(last);
  74181. last = last.next;
  74182. }
  74183. return last;
  74184. }
  74185. // eliminate colinear or duplicate points
  74186. function filterPoints(start, end) {
  74187. if (!start)
  74188. return start;
  74189. if (!end)
  74190. end = start;
  74191. var p = start, again;
  74192. do {
  74193. again = false;
  74194. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74195. removeNode(p);
  74196. p = end = p.prev;
  74197. if (p === p.next)
  74198. return undefined;
  74199. again = true;
  74200. }
  74201. else {
  74202. p = p.next;
  74203. }
  74204. } while (again || p !== end);
  74205. return end;
  74206. }
  74207. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74208. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74209. if (!ear)
  74210. return;
  74211. // interlink polygon nodes in z-order
  74212. if (!pass && size)
  74213. indexCurve(ear, minX, minY, size);
  74214. var stop = ear, prev, next;
  74215. // iterate through ears, slicing them one by one
  74216. while (ear.prev !== ear.next) {
  74217. prev = ear.prev;
  74218. next = ear.next;
  74219. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74220. // cut off the triangle
  74221. triangles.push(prev.i / dim);
  74222. triangles.push(ear.i / dim);
  74223. triangles.push(next.i / dim);
  74224. removeNode(ear);
  74225. // skipping the next vertice leads to less sliver triangles
  74226. ear = next.next;
  74227. stop = next.next;
  74228. continue;
  74229. }
  74230. ear = next;
  74231. // if we looped through the whole remaining polygon and can't find any more ears
  74232. if (ear === stop) {
  74233. // try filtering points and slicing again
  74234. if (!pass) {
  74235. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74236. // if this didn't work, try curing all small self-intersections locally
  74237. }
  74238. else if (pass === 1) {
  74239. ear = cureLocalIntersections(ear, triangles, dim);
  74240. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74241. // as a last resort, try splitting the remaining polygon into two
  74242. }
  74243. else if (pass === 2) {
  74244. splitEarcut(ear, triangles, dim, minX, minY, size);
  74245. }
  74246. break;
  74247. }
  74248. }
  74249. }
  74250. // check whether a polygon node forms a valid ear with adjacent nodes
  74251. function isEar(ear) {
  74252. var a = ear.prev, b = ear, c = ear.next;
  74253. if (area(a, b, c) >= 0)
  74254. return false; // reflex, can't be an ear
  74255. // now make sure we don't have other points inside the potential ear
  74256. var p = ear.next.next;
  74257. while (p !== ear.prev) {
  74258. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74259. area(p.prev, p, p.next) >= 0)
  74260. return false;
  74261. p = p.next;
  74262. }
  74263. return true;
  74264. }
  74265. function isEarHashed(ear, minX, minY, size) {
  74266. var a = ear.prev, b = ear, c = ear.next;
  74267. if (area(a, b, c) >= 0)
  74268. return false; // reflex, can't be an ear
  74269. // triangle bbox; min & max are calculated like this for speed
  74270. 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);
  74271. // z-order range for the current triangle bbox;
  74272. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74273. // first look for points inside the triangle in increasing z-order
  74274. var p = ear.nextZ;
  74275. while (p && p.z <= maxZ) {
  74276. if (p !== ear.prev &&
  74277. p !== ear.next &&
  74278. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74279. area(p.prev, p, p.next) >= 0)
  74280. return false;
  74281. p = p.nextZ;
  74282. }
  74283. // then look for points in decreasing z-order
  74284. p = ear.prevZ;
  74285. while (p && p.z >= minZ) {
  74286. if (p !== ear.prev &&
  74287. p !== ear.next &&
  74288. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74289. area(p.prev, p, p.next) >= 0)
  74290. return false;
  74291. p = p.prevZ;
  74292. }
  74293. return true;
  74294. }
  74295. // go through all polygon nodes and cure small local self-intersections
  74296. function cureLocalIntersections(start, triangles, dim) {
  74297. var p = start;
  74298. do {
  74299. var a = p.prev, b = p.next.next;
  74300. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74301. triangles.push(a.i / dim);
  74302. triangles.push(p.i / dim);
  74303. triangles.push(b.i / dim);
  74304. // remove two nodes involved
  74305. removeNode(p);
  74306. removeNode(p.next);
  74307. p = start = b;
  74308. }
  74309. p = p.next;
  74310. } while (p !== start);
  74311. return p;
  74312. }
  74313. // try splitting polygon into two and triangulate them independently
  74314. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74315. // look for a valid diagonal that divides the polygon into two
  74316. var a = start;
  74317. do {
  74318. var b = a.next.next;
  74319. while (b !== a.prev) {
  74320. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74321. // split the polygon in two by the diagonal
  74322. var c = splitPolygon(a, b);
  74323. // filter colinear points around the cuts
  74324. a = filterPoints(a, a.next);
  74325. c = filterPoints(c, c.next);
  74326. // run earcut on each half
  74327. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74328. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74329. return;
  74330. }
  74331. b = b.next;
  74332. }
  74333. a = a.next;
  74334. } while (a !== start);
  74335. }
  74336. // link every hole into the outer loop, producing a single-ring polygon without holes
  74337. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74338. var queue = [], i, len, start, end, list;
  74339. for (i = 0, len = holeIndices.length; i < len; i++) {
  74340. start = holeIndices[i] * dim;
  74341. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74342. list = linkedList(data, start, end, dim, false);
  74343. if (list === list.next)
  74344. list.steiner = true;
  74345. queue.push(getLeftmost(list));
  74346. }
  74347. queue.sort(compareX);
  74348. // process holes from left to right
  74349. for (i = 0; i < queue.length; i++) {
  74350. eliminateHole(queue[i], outerNode);
  74351. outerNode = filterPoints(outerNode, outerNode.next);
  74352. }
  74353. return outerNode;
  74354. }
  74355. function compareX(a, b) {
  74356. return a.x - b.x;
  74357. }
  74358. // find a bridge between vertices that connects hole with an outer ring and and link it
  74359. function eliminateHole(hole, outerNode) {
  74360. outerNode = findHoleBridge(hole, outerNode);
  74361. if (outerNode) {
  74362. var b = splitPolygon(outerNode, hole);
  74363. filterPoints(b, b.next);
  74364. }
  74365. }
  74366. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74367. function findHoleBridge(hole, outerNode) {
  74368. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74369. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74370. // segment's endpoint with lesser x will be potential connection point
  74371. do {
  74372. if (hy <= p.y && hy >= p.next.y) {
  74373. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74374. if (x <= hx && x > qx) {
  74375. qx = x;
  74376. if (x === hx) {
  74377. if (hy === p.y)
  74378. return p;
  74379. if (hy === p.next.y)
  74380. return p.next;
  74381. }
  74382. m = p.x < p.next.x ? p : p.next;
  74383. }
  74384. }
  74385. p = p.next;
  74386. } while (p !== outerNode);
  74387. if (!m)
  74388. return null;
  74389. if (hx === qx)
  74390. return m.prev; // hole touches outer segment; pick lower endpoint
  74391. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74392. // if there are no points found, we have a valid connection;
  74393. // otherwise choose the point of the minimum angle with the ray as connection point
  74394. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74395. p = m.next;
  74396. while (p !== stop) {
  74397. if (hx >= p.x &&
  74398. p.x >= mx &&
  74399. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74400. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74401. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74402. m = p;
  74403. tanMin = tan;
  74404. }
  74405. }
  74406. p = p.next;
  74407. }
  74408. return m;
  74409. }
  74410. // interlink polygon nodes in z-order
  74411. function indexCurve(start, minX, minY, size) {
  74412. var p = start;
  74413. do {
  74414. if (p.z === null)
  74415. p.z = zOrder(p.x, p.y, minX, minY, size);
  74416. p.prevZ = p.prev;
  74417. p.nextZ = p.next;
  74418. p = p.next;
  74419. } while (p !== start);
  74420. p.prevZ.nextZ = null;
  74421. p.prevZ = null;
  74422. sortLinked(p);
  74423. }
  74424. // Simon Tatham's linked list merge sort algorithm
  74425. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74426. function sortLinked(list) {
  74427. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74428. do {
  74429. p = list;
  74430. list = null;
  74431. tail = null;
  74432. numMerges = 0;
  74433. while (p) {
  74434. numMerges++;
  74435. q = p;
  74436. pSize = 0;
  74437. for (i = 0; i < inSize; i++) {
  74438. pSize++;
  74439. q = q.nextZ;
  74440. if (!q)
  74441. break;
  74442. }
  74443. qSize = inSize;
  74444. while (pSize > 0 || (qSize > 0 && q)) {
  74445. if (pSize === 0) {
  74446. e = q;
  74447. q = q.nextZ;
  74448. qSize--;
  74449. }
  74450. else if (qSize === 0 || !q) {
  74451. e = p;
  74452. p = p.nextZ;
  74453. pSize--;
  74454. }
  74455. else if (p.z <= q.z) {
  74456. e = p;
  74457. p = p.nextZ;
  74458. pSize--;
  74459. }
  74460. else {
  74461. e = q;
  74462. q = q.nextZ;
  74463. qSize--;
  74464. }
  74465. if (tail)
  74466. tail.nextZ = e;
  74467. else
  74468. list = e;
  74469. e.prevZ = tail;
  74470. tail = e;
  74471. }
  74472. p = q;
  74473. }
  74474. tail.nextZ = null;
  74475. inSize *= 2;
  74476. } while (numMerges > 1);
  74477. return list;
  74478. }
  74479. // z-order of a point given coords and size of the data bounding box
  74480. function zOrder(x, y, minX, minY, size) {
  74481. // coords are transformed into non-negative 15-bit integer range
  74482. x = 32767 * (x - minX) / size;
  74483. y = 32767 * (y - minY) / size;
  74484. x = (x | (x << 8)) & 0x00FF00FF;
  74485. x = (x | (x << 4)) & 0x0F0F0F0F;
  74486. x = (x | (x << 2)) & 0x33333333;
  74487. x = (x | (x << 1)) & 0x55555555;
  74488. y = (y | (y << 8)) & 0x00FF00FF;
  74489. y = (y | (y << 4)) & 0x0F0F0F0F;
  74490. y = (y | (y << 2)) & 0x33333333;
  74491. y = (y | (y << 1)) & 0x55555555;
  74492. return x | (y << 1);
  74493. }
  74494. // find the leftmost node of a polygon ring
  74495. function getLeftmost(start) {
  74496. var p = start, leftmost = start;
  74497. do {
  74498. if (p.x < leftmost.x)
  74499. leftmost = p;
  74500. p = p.next;
  74501. } while (p !== start);
  74502. return leftmost;
  74503. }
  74504. // check if a point lies within a convex triangle
  74505. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74506. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74507. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74508. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74509. }
  74510. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74511. function isValidDiagonal(a, b) {
  74512. return a.next.i !== b.i &&
  74513. a.prev.i !== b.i &&
  74514. !intersectsPolygon(a, b) &&
  74515. locallyInside(a, b) &&
  74516. locallyInside(b, a) &&
  74517. middleInside(a, b);
  74518. }
  74519. // signed area of a triangle
  74520. function area(p, q, r) {
  74521. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74522. }
  74523. // check if two points are equal
  74524. function equals(p1, p2) {
  74525. return p1.x === p2.x && p1.y === p2.y;
  74526. }
  74527. // check if two segments intersect
  74528. function intersects(p1, q1, p2, q2) {
  74529. if ((equals(p1, q1) && equals(p2, q2)) ||
  74530. (equals(p1, q2) && equals(p2, q1)))
  74531. return true;
  74532. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74533. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74534. }
  74535. // check if a polygon diagonal intersects any polygon segments
  74536. function intersectsPolygon(a, b) {
  74537. var p = a;
  74538. do {
  74539. if (p.i !== a.i &&
  74540. p.next.i !== a.i &&
  74541. p.i !== b.i &&
  74542. p.next.i !== b.i &&
  74543. intersects(p, p.next, a, b))
  74544. return true;
  74545. p = p.next;
  74546. } while (p !== a);
  74547. return false;
  74548. }
  74549. // check if a polygon diagonal is locally inside the polygon
  74550. function locallyInside(a, b) {
  74551. return area(a.prev, a, a.next) < 0
  74552. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74553. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74554. }
  74555. // check if the middle point of a polygon diagonal is inside the polygon
  74556. function middleInside(a, b) {
  74557. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74558. do {
  74559. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74560. inside = !inside;
  74561. p = p.next;
  74562. } while (p !== a);
  74563. return inside;
  74564. }
  74565. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74566. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74567. function splitPolygon(a, b) {
  74568. 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;
  74569. a.next = b;
  74570. b.prev = a;
  74571. a2.next = an;
  74572. an.prev = a2;
  74573. b2.next = a2;
  74574. a2.prev = b2;
  74575. bp.next = b2;
  74576. b2.prev = bp;
  74577. return b2;
  74578. }
  74579. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74580. function insertNode(i, x, y, last) {
  74581. var p = new Node(i, x, y);
  74582. if (!last) {
  74583. p.prev = p;
  74584. p.next = p;
  74585. }
  74586. else {
  74587. p.next = last.next;
  74588. p.prev = last;
  74589. last.next.prev = p;
  74590. last.next = p;
  74591. }
  74592. return p;
  74593. }
  74594. function removeNode(p) {
  74595. p.next.prev = p.prev;
  74596. p.prev.next = p.next;
  74597. if (p.prevZ)
  74598. p.prevZ.nextZ = p.nextZ;
  74599. if (p.nextZ)
  74600. p.nextZ.prevZ = p.prevZ;
  74601. }
  74602. /**
  74603. * return a percentage difference between the polygon area and its triangulation area;
  74604. * used to verify correctness of triangulation
  74605. */
  74606. function deviation(data, holeIndices, dim, triangles) {
  74607. var hasHoles = holeIndices && holeIndices.length;
  74608. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74609. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74610. if (hasHoles) {
  74611. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74612. var start = holeIndices[i] * dim;
  74613. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74614. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74615. }
  74616. }
  74617. var trianglesArea = 0;
  74618. for (i = 0; i < triangles.length; i += 3) {
  74619. var a = triangles[i] * dim;
  74620. var b = triangles[i + 1] * dim;
  74621. var c = triangles[i + 2] * dim;
  74622. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74623. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74624. }
  74625. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74626. }
  74627. Earcut.deviation = deviation;
  74628. ;
  74629. function signedArea(data, start, end, dim) {
  74630. var sum = 0;
  74631. for (var i = start, j = end - dim; i < end; i += dim) {
  74632. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74633. j = i;
  74634. }
  74635. return sum;
  74636. }
  74637. /**
  74638. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74639. */
  74640. function flatten(data) {
  74641. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74642. for (var i = 0; i < data.length; i++) {
  74643. for (var j = 0; j < data[i].length; j++) {
  74644. for (var d = 0; d < dim; d++)
  74645. result.vertices.push(data[i][j][d]);
  74646. }
  74647. if (i > 0) {
  74648. holeIndex += data[i - 1].length;
  74649. result.holes.push(holeIndex);
  74650. }
  74651. }
  74652. return result;
  74653. }
  74654. Earcut.flatten = flatten;
  74655. ;
  74656. })(Earcut || (Earcut = {}));
  74657. //# sourceMappingURL=babylon.earcut.js.map
  74658. var BABYLON;
  74659. (function (BABYLON) {
  74660. var IndexedVector2 = /** @class */ (function (_super) {
  74661. __extends(IndexedVector2, _super);
  74662. function IndexedVector2(original, index) {
  74663. var _this = _super.call(this, original.x, original.y) || this;
  74664. _this.index = index;
  74665. return _this;
  74666. }
  74667. return IndexedVector2;
  74668. }(BABYLON.Vector2));
  74669. var PolygonPoints = /** @class */ (function () {
  74670. function PolygonPoints() {
  74671. this.elements = new Array();
  74672. }
  74673. PolygonPoints.prototype.add = function (originalPoints) {
  74674. var _this = this;
  74675. var result = new Array();
  74676. originalPoints.forEach(function (point) {
  74677. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74678. var newPoint = new IndexedVector2(point, _this.elements.length);
  74679. result.push(newPoint);
  74680. _this.elements.push(newPoint);
  74681. }
  74682. });
  74683. return result;
  74684. };
  74685. PolygonPoints.prototype.computeBounds = function () {
  74686. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74687. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74688. this.elements.forEach(function (point) {
  74689. // x
  74690. if (point.x < lmin.x) {
  74691. lmin.x = point.x;
  74692. }
  74693. else if (point.x > lmax.x) {
  74694. lmax.x = point.x;
  74695. }
  74696. // y
  74697. if (point.y < lmin.y) {
  74698. lmin.y = point.y;
  74699. }
  74700. else if (point.y > lmax.y) {
  74701. lmax.y = point.y;
  74702. }
  74703. });
  74704. return {
  74705. min: lmin,
  74706. max: lmax,
  74707. width: lmax.x - lmin.x,
  74708. height: lmax.y - lmin.y
  74709. };
  74710. };
  74711. return PolygonPoints;
  74712. }());
  74713. var Polygon = /** @class */ (function () {
  74714. function Polygon() {
  74715. }
  74716. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74717. return [
  74718. new BABYLON.Vector2(xmin, ymin),
  74719. new BABYLON.Vector2(xmax, ymin),
  74720. new BABYLON.Vector2(xmax, ymax),
  74721. new BABYLON.Vector2(xmin, ymax)
  74722. ];
  74723. };
  74724. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74725. if (cx === void 0) { cx = 0; }
  74726. if (cy === void 0) { cy = 0; }
  74727. if (numberOfSides === void 0) { numberOfSides = 32; }
  74728. var result = new Array();
  74729. var angle = 0;
  74730. var increment = (Math.PI * 2) / numberOfSides;
  74731. for (var i = 0; i < numberOfSides; i++) {
  74732. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74733. angle -= increment;
  74734. }
  74735. return result;
  74736. };
  74737. Polygon.Parse = function (input) {
  74738. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74739. var i, result = [];
  74740. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74741. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74742. }
  74743. return result;
  74744. };
  74745. Polygon.StartingAt = function (x, y) {
  74746. return BABYLON.Path2.StartingAt(x, y);
  74747. };
  74748. return Polygon;
  74749. }());
  74750. BABYLON.Polygon = Polygon;
  74751. var PolygonMeshBuilder = /** @class */ (function () {
  74752. function PolygonMeshBuilder(name, contours, scene) {
  74753. this._points = new PolygonPoints();
  74754. this._outlinepoints = new PolygonPoints();
  74755. this._holes = new Array();
  74756. this._epoints = new Array();
  74757. this._eholes = new Array();
  74758. this._name = name;
  74759. this._scene = scene;
  74760. var points;
  74761. if (contours instanceof BABYLON.Path2) {
  74762. points = contours.getPoints();
  74763. }
  74764. else {
  74765. points = contours;
  74766. }
  74767. this._addToepoint(points);
  74768. this._points.add(points);
  74769. this._outlinepoints.add(points);
  74770. }
  74771. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74772. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74773. var p = points_1[_i];
  74774. this._epoints.push(p.x, p.y);
  74775. }
  74776. };
  74777. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74778. this._points.add(hole);
  74779. var holepoints = new PolygonPoints();
  74780. holepoints.add(hole);
  74781. this._holes.push(holepoints);
  74782. this._eholes.push(this._epoints.length / 2);
  74783. this._addToepoint(hole);
  74784. return this;
  74785. };
  74786. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74787. var _this = this;
  74788. if (updatable === void 0) { updatable = false; }
  74789. if (depth === void 0) { depth = 0; }
  74790. var result = new BABYLON.Mesh(this._name, this._scene);
  74791. var normals = new Array();
  74792. var positions = new Array();
  74793. var uvs = new Array();
  74794. var bounds = this._points.computeBounds();
  74795. this._points.elements.forEach(function (p) {
  74796. normals.push(0, 1.0, 0);
  74797. positions.push(p.x, 0, p.y);
  74798. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74799. });
  74800. var indices = new Array();
  74801. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74802. for (var i = 0; i < res.length; i++) {
  74803. indices.push(res[i]);
  74804. }
  74805. if (depth > 0) {
  74806. var positionscount = (positions.length / 3); //get the current pointcount
  74807. this._points.elements.forEach(function (p) {
  74808. normals.push(0, -1.0, 0);
  74809. positions.push(p.x, -depth, p.y);
  74810. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74811. });
  74812. var totalCount = indices.length;
  74813. for (var i = 0; i < totalCount; i += 3) {
  74814. var i0 = indices[i + 0];
  74815. var i1 = indices[i + 1];
  74816. var i2 = indices[i + 2];
  74817. indices.push(i2 + positionscount);
  74818. indices.push(i1 + positionscount);
  74819. indices.push(i0 + positionscount);
  74820. }
  74821. //Add the sides
  74822. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74823. this._holes.forEach(function (hole) {
  74824. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74825. });
  74826. }
  74827. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74828. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74829. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74830. result.setIndices(indices);
  74831. return result;
  74832. };
  74833. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74834. var StartIndex = positions.length / 3;
  74835. var ulength = 0;
  74836. for (var i = 0; i < points.elements.length; i++) {
  74837. var p = points.elements[i];
  74838. var p1;
  74839. if ((i + 1) > points.elements.length - 1) {
  74840. p1 = points.elements[0];
  74841. }
  74842. else {
  74843. p1 = points.elements[i + 1];
  74844. }
  74845. positions.push(p.x, 0, p.y);
  74846. positions.push(p.x, -depth, p.y);
  74847. positions.push(p1.x, 0, p1.y);
  74848. positions.push(p1.x, -depth, p1.y);
  74849. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74850. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74851. var v3 = v2.subtract(v1);
  74852. var v4 = new BABYLON.Vector3(0, 1, 0);
  74853. var vn = BABYLON.Vector3.Cross(v3, v4);
  74854. vn = vn.normalize();
  74855. uvs.push(ulength / bounds.width, 0);
  74856. uvs.push(ulength / bounds.width, 1);
  74857. ulength += v3.length();
  74858. uvs.push((ulength / bounds.width), 0);
  74859. uvs.push((ulength / bounds.width), 1);
  74860. if (!flip) {
  74861. normals.push(-vn.x, -vn.y, -vn.z);
  74862. normals.push(-vn.x, -vn.y, -vn.z);
  74863. normals.push(-vn.x, -vn.y, -vn.z);
  74864. normals.push(-vn.x, -vn.y, -vn.z);
  74865. indices.push(StartIndex);
  74866. indices.push(StartIndex + 1);
  74867. indices.push(StartIndex + 2);
  74868. indices.push(StartIndex + 1);
  74869. indices.push(StartIndex + 3);
  74870. indices.push(StartIndex + 2);
  74871. }
  74872. else {
  74873. normals.push(vn.x, vn.y, vn.z);
  74874. normals.push(vn.x, vn.y, vn.z);
  74875. normals.push(vn.x, vn.y, vn.z);
  74876. normals.push(vn.x, vn.y, vn.z);
  74877. indices.push(StartIndex);
  74878. indices.push(StartIndex + 2);
  74879. indices.push(StartIndex + 1);
  74880. indices.push(StartIndex + 1);
  74881. indices.push(StartIndex + 2);
  74882. indices.push(StartIndex + 3);
  74883. }
  74884. StartIndex += 4;
  74885. }
  74886. ;
  74887. };
  74888. return PolygonMeshBuilder;
  74889. }());
  74890. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74891. })(BABYLON || (BABYLON = {}));
  74892. //# sourceMappingURL=babylon.polygonMesh.js.map
  74893. var BABYLON;
  74894. (function (BABYLON) {
  74895. // Unique ID when we import meshes from Babylon to CSG
  74896. var currentCSGMeshId = 0;
  74897. // # class Vertex
  74898. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74899. // one to provide additional features like texture coordinates and vertex
  74900. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74901. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74902. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74903. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74904. // is not used anywhere else.
  74905. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74906. var Vertex = /** @class */ (function () {
  74907. function Vertex(pos, normal, uv) {
  74908. this.pos = pos;
  74909. this.normal = normal;
  74910. this.uv = uv;
  74911. }
  74912. Vertex.prototype.clone = function () {
  74913. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74914. };
  74915. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74916. // orientation of a polygon is flipped.
  74917. Vertex.prototype.flip = function () {
  74918. this.normal = this.normal.scale(-1);
  74919. };
  74920. // Create a new vertex between this vertex and `other` by linearly
  74921. // interpolating all properties using a parameter of `t`. Subclasses should
  74922. // override this to interpolate additional properties.
  74923. Vertex.prototype.interpolate = function (other, t) {
  74924. 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));
  74925. };
  74926. return Vertex;
  74927. }());
  74928. // # class Plane
  74929. // Represents a plane in 3D space.
  74930. var Plane = /** @class */ (function () {
  74931. function Plane(normal, w) {
  74932. this.normal = normal;
  74933. this.w = w;
  74934. }
  74935. Plane.FromPoints = function (a, b, c) {
  74936. var v0 = c.subtract(a);
  74937. var v1 = b.subtract(a);
  74938. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74939. return null;
  74940. }
  74941. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74942. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74943. };
  74944. Plane.prototype.clone = function () {
  74945. return new Plane(this.normal.clone(), this.w);
  74946. };
  74947. Plane.prototype.flip = function () {
  74948. this.normal.scaleInPlace(-1);
  74949. this.w = -this.w;
  74950. };
  74951. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74952. // fragments in the appropriate lists. Coplanar polygons go into either
  74953. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74954. // respect to this plane. Polygons in front or in back of this plane go into
  74955. // either `front` or `back`.
  74956. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74957. var COPLANAR = 0;
  74958. var FRONT = 1;
  74959. var BACK = 2;
  74960. var SPANNING = 3;
  74961. // Classify each point as well as the entire polygon into one of the above
  74962. // four classes.
  74963. var polygonType = 0;
  74964. var types = [];
  74965. var i;
  74966. var t;
  74967. for (i = 0; i < polygon.vertices.length; i++) {
  74968. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74969. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74970. polygonType |= type;
  74971. types.push(type);
  74972. }
  74973. // Put the polygon in the correct list, splitting it when necessary.
  74974. switch (polygonType) {
  74975. case COPLANAR:
  74976. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74977. break;
  74978. case FRONT:
  74979. front.push(polygon);
  74980. break;
  74981. case BACK:
  74982. back.push(polygon);
  74983. break;
  74984. case SPANNING:
  74985. var f = [], b = [];
  74986. for (i = 0; i < polygon.vertices.length; i++) {
  74987. var j = (i + 1) % polygon.vertices.length;
  74988. var ti = types[i], tj = types[j];
  74989. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74990. if (ti !== BACK)
  74991. f.push(vi);
  74992. if (ti !== FRONT)
  74993. b.push(ti !== BACK ? vi.clone() : vi);
  74994. if ((ti | tj) === SPANNING) {
  74995. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74996. var v = vi.interpolate(vj, t);
  74997. f.push(v);
  74998. b.push(v.clone());
  74999. }
  75000. }
  75001. var poly;
  75002. if (f.length >= 3) {
  75003. poly = new Polygon(f, polygon.shared);
  75004. if (poly.plane)
  75005. front.push(poly);
  75006. }
  75007. if (b.length >= 3) {
  75008. poly = new Polygon(b, polygon.shared);
  75009. if (poly.plane)
  75010. back.push(poly);
  75011. }
  75012. break;
  75013. }
  75014. };
  75015. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75016. // point is on the plane.
  75017. Plane.EPSILON = 1e-5;
  75018. return Plane;
  75019. }());
  75020. // # class Polygon
  75021. // Represents a convex polygon. The vertices used to initialize a polygon must
  75022. // be coplanar and form a convex loop.
  75023. //
  75024. // Each convex polygon has a `shared` property, which is shared between all
  75025. // polygons that are clones of each other or were split from the same polygon.
  75026. // This can be used to define per-polygon properties (such as surface color).
  75027. var Polygon = /** @class */ (function () {
  75028. function Polygon(vertices, shared) {
  75029. this.vertices = vertices;
  75030. this.shared = shared;
  75031. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75032. }
  75033. Polygon.prototype.clone = function () {
  75034. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75035. return new Polygon(vertices, this.shared);
  75036. };
  75037. Polygon.prototype.flip = function () {
  75038. this.vertices.reverse().map(function (v) { v.flip(); });
  75039. this.plane.flip();
  75040. };
  75041. return Polygon;
  75042. }());
  75043. // # class Node
  75044. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75045. // by picking a polygon to split along. That polygon (and all other coplanar
  75046. // polygons) are added directly to that node and the other polygons are added to
  75047. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75048. // no distinction between internal and leaf nodes.
  75049. var Node = /** @class */ (function () {
  75050. function Node(polygons) {
  75051. this.plane = null;
  75052. this.front = null;
  75053. this.back = null;
  75054. this.polygons = new Array();
  75055. if (polygons) {
  75056. this.build(polygons);
  75057. }
  75058. }
  75059. Node.prototype.clone = function () {
  75060. var node = new Node();
  75061. node.plane = this.plane && this.plane.clone();
  75062. node.front = this.front && this.front.clone();
  75063. node.back = this.back && this.back.clone();
  75064. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75065. return node;
  75066. };
  75067. // Convert solid space to empty space and empty space to solid space.
  75068. Node.prototype.invert = function () {
  75069. for (var i = 0; i < this.polygons.length; i++) {
  75070. this.polygons[i].flip();
  75071. }
  75072. if (this.plane) {
  75073. this.plane.flip();
  75074. }
  75075. if (this.front) {
  75076. this.front.invert();
  75077. }
  75078. if (this.back) {
  75079. this.back.invert();
  75080. }
  75081. var temp = this.front;
  75082. this.front = this.back;
  75083. this.back = temp;
  75084. };
  75085. // Recursively remove all polygons in `polygons` that are inside this BSP
  75086. // tree.
  75087. Node.prototype.clipPolygons = function (polygons) {
  75088. if (!this.plane)
  75089. return polygons.slice();
  75090. var front = new Array(), back = new Array();
  75091. for (var i = 0; i < polygons.length; i++) {
  75092. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75093. }
  75094. if (this.front) {
  75095. front = this.front.clipPolygons(front);
  75096. }
  75097. if (this.back) {
  75098. back = this.back.clipPolygons(back);
  75099. }
  75100. else {
  75101. back = [];
  75102. }
  75103. return front.concat(back);
  75104. };
  75105. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75106. // `bsp`.
  75107. Node.prototype.clipTo = function (bsp) {
  75108. this.polygons = bsp.clipPolygons(this.polygons);
  75109. if (this.front)
  75110. this.front.clipTo(bsp);
  75111. if (this.back)
  75112. this.back.clipTo(bsp);
  75113. };
  75114. // Return a list of all polygons in this BSP tree.
  75115. Node.prototype.allPolygons = function () {
  75116. var polygons = this.polygons.slice();
  75117. if (this.front)
  75118. polygons = polygons.concat(this.front.allPolygons());
  75119. if (this.back)
  75120. polygons = polygons.concat(this.back.allPolygons());
  75121. return polygons;
  75122. };
  75123. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75124. // new polygons are filtered down to the bottom of the tree and become new
  75125. // nodes there. Each set of polygons is partitioned using the first polygon
  75126. // (no heuristic is used to pick a good split).
  75127. Node.prototype.build = function (polygons) {
  75128. if (!polygons.length)
  75129. return;
  75130. if (!this.plane)
  75131. this.plane = polygons[0].plane.clone();
  75132. var front = new Array(), back = new Array();
  75133. for (var i = 0; i < polygons.length; i++) {
  75134. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75135. }
  75136. if (front.length) {
  75137. if (!this.front)
  75138. this.front = new Node();
  75139. this.front.build(front);
  75140. }
  75141. if (back.length) {
  75142. if (!this.back)
  75143. this.back = new Node();
  75144. this.back.build(back);
  75145. }
  75146. };
  75147. return Node;
  75148. }());
  75149. var CSG = /** @class */ (function () {
  75150. function CSG() {
  75151. this.polygons = new Array();
  75152. }
  75153. // Convert BABYLON.Mesh to BABYLON.CSG
  75154. CSG.FromMesh = function (mesh) {
  75155. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75156. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75157. if (mesh instanceof BABYLON.Mesh) {
  75158. mesh.computeWorldMatrix(true);
  75159. matrix = mesh.getWorldMatrix();
  75160. meshPosition = mesh.position.clone();
  75161. meshRotation = mesh.rotation.clone();
  75162. if (mesh.rotationQuaternion) {
  75163. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75164. }
  75165. meshScaling = mesh.scaling.clone();
  75166. }
  75167. else {
  75168. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75169. }
  75170. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75171. var subMeshes = mesh.subMeshes;
  75172. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75173. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75174. vertices = [];
  75175. for (var j = 0; j < 3; j++) {
  75176. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75177. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75178. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75179. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75180. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75181. vertex = new Vertex(position, normal, uv);
  75182. vertices.push(vertex);
  75183. }
  75184. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75185. // To handle the case of degenerated triangle
  75186. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75187. if (polygon.plane)
  75188. polygons.push(polygon);
  75189. }
  75190. }
  75191. var csg = CSG.FromPolygons(polygons);
  75192. csg.matrix = matrix;
  75193. csg.position = meshPosition;
  75194. csg.rotation = meshRotation;
  75195. csg.scaling = meshScaling;
  75196. csg.rotationQuaternion = meshRotationQuaternion;
  75197. currentCSGMeshId++;
  75198. return csg;
  75199. };
  75200. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75201. CSG.FromPolygons = function (polygons) {
  75202. var csg = new CSG();
  75203. csg.polygons = polygons;
  75204. return csg;
  75205. };
  75206. CSG.prototype.clone = function () {
  75207. var csg = new CSG();
  75208. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75209. csg.copyTransformAttributes(this);
  75210. return csg;
  75211. };
  75212. CSG.prototype.union = function (csg) {
  75213. var a = new Node(this.clone().polygons);
  75214. var b = new Node(csg.clone().polygons);
  75215. a.clipTo(b);
  75216. b.clipTo(a);
  75217. b.invert();
  75218. b.clipTo(a);
  75219. b.invert();
  75220. a.build(b.allPolygons());
  75221. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75222. };
  75223. CSG.prototype.unionInPlace = function (csg) {
  75224. var a = new Node(this.polygons);
  75225. var b = new Node(csg.polygons);
  75226. a.clipTo(b);
  75227. b.clipTo(a);
  75228. b.invert();
  75229. b.clipTo(a);
  75230. b.invert();
  75231. a.build(b.allPolygons());
  75232. this.polygons = a.allPolygons();
  75233. };
  75234. CSG.prototype.subtract = function (csg) {
  75235. var a = new Node(this.clone().polygons);
  75236. var b = new Node(csg.clone().polygons);
  75237. a.invert();
  75238. a.clipTo(b);
  75239. b.clipTo(a);
  75240. b.invert();
  75241. b.clipTo(a);
  75242. b.invert();
  75243. a.build(b.allPolygons());
  75244. a.invert();
  75245. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75246. };
  75247. CSG.prototype.subtractInPlace = function (csg) {
  75248. var a = new Node(this.polygons);
  75249. var b = new Node(csg.polygons);
  75250. a.invert();
  75251. a.clipTo(b);
  75252. b.clipTo(a);
  75253. b.invert();
  75254. b.clipTo(a);
  75255. b.invert();
  75256. a.build(b.allPolygons());
  75257. a.invert();
  75258. this.polygons = a.allPolygons();
  75259. };
  75260. CSG.prototype.intersect = function (csg) {
  75261. var a = new Node(this.clone().polygons);
  75262. var b = new Node(csg.clone().polygons);
  75263. a.invert();
  75264. b.clipTo(a);
  75265. b.invert();
  75266. a.clipTo(b);
  75267. b.clipTo(a);
  75268. a.build(b.allPolygons());
  75269. a.invert();
  75270. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75271. };
  75272. CSG.prototype.intersectInPlace = function (csg) {
  75273. var a = new Node(this.polygons);
  75274. var b = new Node(csg.polygons);
  75275. a.invert();
  75276. b.clipTo(a);
  75277. b.invert();
  75278. a.clipTo(b);
  75279. b.clipTo(a);
  75280. a.build(b.allPolygons());
  75281. a.invert();
  75282. this.polygons = a.allPolygons();
  75283. };
  75284. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75285. // not modified.
  75286. CSG.prototype.inverse = function () {
  75287. var csg = this.clone();
  75288. csg.inverseInPlace();
  75289. return csg;
  75290. };
  75291. CSG.prototype.inverseInPlace = function () {
  75292. this.polygons.map(function (p) { p.flip(); });
  75293. };
  75294. // This is used to keep meshes transformations so they can be restored
  75295. // when we build back a Babylon Mesh
  75296. // NB : All CSG operations are performed in world coordinates
  75297. CSG.prototype.copyTransformAttributes = function (csg) {
  75298. this.matrix = csg.matrix;
  75299. this.position = csg.position;
  75300. this.rotation = csg.rotation;
  75301. this.scaling = csg.scaling;
  75302. this.rotationQuaternion = csg.rotationQuaternion;
  75303. return this;
  75304. };
  75305. // Build Raw mesh from CSG
  75306. // Coordinates here are in world space
  75307. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75308. var matrix = this.matrix.clone();
  75309. matrix.invert();
  75310. 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;
  75311. if (keepSubMeshes) {
  75312. // Sort Polygons, since subMeshes are indices range
  75313. polygons.sort(function (a, b) {
  75314. if (a.shared.meshId === b.shared.meshId) {
  75315. return a.shared.subMeshId - b.shared.subMeshId;
  75316. }
  75317. else {
  75318. return a.shared.meshId - b.shared.meshId;
  75319. }
  75320. });
  75321. }
  75322. for (var i = 0, il = polygons.length; i < il; i++) {
  75323. polygon = polygons[i];
  75324. // Building SubMeshes
  75325. if (!subMesh_dict[polygon.shared.meshId]) {
  75326. subMesh_dict[polygon.shared.meshId] = {};
  75327. }
  75328. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75329. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75330. indexStart: +Infinity,
  75331. indexEnd: -Infinity,
  75332. materialIndex: polygon.shared.materialIndex
  75333. };
  75334. }
  75335. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75336. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75337. polygonIndices[0] = 0;
  75338. polygonIndices[1] = j - 1;
  75339. polygonIndices[2] = j;
  75340. for (var k = 0; k < 3; k++) {
  75341. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75342. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75343. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75344. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75345. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75346. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75347. // Check if 2 points can be merged
  75348. if (!(typeof vertex_idx !== 'undefined' &&
  75349. normals[vertex_idx * 3] === localNormal.x &&
  75350. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75351. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75352. uvs[vertex_idx * 2] === uv.x &&
  75353. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75354. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75355. uvs.push(uv.x, uv.y);
  75356. normals.push(normal.x, normal.y, normal.z);
  75357. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75358. }
  75359. indices.push(vertex_idx);
  75360. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75361. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75362. currentIndex++;
  75363. }
  75364. }
  75365. }
  75366. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75367. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75368. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75369. mesh.setIndices(indices, null);
  75370. if (keepSubMeshes) {
  75371. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75372. var materialIndexOffset = 0, materialMaxIndex;
  75373. mesh.subMeshes = new Array();
  75374. for (var m in subMesh_dict) {
  75375. materialMaxIndex = -1;
  75376. for (var sm in subMesh_dict[m]) {
  75377. subMesh_obj = subMesh_dict[m][sm];
  75378. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75379. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75380. }
  75381. materialIndexOffset += ++materialMaxIndex;
  75382. }
  75383. }
  75384. return mesh;
  75385. };
  75386. // Build Mesh from CSG taking material and transforms into account
  75387. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75388. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75389. mesh.material = material;
  75390. mesh.position.copyFrom(this.position);
  75391. mesh.rotation.copyFrom(this.rotation);
  75392. if (this.rotationQuaternion) {
  75393. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75394. }
  75395. mesh.scaling.copyFrom(this.scaling);
  75396. mesh.computeWorldMatrix(true);
  75397. return mesh;
  75398. };
  75399. return CSG;
  75400. }());
  75401. BABYLON.CSG = CSG;
  75402. })(BABYLON || (BABYLON = {}));
  75403. //# sourceMappingURL=babylon.csg.js.map
  75404. var BABYLON;
  75405. (function (BABYLON) {
  75406. var LensFlare = /** @class */ (function () {
  75407. function LensFlare(size, position, color, imgUrl, system) {
  75408. this.size = size;
  75409. this.position = position;
  75410. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75411. this.color = color || new BABYLON.Color3(1, 1, 1);
  75412. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75413. this._system = system;
  75414. system.lensFlares.push(this);
  75415. }
  75416. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75417. return new LensFlare(size, position, color, imgUrl, system);
  75418. };
  75419. LensFlare.prototype.dispose = function () {
  75420. if (this.texture) {
  75421. this.texture.dispose();
  75422. }
  75423. // Remove from scene
  75424. var index = this._system.lensFlares.indexOf(this);
  75425. this._system.lensFlares.splice(index, 1);
  75426. };
  75427. ;
  75428. return LensFlare;
  75429. }());
  75430. BABYLON.LensFlare = LensFlare;
  75431. })(BABYLON || (BABYLON = {}));
  75432. //# sourceMappingURL=babylon.lensFlare.js.map
  75433. var BABYLON;
  75434. (function (BABYLON) {
  75435. var LensFlareSystem = /** @class */ (function () {
  75436. function LensFlareSystem(name, emitter, scene) {
  75437. this.name = name;
  75438. this.lensFlares = new Array();
  75439. this.borderLimit = 300;
  75440. this.viewportBorder = 0;
  75441. this.layerMask = 0x0FFFFFFF;
  75442. this._vertexBuffers = {};
  75443. this._isEnabled = true;
  75444. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75445. this._emitter = emitter;
  75446. this.id = name;
  75447. scene.lensFlareSystems.push(this);
  75448. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75449. var engine = scene.getEngine();
  75450. // VBO
  75451. var vertices = [];
  75452. vertices.push(1, 1);
  75453. vertices.push(-1, 1);
  75454. vertices.push(-1, -1);
  75455. vertices.push(1, -1);
  75456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75457. // Indices
  75458. var indices = [];
  75459. indices.push(0);
  75460. indices.push(1);
  75461. indices.push(2);
  75462. indices.push(0);
  75463. indices.push(2);
  75464. indices.push(3);
  75465. this._indexBuffer = engine.createIndexBuffer(indices);
  75466. // Effects
  75467. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75468. }
  75469. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75470. get: function () {
  75471. return this._isEnabled;
  75472. },
  75473. set: function (value) {
  75474. this._isEnabled = value;
  75475. },
  75476. enumerable: true,
  75477. configurable: true
  75478. });
  75479. LensFlareSystem.prototype.getScene = function () {
  75480. return this._scene;
  75481. };
  75482. LensFlareSystem.prototype.getEmitter = function () {
  75483. return this._emitter;
  75484. };
  75485. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75486. this._emitter = newEmitter;
  75487. };
  75488. LensFlareSystem.prototype.getEmitterPosition = function () {
  75489. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75490. };
  75491. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75492. var position = this.getEmitterPosition();
  75493. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75494. this._positionX = position.x;
  75495. this._positionY = position.y;
  75496. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75497. if (this.viewportBorder > 0) {
  75498. globalViewport.x -= this.viewportBorder;
  75499. globalViewport.y -= this.viewportBorder;
  75500. globalViewport.width += this.viewportBorder * 2;
  75501. globalViewport.height += this.viewportBorder * 2;
  75502. position.x += this.viewportBorder;
  75503. position.y += this.viewportBorder;
  75504. this._positionX += this.viewportBorder;
  75505. this._positionY += this.viewportBorder;
  75506. }
  75507. if (position.z > 0) {
  75508. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75509. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75510. return true;
  75511. }
  75512. return true;
  75513. }
  75514. return false;
  75515. };
  75516. LensFlareSystem.prototype._isVisible = function () {
  75517. if (!this._isEnabled || !this._scene.activeCamera) {
  75518. return false;
  75519. }
  75520. var emitterPosition = this.getEmitterPosition();
  75521. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75522. var distance = direction.length();
  75523. direction.normalize();
  75524. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75525. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75526. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75527. };
  75528. LensFlareSystem.prototype.render = function () {
  75529. if (!this._effect.isReady() || !this._scene.activeCamera)
  75530. return false;
  75531. var engine = this._scene.getEngine();
  75532. var viewport = this._scene.activeCamera.viewport;
  75533. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75534. // Position
  75535. if (!this.computeEffectivePosition(globalViewport)) {
  75536. return false;
  75537. }
  75538. // Visibility
  75539. if (!this._isVisible()) {
  75540. return false;
  75541. }
  75542. // Intensity
  75543. var awayX;
  75544. var awayY;
  75545. if (this._positionX < this.borderLimit + globalViewport.x) {
  75546. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75547. }
  75548. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75549. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75550. }
  75551. else {
  75552. awayX = 0;
  75553. }
  75554. if (this._positionY < this.borderLimit + globalViewport.y) {
  75555. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75556. }
  75557. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75558. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75559. }
  75560. else {
  75561. awayY = 0;
  75562. }
  75563. var away = (awayX > awayY) ? awayX : awayY;
  75564. away -= this.viewportBorder;
  75565. if (away > this.borderLimit) {
  75566. away = this.borderLimit;
  75567. }
  75568. var intensity = 1.0 - (away / this.borderLimit);
  75569. if (intensity < 0) {
  75570. return false;
  75571. }
  75572. if (intensity > 1.0) {
  75573. intensity = 1.0;
  75574. }
  75575. if (this.viewportBorder > 0) {
  75576. globalViewport.x += this.viewportBorder;
  75577. globalViewport.y += this.viewportBorder;
  75578. globalViewport.width -= this.viewportBorder * 2;
  75579. globalViewport.height -= this.viewportBorder * 2;
  75580. this._positionX -= this.viewportBorder;
  75581. this._positionY -= this.viewportBorder;
  75582. }
  75583. // Position
  75584. var centerX = globalViewport.x + globalViewport.width / 2;
  75585. var centerY = globalViewport.y + globalViewport.height / 2;
  75586. var distX = centerX - this._positionX;
  75587. var distY = centerY - this._positionY;
  75588. // Effects
  75589. engine.enableEffect(this._effect);
  75590. engine.setState(false);
  75591. engine.setDepthBuffer(false);
  75592. // VBOs
  75593. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75594. // Flares
  75595. for (var index = 0; index < this.lensFlares.length; index++) {
  75596. var flare = this.lensFlares[index];
  75597. engine.setAlphaMode(flare.alphaMode);
  75598. var x = centerX - (distX * flare.position);
  75599. var y = centerY - (distY * flare.position);
  75600. var cw = flare.size;
  75601. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75602. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75603. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75604. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75605. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75606. // Texture
  75607. this._effect.setTexture("textureSampler", flare.texture);
  75608. // Color
  75609. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75610. // Draw order
  75611. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75612. }
  75613. engine.setDepthBuffer(true);
  75614. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75615. return true;
  75616. };
  75617. LensFlareSystem.prototype.dispose = function () {
  75618. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75619. if (vertexBuffer) {
  75620. vertexBuffer.dispose();
  75621. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75622. }
  75623. if (this._indexBuffer) {
  75624. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75625. this._indexBuffer = null;
  75626. }
  75627. while (this.lensFlares.length) {
  75628. this.lensFlares[0].dispose();
  75629. }
  75630. // Remove from scene
  75631. var index = this._scene.lensFlareSystems.indexOf(this);
  75632. this._scene.lensFlareSystems.splice(index, 1);
  75633. };
  75634. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75635. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75636. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75637. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75638. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75639. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75640. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75641. var parsedFlare = parsedLensFlareSystem.flares[index];
  75642. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75643. }
  75644. return lensFlareSystem;
  75645. };
  75646. LensFlareSystem.prototype.serialize = function () {
  75647. var serializationObject = {};
  75648. serializationObject.id = this.id;
  75649. serializationObject.name = this.name;
  75650. serializationObject.emitterId = this.getEmitter().id;
  75651. serializationObject.borderLimit = this.borderLimit;
  75652. serializationObject.flares = [];
  75653. for (var index = 0; index < this.lensFlares.length; index++) {
  75654. var flare = this.lensFlares[index];
  75655. serializationObject.flares.push({
  75656. size: flare.size,
  75657. position: flare.position,
  75658. color: flare.color.asArray(),
  75659. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75660. });
  75661. }
  75662. return serializationObject;
  75663. };
  75664. return LensFlareSystem;
  75665. }());
  75666. BABYLON.LensFlareSystem = LensFlareSystem;
  75667. })(BABYLON || (BABYLON = {}));
  75668. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75669. var BABYLON;
  75670. (function (BABYLON) {
  75671. /**
  75672. * This is a holder class for the physics joint created by the physics plugin.
  75673. * It holds a set of functions to control the underlying joint.
  75674. */
  75675. var PhysicsJoint = /** @class */ (function () {
  75676. function PhysicsJoint(type, jointData) {
  75677. this.type = type;
  75678. this.jointData = jointData;
  75679. jointData.nativeParams = jointData.nativeParams || {};
  75680. }
  75681. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75682. get: function () {
  75683. return this._physicsJoint;
  75684. },
  75685. set: function (newJoint) {
  75686. if (this._physicsJoint) {
  75687. //remove from the wolrd
  75688. }
  75689. this._physicsJoint = newJoint;
  75690. },
  75691. enumerable: true,
  75692. configurable: true
  75693. });
  75694. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75695. set: function (physicsPlugin) {
  75696. this._physicsPlugin = physicsPlugin;
  75697. },
  75698. enumerable: true,
  75699. configurable: true
  75700. });
  75701. /**
  75702. * Execute a function that is physics-plugin specific.
  75703. * @param {Function} func the function that will be executed.
  75704. * It accepts two parameters: the physics world and the physics joint.
  75705. */
  75706. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75707. func(this._physicsPlugin.world, this._physicsJoint);
  75708. };
  75709. //TODO check if the native joints are the same
  75710. //Joint Types
  75711. PhysicsJoint.DistanceJoint = 0;
  75712. PhysicsJoint.HingeJoint = 1;
  75713. PhysicsJoint.BallAndSocketJoint = 2;
  75714. PhysicsJoint.WheelJoint = 3;
  75715. PhysicsJoint.SliderJoint = 4;
  75716. //OIMO
  75717. PhysicsJoint.PrismaticJoint = 5;
  75718. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75719. PhysicsJoint.UniversalJoint = 6;
  75720. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75721. //Cannon
  75722. //Similar to a Ball-Joint. Different in params
  75723. PhysicsJoint.PointToPointJoint = 8;
  75724. //Cannon only at the moment
  75725. PhysicsJoint.SpringJoint = 9;
  75726. PhysicsJoint.LockJoint = 10;
  75727. return PhysicsJoint;
  75728. }());
  75729. BABYLON.PhysicsJoint = PhysicsJoint;
  75730. /**
  75731. * A class representing a physics distance joint.
  75732. */
  75733. var DistanceJoint = /** @class */ (function (_super) {
  75734. __extends(DistanceJoint, _super);
  75735. function DistanceJoint(jointData) {
  75736. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75737. }
  75738. /**
  75739. * Update the predefined distance.
  75740. */
  75741. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75742. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75743. };
  75744. return DistanceJoint;
  75745. }(PhysicsJoint));
  75746. BABYLON.DistanceJoint = DistanceJoint;
  75747. var MotorEnabledJoint = /** @class */ (function (_super) {
  75748. __extends(MotorEnabledJoint, _super);
  75749. function MotorEnabledJoint(type, jointData) {
  75750. return _super.call(this, type, jointData) || this;
  75751. }
  75752. /**
  75753. * Set the motor values.
  75754. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75755. * @param {number} force the force to apply
  75756. * @param {number} maxForce max force for this motor.
  75757. */
  75758. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75759. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75760. };
  75761. /**
  75762. * Set the motor's limits.
  75763. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75764. */
  75765. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75766. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75767. };
  75768. return MotorEnabledJoint;
  75769. }(PhysicsJoint));
  75770. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75771. /**
  75772. * This class represents a single hinge physics joint
  75773. */
  75774. var HingeJoint = /** @class */ (function (_super) {
  75775. __extends(HingeJoint, _super);
  75776. function HingeJoint(jointData) {
  75777. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75778. }
  75779. /**
  75780. * Set the motor values.
  75781. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75782. * @param {number} force the force to apply
  75783. * @param {number} maxForce max force for this motor.
  75784. */
  75785. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75786. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75787. };
  75788. /**
  75789. * Set the motor's limits.
  75790. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75791. */
  75792. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75793. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75794. };
  75795. return HingeJoint;
  75796. }(MotorEnabledJoint));
  75797. BABYLON.HingeJoint = HingeJoint;
  75798. /**
  75799. * This class represents a dual hinge physics joint (same as wheel joint)
  75800. */
  75801. var Hinge2Joint = /** @class */ (function (_super) {
  75802. __extends(Hinge2Joint, _super);
  75803. function Hinge2Joint(jointData) {
  75804. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75805. }
  75806. /**
  75807. * Set the motor values.
  75808. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75809. * @param {number} force the force to apply
  75810. * @param {number} maxForce max force for this motor.
  75811. * @param {motorIndex} the motor's index, 0 or 1.
  75812. */
  75813. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75814. if (motorIndex === void 0) { motorIndex = 0; }
  75815. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75816. };
  75817. /**
  75818. * Set the motor limits.
  75819. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75820. * @param {number} upperLimit the upper limit
  75821. * @param {number} lowerLimit lower limit
  75822. * @param {motorIndex} the motor's index, 0 or 1.
  75823. */
  75824. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75825. if (motorIndex === void 0) { motorIndex = 0; }
  75826. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75827. };
  75828. return Hinge2Joint;
  75829. }(MotorEnabledJoint));
  75830. BABYLON.Hinge2Joint = Hinge2Joint;
  75831. })(BABYLON || (BABYLON = {}));
  75832. //# sourceMappingURL=babylon.physicsJoint.js.map
  75833. var BABYLON;
  75834. (function (BABYLON) {
  75835. var PhysicsImpostor = /** @class */ (function () {
  75836. function PhysicsImpostor(object, type, _options, _scene) {
  75837. if (_options === void 0) { _options = { mass: 0 }; }
  75838. var _this = this;
  75839. this.object = object;
  75840. this.type = type;
  75841. this._options = _options;
  75842. this._scene = _scene;
  75843. this._bodyUpdateRequired = false;
  75844. this._onBeforePhysicsStepCallbacks = new Array();
  75845. this._onAfterPhysicsStepCallbacks = new Array();
  75846. this._onPhysicsCollideCallbacks = [];
  75847. this._deltaPosition = BABYLON.Vector3.Zero();
  75848. this._isDisposed = false;
  75849. //temp variables for parent rotation calculations
  75850. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75851. this._tmpQuat = new BABYLON.Quaternion();
  75852. this._tmpQuat2 = new BABYLON.Quaternion();
  75853. /**
  75854. * this function is executed by the physics engine.
  75855. */
  75856. this.beforeStep = function () {
  75857. if (!_this._physicsEngine) {
  75858. return;
  75859. }
  75860. _this.object.translate(_this._deltaPosition, -1);
  75861. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75862. _this.object.computeWorldMatrix(false);
  75863. if (_this.object.parent && _this.object.rotationQuaternion) {
  75864. _this.getParentsRotation();
  75865. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75866. }
  75867. else {
  75868. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75869. }
  75870. if (!_this._options.disableBidirectionalTransformation) {
  75871. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75872. }
  75873. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75874. func(_this);
  75875. });
  75876. };
  75877. /**
  75878. * this function is executed by the physics engine.
  75879. */
  75880. this.afterStep = function () {
  75881. if (!_this._physicsEngine) {
  75882. return;
  75883. }
  75884. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75885. func(_this);
  75886. });
  75887. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75888. // object has now its world rotation. needs to be converted to local.
  75889. if (_this.object.parent && _this.object.rotationQuaternion) {
  75890. _this.getParentsRotation();
  75891. _this._tmpQuat.conjugateInPlace();
  75892. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75893. }
  75894. // take the position set and make it the absolute position of this object.
  75895. _this.object.setAbsolutePosition(_this.object.position);
  75896. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75897. _this.object.translate(_this._deltaPosition, 1);
  75898. };
  75899. /**
  75900. * Legacy collision detection event support
  75901. */
  75902. this.onCollideEvent = null;
  75903. //event and body object due to cannon's event-based architecture.
  75904. this.onCollide = function (e) {
  75905. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75906. return;
  75907. }
  75908. if (!_this._physicsEngine) {
  75909. return;
  75910. }
  75911. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75912. if (otherImpostor) {
  75913. // Legacy collision detection event support
  75914. if (_this.onCollideEvent) {
  75915. _this.onCollideEvent(_this, otherImpostor);
  75916. }
  75917. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75918. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75919. }).forEach(function (obj) {
  75920. obj.callback(_this, otherImpostor);
  75921. });
  75922. }
  75923. };
  75924. //sanity check!
  75925. if (!this.object) {
  75926. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75927. return;
  75928. }
  75929. //legacy support for old syntax.
  75930. if (!this._scene && object.getScene) {
  75931. this._scene = object.getScene();
  75932. }
  75933. if (!this._scene) {
  75934. return;
  75935. }
  75936. this._physicsEngine = this._scene.getPhysicsEngine();
  75937. if (!this._physicsEngine) {
  75938. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75939. }
  75940. else {
  75941. //set the object's quaternion, if not set
  75942. if (!this.object.rotationQuaternion) {
  75943. if (this.object.rotation) {
  75944. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75945. }
  75946. else {
  75947. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75948. }
  75949. }
  75950. //default options params
  75951. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75952. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75953. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75954. this._joints = [];
  75955. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75956. if (!this.object.parent || this._options.ignoreParent) {
  75957. this._init();
  75958. }
  75959. else if (this.object.parent.physicsImpostor) {
  75960. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75961. }
  75962. }
  75963. }
  75964. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75965. get: function () {
  75966. return this._isDisposed;
  75967. },
  75968. enumerable: true,
  75969. configurable: true
  75970. });
  75971. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75972. get: function () {
  75973. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75974. },
  75975. set: function (value) {
  75976. this.setMass(value);
  75977. },
  75978. enumerable: true,
  75979. configurable: true
  75980. });
  75981. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75982. get: function () {
  75983. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75984. },
  75985. set: function (value) {
  75986. if (!this._physicsEngine) {
  75987. return;
  75988. }
  75989. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75990. },
  75991. enumerable: true,
  75992. configurable: true
  75993. });
  75994. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75995. get: function () {
  75996. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75997. },
  75998. set: function (value) {
  75999. if (!this._physicsEngine) {
  76000. return;
  76001. }
  76002. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76003. },
  76004. enumerable: true,
  76005. configurable: true
  76006. });
  76007. /**
  76008. * This function will completly initialize this impostor.
  76009. * It will create a new body - but only if this mesh has no parent.
  76010. * If it has, this impostor will not be used other than to define the impostor
  76011. * of the child mesh.
  76012. */
  76013. PhysicsImpostor.prototype._init = function () {
  76014. if (!this._physicsEngine) {
  76015. return;
  76016. }
  76017. this._physicsEngine.removeImpostor(this);
  76018. this.physicsBody = null;
  76019. this._parent = this._parent || this._getPhysicsParent();
  76020. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76021. this._physicsEngine.addImpostor(this);
  76022. }
  76023. };
  76024. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76025. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76026. var parentMesh = this.object.parent;
  76027. return parentMesh.physicsImpostor;
  76028. }
  76029. return null;
  76030. };
  76031. /**
  76032. * Should a new body be generated.
  76033. */
  76034. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76035. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76036. };
  76037. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76038. this.forceUpdate();
  76039. };
  76040. /**
  76041. * Force a regeneration of this or the parent's impostor's body.
  76042. * Use under cautious - This will remove all joints already implemented.
  76043. */
  76044. PhysicsImpostor.prototype.forceUpdate = function () {
  76045. this._init();
  76046. if (this.parent && !this._options.ignoreParent) {
  76047. this.parent.forceUpdate();
  76048. }
  76049. };
  76050. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76051. /*public get mesh(): AbstractMesh {
  76052. return this._mesh;
  76053. }*/
  76054. /**
  76055. * Gets the body that holds this impostor. Either its own, or its parent.
  76056. */
  76057. get: function () {
  76058. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76059. },
  76060. /**
  76061. * Set the physics body. Used mainly by the physics engine/plugin
  76062. */
  76063. set: function (physicsBody) {
  76064. if (this._physicsBody && this._physicsEngine) {
  76065. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76066. }
  76067. this._physicsBody = physicsBody;
  76068. this.resetUpdateFlags();
  76069. },
  76070. enumerable: true,
  76071. configurable: true
  76072. });
  76073. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76074. get: function () {
  76075. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76076. },
  76077. set: function (value) {
  76078. this._parent = value;
  76079. },
  76080. enumerable: true,
  76081. configurable: true
  76082. });
  76083. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76084. this._bodyUpdateRequired = false;
  76085. };
  76086. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76087. if (this.object.getBoundingInfo) {
  76088. var q = this.object.rotationQuaternion;
  76089. //reset rotation
  76090. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76091. //calculate the world matrix with no rotation
  76092. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76093. var boundingInfo = this.object.getBoundingInfo();
  76094. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76095. //bring back the rotation
  76096. this.object.rotationQuaternion = q;
  76097. //calculate the world matrix with the new rotation
  76098. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76099. return size;
  76100. }
  76101. else {
  76102. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76103. }
  76104. };
  76105. PhysicsImpostor.prototype.getObjectCenter = function () {
  76106. if (this.object.getBoundingInfo) {
  76107. var boundingInfo = this.object.getBoundingInfo();
  76108. return boundingInfo.boundingBox.centerWorld;
  76109. }
  76110. else {
  76111. return this.object.position;
  76112. }
  76113. };
  76114. /**
  76115. * Get a specific parametes from the options parameter.
  76116. */
  76117. PhysicsImpostor.prototype.getParam = function (paramName) {
  76118. return this._options[paramName];
  76119. };
  76120. /**
  76121. * Sets a specific parameter in the options given to the physics plugin
  76122. */
  76123. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76124. this._options[paramName] = value;
  76125. this._bodyUpdateRequired = true;
  76126. };
  76127. /**
  76128. * Specifically change the body's mass option. Won't recreate the physics body object
  76129. */
  76130. PhysicsImpostor.prototype.setMass = function (mass) {
  76131. if (this.getParam("mass") !== mass) {
  76132. this.setParam("mass", mass);
  76133. }
  76134. if (this._physicsEngine) {
  76135. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76136. }
  76137. };
  76138. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76139. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76140. };
  76141. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76142. if (this._physicsEngine) {
  76143. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76144. }
  76145. };
  76146. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76147. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76148. };
  76149. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76150. if (this._physicsEngine) {
  76151. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76152. }
  76153. };
  76154. /**
  76155. * Execute a function with the physics plugin native code.
  76156. * Provide a function the will have two variables - the world object and the physics body object.
  76157. */
  76158. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76159. if (this._physicsEngine) {
  76160. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76161. }
  76162. };
  76163. /**
  76164. * Register a function that will be executed before the physics world is stepping forward.
  76165. */
  76166. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76167. this._onBeforePhysicsStepCallbacks.push(func);
  76168. };
  76169. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76170. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76171. if (index > -1) {
  76172. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76173. }
  76174. else {
  76175. BABYLON.Tools.Warn("Function to remove was not found");
  76176. }
  76177. };
  76178. /**
  76179. * Register a function that will be executed after the physics step
  76180. */
  76181. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76182. this._onAfterPhysicsStepCallbacks.push(func);
  76183. };
  76184. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76185. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76186. if (index > -1) {
  76187. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76188. }
  76189. else {
  76190. BABYLON.Tools.Warn("Function to remove was not found");
  76191. }
  76192. };
  76193. /**
  76194. * register a function that will be executed when this impostor collides against a different body.
  76195. */
  76196. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76197. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76198. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76199. };
  76200. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76201. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76202. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76203. if (index > -1) {
  76204. this._onPhysicsCollideCallbacks.splice(index, 1);
  76205. }
  76206. else {
  76207. BABYLON.Tools.Warn("Function to remove was not found");
  76208. }
  76209. };
  76210. PhysicsImpostor.prototype.getParentsRotation = function () {
  76211. var parent = this.object.parent;
  76212. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76213. while (parent) {
  76214. if (parent.rotationQuaternion) {
  76215. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76216. }
  76217. else {
  76218. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76219. }
  76220. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76221. parent = parent.parent;
  76222. }
  76223. return this._tmpQuat;
  76224. };
  76225. /**
  76226. * Apply a force
  76227. */
  76228. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76229. if (this._physicsEngine) {
  76230. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76231. }
  76232. return this;
  76233. };
  76234. /**
  76235. * Apply an impulse
  76236. */
  76237. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76238. if (this._physicsEngine) {
  76239. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76240. }
  76241. return this;
  76242. };
  76243. /**
  76244. * A help function to create a joint.
  76245. */
  76246. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76247. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76248. this.addJoint(otherImpostor, joint);
  76249. return this;
  76250. };
  76251. /**
  76252. * Add a joint to this impostor with a different impostor.
  76253. */
  76254. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76255. this._joints.push({
  76256. otherImpostor: otherImpostor,
  76257. joint: joint
  76258. });
  76259. if (this._physicsEngine) {
  76260. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76261. }
  76262. return this;
  76263. };
  76264. /**
  76265. * Will keep this body still, in a sleep mode.
  76266. */
  76267. PhysicsImpostor.prototype.sleep = function () {
  76268. if (this._physicsEngine) {
  76269. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76270. }
  76271. return this;
  76272. };
  76273. /**
  76274. * Wake the body up.
  76275. */
  76276. PhysicsImpostor.prototype.wakeUp = function () {
  76277. if (this._physicsEngine) {
  76278. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76279. }
  76280. return this;
  76281. };
  76282. PhysicsImpostor.prototype.clone = function (newObject) {
  76283. if (!newObject)
  76284. return null;
  76285. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76286. };
  76287. PhysicsImpostor.prototype.dispose = function () {
  76288. var _this = this;
  76289. //no dispose if no physics engine is available.
  76290. if (!this._physicsEngine) {
  76291. return;
  76292. }
  76293. this._joints.forEach(function (j) {
  76294. if (_this._physicsEngine) {
  76295. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76296. }
  76297. });
  76298. //dispose the physics body
  76299. this._physicsEngine.removeImpostor(this);
  76300. if (this.parent) {
  76301. this.parent.forceUpdate();
  76302. }
  76303. else {
  76304. /*this._object.getChildMeshes().forEach(function(mesh) {
  76305. if (mesh.physicsImpostor) {
  76306. if (disposeChildren) {
  76307. mesh.physicsImpostor.dispose();
  76308. mesh.physicsImpostor = null;
  76309. }
  76310. }
  76311. })*/
  76312. }
  76313. this._isDisposed = true;
  76314. };
  76315. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76316. this._deltaPosition.copyFrom(position);
  76317. };
  76318. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76319. if (!this._deltaRotation) {
  76320. this._deltaRotation = new BABYLON.Quaternion();
  76321. }
  76322. this._deltaRotation.copyFrom(rotation);
  76323. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76324. };
  76325. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76326. if (this._physicsEngine) {
  76327. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76328. }
  76329. return this;
  76330. };
  76331. PhysicsImpostor.prototype.getRadius = function () {
  76332. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76333. };
  76334. /**
  76335. * Sync a bone with this impostor
  76336. * @param bone The bone to sync to the impostor.
  76337. * @param boneMesh The mesh that the bone is influencing.
  76338. * @param jointPivot The pivot of the joint / bone in local space.
  76339. * @param distToJoint Optional distance from the impostor to the joint.
  76340. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76341. */
  76342. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76343. var tempVec = PhysicsImpostor._tmpVecs[0];
  76344. var mesh = this.object;
  76345. if (mesh.rotationQuaternion) {
  76346. if (adjustRotation) {
  76347. var tempQuat = PhysicsImpostor._tmpQuat;
  76348. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76349. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76350. }
  76351. else {
  76352. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76353. }
  76354. }
  76355. tempVec.x = 0;
  76356. tempVec.y = 0;
  76357. tempVec.z = 0;
  76358. if (jointPivot) {
  76359. tempVec.x = jointPivot.x;
  76360. tempVec.y = jointPivot.y;
  76361. tempVec.z = jointPivot.z;
  76362. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76363. if (distToJoint === undefined || distToJoint === null) {
  76364. distToJoint = jointPivot.length();
  76365. }
  76366. tempVec.x *= distToJoint;
  76367. tempVec.y *= distToJoint;
  76368. tempVec.z *= distToJoint;
  76369. }
  76370. if (bone.getParent()) {
  76371. tempVec.addInPlace(mesh.getAbsolutePosition());
  76372. bone.setAbsolutePosition(tempVec, boneMesh);
  76373. }
  76374. else {
  76375. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76376. boneMesh.position.x -= tempVec.x;
  76377. boneMesh.position.y -= tempVec.y;
  76378. boneMesh.position.z -= tempVec.z;
  76379. }
  76380. };
  76381. /**
  76382. * Sync impostor to a bone
  76383. * @param bone The bone that the impostor will be synced to.
  76384. * @param boneMesh The mesh that the bone is influencing.
  76385. * @param jointPivot The pivot of the joint / bone in local space.
  76386. * @param distToJoint Optional distance from the impostor to the joint.
  76387. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76388. * @param boneAxis Optional vector3 axis the bone is aligned with
  76389. */
  76390. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76391. var mesh = this.object;
  76392. if (mesh.rotationQuaternion) {
  76393. if (adjustRotation) {
  76394. var tempQuat = PhysicsImpostor._tmpQuat;
  76395. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76396. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76397. }
  76398. else {
  76399. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76400. }
  76401. }
  76402. var pos = PhysicsImpostor._tmpVecs[0];
  76403. var boneDir = PhysicsImpostor._tmpVecs[1];
  76404. if (!boneAxis) {
  76405. boneAxis = PhysicsImpostor._tmpVecs[2];
  76406. boneAxis.x = 0;
  76407. boneAxis.y = 1;
  76408. boneAxis.z = 0;
  76409. }
  76410. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76411. bone.getAbsolutePositionToRef(boneMesh, pos);
  76412. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76413. distToJoint = jointPivot.length();
  76414. }
  76415. if (distToJoint !== undefined && distToJoint !== null) {
  76416. pos.x += boneDir.x * distToJoint;
  76417. pos.y += boneDir.y * distToJoint;
  76418. pos.z += boneDir.z * distToJoint;
  76419. }
  76420. mesh.setAbsolutePosition(pos);
  76421. };
  76422. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76423. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76424. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76425. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76426. //Impostor types
  76427. PhysicsImpostor.NoImpostor = 0;
  76428. PhysicsImpostor.SphereImpostor = 1;
  76429. PhysicsImpostor.BoxImpostor = 2;
  76430. PhysicsImpostor.PlaneImpostor = 3;
  76431. PhysicsImpostor.MeshImpostor = 4;
  76432. PhysicsImpostor.CylinderImpostor = 7;
  76433. PhysicsImpostor.ParticleImpostor = 8;
  76434. PhysicsImpostor.HeightmapImpostor = 9;
  76435. return PhysicsImpostor;
  76436. }());
  76437. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76438. })(BABYLON || (BABYLON = {}));
  76439. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76440. var BABYLON;
  76441. (function (BABYLON) {
  76442. var PhysicsEngine = /** @class */ (function () {
  76443. function PhysicsEngine(gravity, _physicsPlugin) {
  76444. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76445. this._physicsPlugin = _physicsPlugin;
  76446. //new methods and parameters
  76447. this._impostors = [];
  76448. this._joints = [];
  76449. if (!this._physicsPlugin.isSupported()) {
  76450. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76451. + "Please make sure it is included.");
  76452. }
  76453. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76454. this.setGravity(gravity);
  76455. this.setTimeStep();
  76456. }
  76457. PhysicsEngine.prototype.setGravity = function (gravity) {
  76458. this.gravity = gravity;
  76459. this._physicsPlugin.setGravity(this.gravity);
  76460. };
  76461. /**
  76462. * Set the time step of the physics engine.
  76463. * default is 1/60.
  76464. * To slow it down, enter 1/600 for example.
  76465. * To speed it up, 1/30
  76466. * @param {number} newTimeStep the new timestep to apply to this world.
  76467. */
  76468. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76469. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76470. this._physicsPlugin.setTimeStep(newTimeStep);
  76471. };
  76472. /**
  76473. * Get the time step of the physics engine.
  76474. */
  76475. PhysicsEngine.prototype.getTimeStep = function () {
  76476. return this._physicsPlugin.getTimeStep();
  76477. };
  76478. PhysicsEngine.prototype.dispose = function () {
  76479. this._impostors.forEach(function (impostor) {
  76480. impostor.dispose();
  76481. });
  76482. this._physicsPlugin.dispose();
  76483. };
  76484. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76485. return this._physicsPlugin.name;
  76486. };
  76487. /**
  76488. * Adding a new impostor for the impostor tracking.
  76489. * This will be done by the impostor itself.
  76490. * @param {PhysicsImpostor} impostor the impostor to add
  76491. */
  76492. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76493. impostor.uniqueId = this._impostors.push(impostor);
  76494. //if no parent, generate the body
  76495. if (!impostor.parent) {
  76496. this._physicsPlugin.generatePhysicsBody(impostor);
  76497. }
  76498. };
  76499. /**
  76500. * Remove an impostor from the engine.
  76501. * This impostor and its mesh will not longer be updated by the physics engine.
  76502. * @param {PhysicsImpostor} impostor the impostor to remove
  76503. */
  76504. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76505. var index = this._impostors.indexOf(impostor);
  76506. if (index > -1) {
  76507. var removed = this._impostors.splice(index, 1);
  76508. //Is it needed?
  76509. if (removed.length) {
  76510. //this will also remove it from the world.
  76511. removed[0].physicsBody = null;
  76512. }
  76513. }
  76514. };
  76515. /**
  76516. * Add a joint to the physics engine
  76517. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76518. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76519. * @param {PhysicsJoint} the joint that will connect both impostors.
  76520. */
  76521. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76522. var impostorJoint = {
  76523. mainImpostor: mainImpostor,
  76524. connectedImpostor: connectedImpostor,
  76525. joint: joint
  76526. };
  76527. joint.physicsPlugin = this._physicsPlugin;
  76528. this._joints.push(impostorJoint);
  76529. this._physicsPlugin.generateJoint(impostorJoint);
  76530. };
  76531. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76532. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76533. return (impostorJoint.connectedImpostor === connectedImpostor
  76534. && impostorJoint.joint === joint
  76535. && impostorJoint.mainImpostor === mainImpostor);
  76536. });
  76537. if (matchingJoints.length) {
  76538. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76539. //TODO remove it from the list as well
  76540. }
  76541. };
  76542. /**
  76543. * Called by the scene. no need to call it.
  76544. */
  76545. PhysicsEngine.prototype._step = function (delta) {
  76546. var _this = this;
  76547. //check if any mesh has no body / requires an update
  76548. this._impostors.forEach(function (impostor) {
  76549. if (impostor.isBodyInitRequired()) {
  76550. _this._physicsPlugin.generatePhysicsBody(impostor);
  76551. }
  76552. });
  76553. if (delta > 0.1) {
  76554. delta = 0.1;
  76555. }
  76556. else if (delta <= 0) {
  76557. delta = 1.0 / 60.0;
  76558. }
  76559. this._physicsPlugin.executeStep(delta, this._impostors);
  76560. };
  76561. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76562. return this._physicsPlugin;
  76563. };
  76564. PhysicsEngine.prototype.getImpostors = function () {
  76565. return this._impostors;
  76566. };
  76567. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76568. for (var i = 0; i < this._impostors.length; ++i) {
  76569. if (this._impostors[i].object === object) {
  76570. return this._impostors[i];
  76571. }
  76572. }
  76573. return null;
  76574. };
  76575. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76576. for (var i = 0; i < this._impostors.length; ++i) {
  76577. if (this._impostors[i].physicsBody === body) {
  76578. return this._impostors[i];
  76579. }
  76580. }
  76581. return null;
  76582. };
  76583. // Statics
  76584. PhysicsEngine.Epsilon = 0.001;
  76585. return PhysicsEngine;
  76586. }());
  76587. BABYLON.PhysicsEngine = PhysicsEngine;
  76588. })(BABYLON || (BABYLON = {}));
  76589. //# sourceMappingURL=babylon.physicsEngine.js.map
  76590. var BABYLON;
  76591. (function (BABYLON) {
  76592. var PhysicsHelper = /** @class */ (function () {
  76593. function PhysicsHelper(scene) {
  76594. this._scene = scene;
  76595. this._physicsEngine = this._scene.getPhysicsEngine();
  76596. if (!this._physicsEngine) {
  76597. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76598. }
  76599. }
  76600. /**
  76601. * @param {Vector3} origin the origin of the explosion
  76602. * @param {number} radius the explosion radius
  76603. * @param {number} strength the explosion strength
  76604. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76605. */
  76606. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76607. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76608. if (!this._physicsEngine) {
  76609. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76610. return null;
  76611. }
  76612. var impostors = this._physicsEngine.getImpostors();
  76613. if (impostors.length === 0) {
  76614. return null;
  76615. }
  76616. var event = new PhysicsRadialExplosionEvent(this._scene);
  76617. impostors.forEach(function (impostor) {
  76618. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76619. if (!impostorForceAndContactPoint) {
  76620. return;
  76621. }
  76622. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76623. });
  76624. event.dispose(false);
  76625. return event;
  76626. };
  76627. /**
  76628. * @param {Vector3} origin the origin of the explosion
  76629. * @param {number} radius the explosion radius
  76630. * @param {number} strength the explosion strength
  76631. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76632. */
  76633. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76634. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76635. if (!this._physicsEngine) {
  76636. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76637. return null;
  76638. }
  76639. var impostors = this._physicsEngine.getImpostors();
  76640. if (impostors.length === 0) {
  76641. return null;
  76642. }
  76643. var event = new PhysicsRadialExplosionEvent(this._scene);
  76644. impostors.forEach(function (impostor) {
  76645. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76646. if (!impostorForceAndContactPoint) {
  76647. return;
  76648. }
  76649. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76650. });
  76651. event.dispose(false);
  76652. return event;
  76653. };
  76654. /**
  76655. * @param {Vector3} origin the origin of the explosion
  76656. * @param {number} radius the explosion radius
  76657. * @param {number} strength the explosion strength
  76658. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76659. */
  76660. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76661. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76662. if (!this._physicsEngine) {
  76663. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76664. return null;
  76665. }
  76666. var impostors = this._physicsEngine.getImpostors();
  76667. if (impostors.length === 0) {
  76668. return null;
  76669. }
  76670. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76671. event.dispose(false);
  76672. return event;
  76673. };
  76674. /**
  76675. * @param {Vector3} origin the origin of the updraft
  76676. * @param {number} radius the radius of the updraft
  76677. * @param {number} strength the strength of the updraft
  76678. * @param {number} height the height of the updraft
  76679. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76680. */
  76681. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76682. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76683. if (!this._physicsEngine) {
  76684. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76685. return null;
  76686. }
  76687. if (this._physicsEngine.getImpostors().length === 0) {
  76688. return null;
  76689. }
  76690. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76691. event.dispose(false);
  76692. return event;
  76693. };
  76694. /**
  76695. * @param {Vector3} origin the of the vortex
  76696. * @param {number} radius the radius of the vortex
  76697. * @param {number} strength the strength of the vortex
  76698. * @param {number} height the height of the vortex
  76699. */
  76700. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76701. if (!this._physicsEngine) {
  76702. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76703. return null;
  76704. }
  76705. if (this._physicsEngine.getImpostors().length === 0) {
  76706. return null;
  76707. }
  76708. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76709. event.dispose(false);
  76710. return event;
  76711. };
  76712. return PhysicsHelper;
  76713. }());
  76714. BABYLON.PhysicsHelper = PhysicsHelper;
  76715. /***** Radial explosion *****/
  76716. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76717. function PhysicsRadialExplosionEvent(scene) {
  76718. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76719. this._rays = [];
  76720. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76721. this._scene = scene;
  76722. }
  76723. /**
  76724. * Returns the data related to the radial explosion event (sphere & rays).
  76725. * @returns {PhysicsRadialExplosionEventData}
  76726. */
  76727. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76728. this._dataFetched = true;
  76729. return {
  76730. sphere: this._sphere,
  76731. rays: this._rays,
  76732. };
  76733. };
  76734. /**
  76735. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76736. * @param impostor
  76737. * @param {Vector3} origin the origin of the explosion
  76738. * @param {number} radius the explosion radius
  76739. * @param {number} strength the explosion strength
  76740. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76741. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76742. */
  76743. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76744. if (impostor.mass === 0) {
  76745. return null;
  76746. }
  76747. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76748. return null;
  76749. }
  76750. if (impostor.object.getClassName() !== 'Mesh') {
  76751. return null;
  76752. }
  76753. var impostorObject = impostor.object;
  76754. var impostorObjectCenter = impostor.getObjectCenter();
  76755. var direction = impostorObjectCenter.subtract(origin);
  76756. var ray = new BABYLON.Ray(origin, direction, radius);
  76757. this._rays.push(ray);
  76758. var hit = ray.intersectsMesh(impostorObject);
  76759. var contactPoint = hit.pickedPoint;
  76760. if (!contactPoint) {
  76761. return null;
  76762. }
  76763. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76764. if (distanceFromOrigin > radius) {
  76765. return null;
  76766. }
  76767. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76768. ? strength
  76769. : strength * (1 - (distanceFromOrigin / radius));
  76770. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76771. return { force: force, contactPoint: contactPoint };
  76772. };
  76773. /**
  76774. * Disposes the sphere.
  76775. * @param {bolean} force
  76776. */
  76777. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76778. var _this = this;
  76779. if (force === void 0) { force = true; }
  76780. if (force) {
  76781. this._sphere.dispose();
  76782. }
  76783. else {
  76784. setTimeout(function () {
  76785. if (!_this._dataFetched) {
  76786. _this._sphere.dispose();
  76787. }
  76788. }, 0);
  76789. }
  76790. };
  76791. /*** Helpers ***/
  76792. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76793. if (!this._sphere) {
  76794. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76795. this._sphere.isVisible = false;
  76796. }
  76797. };
  76798. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76799. var impostorObject = impostor.object;
  76800. this._prepareSphere();
  76801. this._sphere.position = origin;
  76802. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76803. this._sphere._updateBoundingInfo();
  76804. this._sphere.computeWorldMatrix(true);
  76805. return this._sphere.intersectsMesh(impostorObject, true);
  76806. };
  76807. return PhysicsRadialExplosionEvent;
  76808. }());
  76809. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76810. /***** Gravitational Field *****/
  76811. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76812. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76813. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76814. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76815. this._physicsHelper = physicsHelper;
  76816. this._scene = scene;
  76817. this._origin = origin;
  76818. this._radius = radius;
  76819. this._strength = strength;
  76820. this._falloff = falloff;
  76821. this._tickCallback = this._tick.bind(this);
  76822. }
  76823. /**
  76824. * Returns the data related to the gravitational field event (sphere).
  76825. * @returns {PhysicsGravitationalFieldEventData}
  76826. */
  76827. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76828. this._dataFetched = true;
  76829. return {
  76830. sphere: this._sphere,
  76831. };
  76832. };
  76833. /**
  76834. * Enables the gravitational field.
  76835. */
  76836. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76837. this._tickCallback.call(this);
  76838. this._scene.registerBeforeRender(this._tickCallback);
  76839. };
  76840. /**
  76841. * Disables the gravitational field.
  76842. */
  76843. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76844. this._scene.unregisterBeforeRender(this._tickCallback);
  76845. };
  76846. /**
  76847. * Disposes the sphere.
  76848. * @param {bolean} force
  76849. */
  76850. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76851. var _this = this;
  76852. if (force === void 0) { force = true; }
  76853. if (force) {
  76854. this._sphere.dispose();
  76855. }
  76856. else {
  76857. setTimeout(function () {
  76858. if (!_this._dataFetched) {
  76859. _this._sphere.dispose();
  76860. }
  76861. }, 0);
  76862. }
  76863. };
  76864. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76865. // Since the params won't change, we fetch the event only once
  76866. if (this._sphere) {
  76867. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76868. }
  76869. else {
  76870. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76871. if (radialExplosionEvent) {
  76872. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76873. }
  76874. }
  76875. };
  76876. return PhysicsGravitationalFieldEvent;
  76877. }());
  76878. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76879. /***** Updraft *****/
  76880. var PhysicsUpdraftEvent = /** @class */ (function () {
  76881. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76882. this._scene = _scene;
  76883. this._origin = _origin;
  76884. this._radius = _radius;
  76885. this._strength = _strength;
  76886. this._height = _height;
  76887. this._updraftMode = _updraftMode;
  76888. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76889. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76890. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76891. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76892. this._physicsEngine = this._scene.getPhysicsEngine();
  76893. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76894. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76895. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76896. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76897. }
  76898. this._tickCallback = this._tick.bind(this);
  76899. }
  76900. /**
  76901. * Returns the data related to the updraft event (cylinder).
  76902. * @returns {PhysicsUpdraftEventData}
  76903. */
  76904. PhysicsUpdraftEvent.prototype.getData = function () {
  76905. this._dataFetched = true;
  76906. return {
  76907. cylinder: this._cylinder,
  76908. };
  76909. };
  76910. /**
  76911. * Enables the updraft.
  76912. */
  76913. PhysicsUpdraftEvent.prototype.enable = function () {
  76914. this._tickCallback.call(this);
  76915. this._scene.registerBeforeRender(this._tickCallback);
  76916. };
  76917. /**
  76918. * Disables the cortex.
  76919. */
  76920. PhysicsUpdraftEvent.prototype.disable = function () {
  76921. this._scene.unregisterBeforeRender(this._tickCallback);
  76922. };
  76923. /**
  76924. * Disposes the sphere.
  76925. * @param {bolean} force
  76926. */
  76927. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76928. var _this = this;
  76929. if (force === void 0) { force = true; }
  76930. if (force) {
  76931. this._cylinder.dispose();
  76932. }
  76933. else {
  76934. setTimeout(function () {
  76935. if (!_this._dataFetched) {
  76936. _this._cylinder.dispose();
  76937. }
  76938. }, 0);
  76939. }
  76940. };
  76941. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76942. if (impostor.mass === 0) {
  76943. return null;
  76944. }
  76945. if (!this._intersectsWithCylinder(impostor)) {
  76946. return null;
  76947. }
  76948. var impostorObjectCenter = impostor.getObjectCenter();
  76949. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76950. var direction = this._originDirection;
  76951. }
  76952. else {
  76953. var direction = impostorObjectCenter.subtract(this._originTop);
  76954. }
  76955. var multiplier = this._strength * -1;
  76956. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76957. return { force: force, contactPoint: impostorObjectCenter };
  76958. };
  76959. PhysicsUpdraftEvent.prototype._tick = function () {
  76960. var _this = this;
  76961. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76962. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76963. if (!impostorForceAndContactPoint) {
  76964. return;
  76965. }
  76966. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76967. });
  76968. };
  76969. /*** Helpers ***/
  76970. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76971. if (!this._cylinder) {
  76972. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76973. height: this._height,
  76974. diameter: this._radius * 2,
  76975. }, this._scene);
  76976. this._cylinder.isVisible = false;
  76977. }
  76978. };
  76979. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76980. var impostorObject = impostor.object;
  76981. this._prepareCylinder();
  76982. this._cylinder.position = this._cylinderPosition;
  76983. return this._cylinder.intersectsMesh(impostorObject, true);
  76984. };
  76985. return PhysicsUpdraftEvent;
  76986. }());
  76987. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76988. /***** Vortex *****/
  76989. var PhysicsVortexEvent = /** @class */ (function () {
  76990. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76991. this._scene = _scene;
  76992. this._origin = _origin;
  76993. this._radius = _radius;
  76994. this._strength = _strength;
  76995. this._height = _height;
  76996. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76997. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76998. this._updraftMultiplier = 0.02;
  76999. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77000. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77001. this._physicsEngine = this._scene.getPhysicsEngine();
  77002. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77003. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77004. this._tickCallback = this._tick.bind(this);
  77005. }
  77006. /**
  77007. * Returns the data related to the vortex event (cylinder).
  77008. * @returns {PhysicsVortexEventData}
  77009. */
  77010. PhysicsVortexEvent.prototype.getData = function () {
  77011. this._dataFetched = true;
  77012. return {
  77013. cylinder: this._cylinder,
  77014. };
  77015. };
  77016. /**
  77017. * Enables the vortex.
  77018. */
  77019. PhysicsVortexEvent.prototype.enable = function () {
  77020. this._tickCallback.call(this);
  77021. this._scene.registerBeforeRender(this._tickCallback);
  77022. };
  77023. /**
  77024. * Disables the cortex.
  77025. */
  77026. PhysicsVortexEvent.prototype.disable = function () {
  77027. this._scene.unregisterBeforeRender(this._tickCallback);
  77028. };
  77029. /**
  77030. * Disposes the sphere.
  77031. * @param {bolean} force
  77032. */
  77033. PhysicsVortexEvent.prototype.dispose = function (force) {
  77034. var _this = this;
  77035. if (force === void 0) { force = true; }
  77036. if (force) {
  77037. this._cylinder.dispose();
  77038. }
  77039. else {
  77040. setTimeout(function () {
  77041. if (!_this._dataFetched) {
  77042. _this._cylinder.dispose();
  77043. }
  77044. }, 0);
  77045. }
  77046. };
  77047. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77048. if (impostor.mass === 0) {
  77049. return null;
  77050. }
  77051. if (!this._intersectsWithCylinder(impostor)) {
  77052. return null;
  77053. }
  77054. if (impostor.object.getClassName() !== 'Mesh') {
  77055. return null;
  77056. }
  77057. var impostorObject = impostor.object;
  77058. var impostorObjectCenter = impostor.getObjectCenter();
  77059. 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)
  77060. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77061. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77062. var hit = ray.intersectsMesh(impostorObject);
  77063. var contactPoint = hit.pickedPoint;
  77064. if (!contactPoint) {
  77065. return null;
  77066. }
  77067. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77068. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77069. var directionToOrigin = contactPoint.normalize();
  77070. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77071. directionToOrigin = directionToOrigin.negate();
  77072. }
  77073. // TODO: find a more physically based solution
  77074. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77075. var forceX = directionToOrigin.x * this._strength / 8;
  77076. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77077. var forceZ = directionToOrigin.z * this._strength / 8;
  77078. }
  77079. else {
  77080. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77081. var forceY = this._originTop.y * this._updraftMultiplier;
  77082. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77083. }
  77084. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77085. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77086. return { force: force, contactPoint: impostorObjectCenter };
  77087. };
  77088. PhysicsVortexEvent.prototype._tick = function () {
  77089. var _this = this;
  77090. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77091. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77092. if (!impostorForceAndContactPoint) {
  77093. return;
  77094. }
  77095. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77096. });
  77097. };
  77098. /*** Helpers ***/
  77099. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77100. if (!this._cylinder) {
  77101. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77102. height: this._height,
  77103. diameter: this._radius * 2,
  77104. }, this._scene);
  77105. this._cylinder.isVisible = false;
  77106. }
  77107. };
  77108. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77109. var impostorObject = impostor.object;
  77110. this._prepareCylinder();
  77111. this._cylinder.position = this._cylinderPosition;
  77112. return this._cylinder.intersectsMesh(impostorObject, true);
  77113. };
  77114. return PhysicsVortexEvent;
  77115. }());
  77116. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77117. /***** Enums *****/
  77118. /**
  77119. * The strenght of the force in correspondence to the distance of the affected object
  77120. */
  77121. var PhysicsRadialImpulseFalloff;
  77122. (function (PhysicsRadialImpulseFalloff) {
  77123. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77124. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77125. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77126. /**
  77127. * The strenght of the force in correspondence to the distance of the affected object
  77128. */
  77129. var PhysicsUpdraftMode;
  77130. (function (PhysicsUpdraftMode) {
  77131. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77132. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77133. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77134. })(BABYLON || (BABYLON = {}));
  77135. //# sourceMappingURL=babylon.physicsHelper.js.map
  77136. var BABYLON;
  77137. (function (BABYLON) {
  77138. var CannonJSPlugin = /** @class */ (function () {
  77139. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77140. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77141. if (iterations === void 0) { iterations = 10; }
  77142. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77143. this.name = "CannonJSPlugin";
  77144. this._physicsMaterials = new Array();
  77145. this._fixedTimeStep = 1 / 60;
  77146. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77147. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77148. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77149. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77150. this._tmpPosition = BABYLON.Vector3.Zero();
  77151. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77152. this._tmpUnityRotation = new BABYLON.Quaternion();
  77153. if (!this.isSupported()) {
  77154. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77155. return;
  77156. }
  77157. this._extendNamespace();
  77158. this.world = new this.BJSCANNON.World();
  77159. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77160. this.world.solver.iterations = iterations;
  77161. }
  77162. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77163. this.world.gravity.copy(gravity);
  77164. };
  77165. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77166. this._fixedTimeStep = timeStep;
  77167. };
  77168. CannonJSPlugin.prototype.getTimeStep = function () {
  77169. return this._fixedTimeStep;
  77170. };
  77171. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77172. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77173. };
  77174. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77175. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77176. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77177. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77178. };
  77179. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77180. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77181. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77182. impostor.physicsBody.applyForce(impulse, worldPoint);
  77183. };
  77184. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77185. //parent-child relationship. Does this impostor has a parent impostor?
  77186. if (impostor.parent) {
  77187. if (impostor.physicsBody) {
  77188. this.removePhysicsBody(impostor);
  77189. //TODO is that needed?
  77190. impostor.forceUpdate();
  77191. }
  77192. return;
  77193. }
  77194. //should a new body be created for this impostor?
  77195. if (impostor.isBodyInitRequired()) {
  77196. var shape = this._createShape(impostor);
  77197. //unregister events, if body is being changed
  77198. var oldBody = impostor.physicsBody;
  77199. if (oldBody) {
  77200. this.removePhysicsBody(impostor);
  77201. }
  77202. //create the body and material
  77203. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77204. var bodyCreationObject = {
  77205. mass: impostor.getParam("mass"),
  77206. material: material
  77207. };
  77208. // A simple extend, in case native options were used.
  77209. var nativeOptions = impostor.getParam("nativeOptions");
  77210. for (var key in nativeOptions) {
  77211. if (nativeOptions.hasOwnProperty(key)) {
  77212. bodyCreationObject[key] = nativeOptions[key];
  77213. }
  77214. }
  77215. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77216. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77217. this.world.addEventListener("preStep", impostor.beforeStep);
  77218. this.world.addEventListener("postStep", impostor.afterStep);
  77219. impostor.physicsBody.addShape(shape);
  77220. this.world.add(impostor.physicsBody);
  77221. //try to keep the body moving in the right direction by taking old properties.
  77222. //Should be tested!
  77223. if (oldBody) {
  77224. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77225. impostor.physicsBody[param].copy(oldBody[param]);
  77226. });
  77227. }
  77228. this._processChildMeshes(impostor);
  77229. }
  77230. //now update the body's transformation
  77231. this._updatePhysicsBodyTransformation(impostor);
  77232. };
  77233. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77234. var _this = this;
  77235. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77236. var currentRotation = mainImpostor.object.rotationQuaternion;
  77237. if (meshChildren.length) {
  77238. var processMesh = function (localPosition, mesh) {
  77239. if (!currentRotation || !mesh.rotationQuaternion) {
  77240. return;
  77241. }
  77242. var childImpostor = mesh.getPhysicsImpostor();
  77243. if (childImpostor) {
  77244. var parent = childImpostor.parent;
  77245. if (parent !== mainImpostor) {
  77246. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77247. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77248. if (childImpostor.physicsBody) {
  77249. _this.removePhysicsBody(childImpostor);
  77250. childImpostor.physicsBody = null;
  77251. }
  77252. childImpostor.parent = mainImpostor;
  77253. childImpostor.resetUpdateFlags();
  77254. 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));
  77255. //Add the mass of the children.
  77256. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77257. }
  77258. }
  77259. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77260. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77261. };
  77262. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77263. }
  77264. };
  77265. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77266. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77267. this.world.removeEventListener("preStep", impostor.beforeStep);
  77268. this.world.removeEventListener("postStep", impostor.afterStep);
  77269. this.world.remove(impostor.physicsBody);
  77270. };
  77271. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77272. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77273. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77274. if (!mainBody || !connectedBody) {
  77275. return;
  77276. }
  77277. var constraint;
  77278. var jointData = impostorJoint.joint.jointData;
  77279. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77280. var constraintData = {
  77281. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77282. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77283. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77284. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77285. maxForce: jointData.nativeParams.maxForce,
  77286. collideConnected: !!jointData.collision
  77287. };
  77288. switch (impostorJoint.joint.type) {
  77289. case BABYLON.PhysicsJoint.HingeJoint:
  77290. case BABYLON.PhysicsJoint.Hinge2Joint:
  77291. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77292. break;
  77293. case BABYLON.PhysicsJoint.DistanceJoint:
  77294. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77295. break;
  77296. case BABYLON.PhysicsJoint.SpringJoint:
  77297. var springData = jointData;
  77298. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77299. restLength: springData.length,
  77300. stiffness: springData.stiffness,
  77301. damping: springData.damping,
  77302. localAnchorA: constraintData.pivotA,
  77303. localAnchorB: constraintData.pivotB
  77304. });
  77305. break;
  77306. case BABYLON.PhysicsJoint.LockJoint:
  77307. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77308. break;
  77309. case BABYLON.PhysicsJoint.PointToPointJoint:
  77310. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77311. default:
  77312. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77313. break;
  77314. }
  77315. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77316. constraint.collideConnected = !!jointData.collision;
  77317. impostorJoint.joint.physicsJoint = constraint;
  77318. //don't add spring as constraint, as it is not one.
  77319. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77320. this.world.addConstraint(constraint);
  77321. }
  77322. else {
  77323. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77324. constraint.applyForce();
  77325. });
  77326. }
  77327. };
  77328. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77329. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77330. };
  77331. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77332. var index;
  77333. var mat;
  77334. for (index = 0; index < this._physicsMaterials.length; index++) {
  77335. mat = this._physicsMaterials[index];
  77336. if (mat.friction === friction && mat.restitution === restitution) {
  77337. return mat;
  77338. }
  77339. }
  77340. var currentMat = new this.BJSCANNON.Material(name);
  77341. currentMat.friction = friction;
  77342. currentMat.restitution = restitution;
  77343. this._physicsMaterials.push(currentMat);
  77344. return currentMat;
  77345. };
  77346. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77347. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77348. };
  77349. CannonJSPlugin.prototype._createShape = function (impostor) {
  77350. var object = impostor.object;
  77351. var returnValue;
  77352. var extendSize = impostor.getObjectExtendSize();
  77353. switch (impostor.type) {
  77354. case BABYLON.PhysicsImpostor.SphereImpostor:
  77355. var radiusX = extendSize.x;
  77356. var radiusY = extendSize.y;
  77357. var radiusZ = extendSize.z;
  77358. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77359. break;
  77360. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77361. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77362. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77363. break;
  77364. case BABYLON.PhysicsImpostor.BoxImpostor:
  77365. var box = extendSize.scale(0.5);
  77366. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77367. break;
  77368. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77369. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77370. returnValue = new this.BJSCANNON.Plane();
  77371. break;
  77372. case BABYLON.PhysicsImpostor.MeshImpostor:
  77373. // should transform the vertex data to world coordinates!!
  77374. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77375. var rawFaces = object.getIndices ? object.getIndices() : [];
  77376. if (!rawVerts)
  77377. return;
  77378. // get only scale! so the object could transform correctly.
  77379. var oldPosition = object.position.clone();
  77380. var oldRotation = object.rotation && object.rotation.clone();
  77381. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77382. object.position.copyFromFloats(0, 0, 0);
  77383. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77384. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77385. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77386. var transform = object.computeWorldMatrix(true);
  77387. // convert rawVerts to object space
  77388. var temp = new Array();
  77389. var index;
  77390. for (index = 0; index < rawVerts.length; index += 3) {
  77391. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77392. }
  77393. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77394. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77395. //now set back the transformation!
  77396. object.position.copyFrom(oldPosition);
  77397. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77398. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77399. break;
  77400. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77401. var oldPosition2 = object.position.clone();
  77402. var oldRotation2 = object.rotation && object.rotation.clone();
  77403. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77404. object.position.copyFromFloats(0, 0, 0);
  77405. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77406. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77407. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77408. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77409. returnValue = this._createHeightmap(object);
  77410. object.position.copyFrom(oldPosition2);
  77411. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77412. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77413. object.computeWorldMatrix(true);
  77414. break;
  77415. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77416. returnValue = new this.BJSCANNON.Particle();
  77417. break;
  77418. }
  77419. return returnValue;
  77420. };
  77421. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77422. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77423. var transform = object.computeWorldMatrix(true);
  77424. // convert rawVerts to object space
  77425. var temp = new Array();
  77426. var index;
  77427. for (index = 0; index < pos.length; index += 3) {
  77428. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77429. }
  77430. pos = temp;
  77431. var matrix = new Array();
  77432. //For now pointDepth will not be used and will be automatically calculated.
  77433. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77434. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77435. var boundingInfo = object.getBoundingInfo();
  77436. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77437. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77438. var elementSize = dim * 2 / arraySize;
  77439. for (var i = 0; i < pos.length; i = i + 3) {
  77440. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77441. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77442. var y = -pos[i + 2] + minY;
  77443. if (!matrix[x]) {
  77444. matrix[x] = [];
  77445. }
  77446. if (!matrix[x][z]) {
  77447. matrix[x][z] = y;
  77448. }
  77449. matrix[x][z] = Math.max(y, matrix[x][z]);
  77450. }
  77451. for (var x = 0; x <= arraySize; ++x) {
  77452. if (!matrix[x]) {
  77453. var loc = 1;
  77454. while (!matrix[(x + loc) % arraySize]) {
  77455. loc++;
  77456. }
  77457. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77458. //console.log("missing x", x);
  77459. }
  77460. for (var z = 0; z <= arraySize; ++z) {
  77461. if (!matrix[x][z]) {
  77462. var loc = 1;
  77463. var newValue;
  77464. while (newValue === undefined) {
  77465. newValue = matrix[x][(z + loc++) % arraySize];
  77466. }
  77467. matrix[x][z] = newValue;
  77468. }
  77469. }
  77470. }
  77471. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77472. elementSize: elementSize
  77473. });
  77474. //For future reference, needed for body transformation
  77475. shape.minY = minY;
  77476. return shape;
  77477. };
  77478. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77479. var object = impostor.object;
  77480. //make sure it is updated...
  77481. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77482. // The delta between the mesh position and the mesh bounding box center
  77483. var bInfo = object.getBoundingInfo();
  77484. if (!bInfo)
  77485. return;
  77486. var center = impostor.getObjectCenter();
  77487. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77488. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77489. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77490. this._tmpPosition.copyFrom(center);
  77491. var quaternion = object.rotationQuaternion;
  77492. if (!quaternion) {
  77493. return;
  77494. }
  77495. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77496. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77497. //-90 DEG in X, precalculated
  77498. quaternion = quaternion.multiply(this._minus90X);
  77499. //Invert! (Precalculated, 90 deg in X)
  77500. //No need to clone. this will never change.
  77501. impostor.setDeltaRotation(this._plus90X);
  77502. }
  77503. //If it is a heightfield, if should be centered.
  77504. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77505. var mesh = object;
  77506. var boundingInfo = mesh.getBoundingInfo();
  77507. //calculate the correct body position:
  77508. var rotationQuaternion = mesh.rotationQuaternion;
  77509. mesh.rotationQuaternion = this._tmpUnityRotation;
  77510. mesh.computeWorldMatrix(true);
  77511. //get original center with no rotation
  77512. var c = center.clone();
  77513. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77514. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77515. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77516. mesh.setPreTransformMatrix(p);
  77517. mesh.computeWorldMatrix(true);
  77518. //calculate the translation
  77519. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77520. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77521. //add it inverted to the delta
  77522. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77523. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77524. //rotation is back
  77525. mesh.rotationQuaternion = rotationQuaternion;
  77526. mesh.setPreTransformMatrix(oldPivot);
  77527. mesh.computeWorldMatrix(true);
  77528. }
  77529. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77530. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77531. //this._tmpPosition.copyFrom(object.position);
  77532. }
  77533. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77534. //Now update the impostor object
  77535. impostor.physicsBody.position.copy(this._tmpPosition);
  77536. impostor.physicsBody.quaternion.copy(quaternion);
  77537. };
  77538. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77539. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77540. if (impostor.object.rotationQuaternion) {
  77541. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77542. }
  77543. };
  77544. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77545. impostor.physicsBody.position.copy(newPosition);
  77546. impostor.physicsBody.quaternion.copy(newRotation);
  77547. };
  77548. CannonJSPlugin.prototype.isSupported = function () {
  77549. return this.BJSCANNON !== undefined;
  77550. };
  77551. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77552. impostor.physicsBody.velocity.copy(velocity);
  77553. };
  77554. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77555. impostor.physicsBody.angularVelocity.copy(velocity);
  77556. };
  77557. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77558. var v = impostor.physicsBody.velocity;
  77559. if (!v) {
  77560. return null;
  77561. }
  77562. return new BABYLON.Vector3(v.x, v.y, v.z);
  77563. };
  77564. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77565. var v = impostor.physicsBody.angularVelocity;
  77566. if (!v) {
  77567. return null;
  77568. }
  77569. return new BABYLON.Vector3(v.x, v.y, v.z);
  77570. };
  77571. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77572. impostor.physicsBody.mass = mass;
  77573. impostor.physicsBody.updateMassProperties();
  77574. };
  77575. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77576. return impostor.physicsBody.mass;
  77577. };
  77578. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77579. return impostor.physicsBody.material.friction;
  77580. };
  77581. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77582. impostor.physicsBody.material.friction = friction;
  77583. };
  77584. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77585. return impostor.physicsBody.material.restitution;
  77586. };
  77587. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77588. impostor.physicsBody.material.restitution = restitution;
  77589. };
  77590. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77591. impostor.physicsBody.sleep();
  77592. };
  77593. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77594. impostor.physicsBody.wakeUp();
  77595. };
  77596. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77597. joint.physicsJoint.distance = maxDistance;
  77598. };
  77599. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77600. // if (!motorIndex) {
  77601. // joint.physicsJoint.enableMotor();
  77602. // }
  77603. // }
  77604. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77605. // if (!motorIndex) {
  77606. // joint.physicsJoint.disableMotor();
  77607. // }
  77608. // }
  77609. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77610. if (!motorIndex) {
  77611. joint.physicsJoint.enableMotor();
  77612. joint.physicsJoint.setMotorSpeed(speed);
  77613. if (maxForce) {
  77614. this.setLimit(joint, maxForce);
  77615. }
  77616. }
  77617. };
  77618. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77619. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77620. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77621. };
  77622. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77623. var body = impostor.physicsBody;
  77624. mesh.position.x = body.position.x;
  77625. mesh.position.y = body.position.y;
  77626. mesh.position.z = body.position.z;
  77627. if (mesh.rotationQuaternion) {
  77628. mesh.rotationQuaternion.x = body.quaternion.x;
  77629. mesh.rotationQuaternion.y = body.quaternion.y;
  77630. mesh.rotationQuaternion.z = body.quaternion.z;
  77631. mesh.rotationQuaternion.w = body.quaternion.w;
  77632. }
  77633. };
  77634. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77635. var shape = impostor.physicsBody.shapes[0];
  77636. return shape.boundingSphereRadius;
  77637. };
  77638. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77639. var shape = impostor.physicsBody.shapes[0];
  77640. result.x = shape.halfExtents.x * 2;
  77641. result.y = shape.halfExtents.y * 2;
  77642. result.z = shape.halfExtents.z * 2;
  77643. };
  77644. CannonJSPlugin.prototype.dispose = function () {
  77645. };
  77646. CannonJSPlugin.prototype._extendNamespace = function () {
  77647. //this will force cannon to execute at least one step when using interpolation
  77648. var step_tmp1 = new this.BJSCANNON.Vec3();
  77649. var Engine = this.BJSCANNON;
  77650. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77651. maxSubSteps = maxSubSteps || 10;
  77652. timeSinceLastCalled = timeSinceLastCalled || 0;
  77653. if (timeSinceLastCalled === 0) {
  77654. this.internalStep(dt);
  77655. this.time += dt;
  77656. }
  77657. else {
  77658. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77659. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77660. var t0 = performance.now();
  77661. for (var i = 0; i !== internalSteps; i++) {
  77662. this.internalStep(dt);
  77663. if (performance.now() - t0 > dt * 1000) {
  77664. break;
  77665. }
  77666. }
  77667. this.time += timeSinceLastCalled;
  77668. var h = this.time % dt;
  77669. var h_div_dt = h / dt;
  77670. var interpvelo = step_tmp1;
  77671. var bodies = this.bodies;
  77672. for (var j = 0; j !== bodies.length; j++) {
  77673. var b = bodies[j];
  77674. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77675. b.position.vsub(b.previousPosition, interpvelo);
  77676. interpvelo.scale(h_div_dt, interpvelo);
  77677. b.position.vadd(interpvelo, b.interpolatedPosition);
  77678. }
  77679. else {
  77680. b.interpolatedPosition.copy(b.position);
  77681. b.interpolatedQuaternion.copy(b.quaternion);
  77682. }
  77683. }
  77684. }
  77685. };
  77686. };
  77687. return CannonJSPlugin;
  77688. }());
  77689. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77690. })(BABYLON || (BABYLON = {}));
  77691. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77692. var BABYLON;
  77693. (function (BABYLON) {
  77694. var OimoJSPlugin = /** @class */ (function () {
  77695. function OimoJSPlugin(iterations) {
  77696. this.name = "OimoJSPlugin";
  77697. this._tmpImpostorsArray = [];
  77698. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77699. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77700. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77701. this.world.worldscale(1);
  77702. this.world.clear();
  77703. //making sure no stats are calculated
  77704. this.world.isNoStat = true;
  77705. }
  77706. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77707. this.world.gravity.copy(gravity);
  77708. };
  77709. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77710. this.world.timeStep = timeStep;
  77711. };
  77712. OimoJSPlugin.prototype.getTimeStep = function () {
  77713. return this.world.timeStep;
  77714. };
  77715. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77716. var _this = this;
  77717. impostors.forEach(function (impostor) {
  77718. impostor.beforeStep();
  77719. });
  77720. this.world.step();
  77721. impostors.forEach(function (impostor) {
  77722. impostor.afterStep();
  77723. //update the ordered impostors array
  77724. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77725. });
  77726. //check for collisions
  77727. var contact = this.world.contacts;
  77728. while (contact !== null) {
  77729. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77730. contact = contact.next;
  77731. continue;
  77732. }
  77733. //is this body colliding with any other? get the impostor
  77734. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77735. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77736. if (!mainImpostor || !collidingImpostor) {
  77737. contact = contact.next;
  77738. continue;
  77739. }
  77740. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77741. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77742. contact = contact.next;
  77743. }
  77744. };
  77745. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77746. var mass = impostor.physicsBody.massInfo.mass;
  77747. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77748. };
  77749. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77750. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77751. this.applyImpulse(impostor, force, contactPoint);
  77752. };
  77753. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77754. var _this = this;
  77755. //parent-child relationship. Does this impostor has a parent impostor?
  77756. if (impostor.parent) {
  77757. if (impostor.physicsBody) {
  77758. this.removePhysicsBody(impostor);
  77759. //TODO is that needed?
  77760. impostor.forceUpdate();
  77761. }
  77762. return;
  77763. }
  77764. if (impostor.isBodyInitRequired()) {
  77765. var bodyConfig = {
  77766. name: impostor.uniqueId,
  77767. //Oimo must have mass, also for static objects.
  77768. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77769. size: [],
  77770. type: [],
  77771. pos: [],
  77772. rot: [],
  77773. move: impostor.getParam("mass") !== 0,
  77774. //Supporting older versions of Oimo
  77775. world: this.world
  77776. };
  77777. var impostors = [impostor];
  77778. var addToArray = function (parent) {
  77779. if (!parent.getChildMeshes)
  77780. return;
  77781. parent.getChildMeshes().forEach(function (m) {
  77782. if (m.physicsImpostor) {
  77783. impostors.push(m.physicsImpostor);
  77784. //m.physicsImpostor._init();
  77785. }
  77786. });
  77787. };
  77788. addToArray(impostor.object);
  77789. var checkWithEpsilon_1 = function (value) {
  77790. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77791. };
  77792. impostors.forEach(function (i) {
  77793. if (!impostor.object.rotationQuaternion) {
  77794. return;
  77795. }
  77796. //get the correct bounding box
  77797. var oldQuaternion = i.object.rotationQuaternion;
  77798. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77799. x: impostor.object.rotationQuaternion.x,
  77800. y: impostor.object.rotationQuaternion.y,
  77801. z: impostor.object.rotationQuaternion.z,
  77802. s: impostor.object.rotationQuaternion.w
  77803. });
  77804. var extendSize = i.getObjectExtendSize();
  77805. if (i === impostor) {
  77806. var center = impostor.getObjectCenter();
  77807. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77808. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77809. //Can also use Array.prototype.push.apply
  77810. bodyConfig.pos.push(center.x);
  77811. bodyConfig.pos.push(center.y);
  77812. bodyConfig.pos.push(center.z);
  77813. //tmp solution
  77814. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77815. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77816. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77817. }
  77818. else {
  77819. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77820. bodyConfig.pos.push(localPosition.x);
  77821. bodyConfig.pos.push(localPosition.y);
  77822. bodyConfig.pos.push(localPosition.z);
  77823. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77824. bodyConfig.rot.push(0);
  77825. bodyConfig.rot.push(0);
  77826. bodyConfig.rot.push(0);
  77827. }
  77828. // register mesh
  77829. switch (i.type) {
  77830. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77831. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77832. case BABYLON.PhysicsImpostor.SphereImpostor:
  77833. var radiusX = extendSize.x;
  77834. var radiusY = extendSize.y;
  77835. var radiusZ = extendSize.z;
  77836. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77837. bodyConfig.type.push('sphere');
  77838. //due to the way oimo works with compounds, add 3 times
  77839. bodyConfig.size.push(size);
  77840. bodyConfig.size.push(size);
  77841. bodyConfig.size.push(size);
  77842. break;
  77843. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77844. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77845. var sizeY = checkWithEpsilon_1(extendSize.y);
  77846. bodyConfig.type.push('cylinder');
  77847. bodyConfig.size.push(sizeX);
  77848. bodyConfig.size.push(sizeY);
  77849. //due to the way oimo works with compounds, add one more value.
  77850. bodyConfig.size.push(sizeY);
  77851. break;
  77852. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77853. case BABYLON.PhysicsImpostor.BoxImpostor:
  77854. default:
  77855. var sizeX = checkWithEpsilon_1(extendSize.x);
  77856. var sizeY = checkWithEpsilon_1(extendSize.y);
  77857. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77858. bodyConfig.type.push('box');
  77859. bodyConfig.size.push(sizeX);
  77860. bodyConfig.size.push(sizeY);
  77861. bodyConfig.size.push(sizeZ);
  77862. break;
  77863. }
  77864. //actually not needed, but hey...
  77865. i.object.rotationQuaternion = oldQuaternion;
  77866. });
  77867. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77868. }
  77869. else {
  77870. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77871. }
  77872. impostor.setDeltaPosition(this._tmpPositionVector);
  77873. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77874. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77875. };
  77876. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77877. //impostor.physicsBody.dispose();
  77878. //Same as : (older oimo versions)
  77879. this.world.removeRigidBody(impostor.physicsBody);
  77880. };
  77881. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77882. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77883. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77884. if (!mainBody || !connectedBody) {
  77885. return;
  77886. }
  77887. var jointData = impostorJoint.joint.jointData;
  77888. var options = jointData.nativeParams || {};
  77889. var type;
  77890. var nativeJointData = {
  77891. body1: mainBody,
  77892. body2: connectedBody,
  77893. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77894. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77895. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77896. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77897. min: options.min,
  77898. max: options.max,
  77899. collision: options.collision || jointData.collision,
  77900. spring: options.spring,
  77901. //supporting older version of Oimo
  77902. world: this.world
  77903. };
  77904. switch (impostorJoint.joint.type) {
  77905. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77906. type = "jointBall";
  77907. break;
  77908. case BABYLON.PhysicsJoint.SpringJoint:
  77909. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77910. var springData = jointData;
  77911. nativeJointData.min = springData.length || nativeJointData.min;
  77912. //Max should also be set, just make sure it is at least min
  77913. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77914. case BABYLON.PhysicsJoint.DistanceJoint:
  77915. type = "jointDistance";
  77916. nativeJointData.max = jointData.maxDistance;
  77917. break;
  77918. case BABYLON.PhysicsJoint.PrismaticJoint:
  77919. type = "jointPrisme";
  77920. break;
  77921. case BABYLON.PhysicsJoint.SliderJoint:
  77922. type = "jointSlide";
  77923. break;
  77924. case BABYLON.PhysicsJoint.WheelJoint:
  77925. type = "jointWheel";
  77926. break;
  77927. case BABYLON.PhysicsJoint.HingeJoint:
  77928. default:
  77929. type = "jointHinge";
  77930. break;
  77931. }
  77932. nativeJointData.type = type;
  77933. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77934. };
  77935. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77936. //Bug in Oimo prevents us from disposing a joint in the playground
  77937. //joint.joint.physicsJoint.dispose();
  77938. //So we will bruteforce it!
  77939. try {
  77940. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77941. }
  77942. catch (e) {
  77943. BABYLON.Tools.Warn(e);
  77944. }
  77945. };
  77946. OimoJSPlugin.prototype.isSupported = function () {
  77947. return this.BJSOIMO !== undefined;
  77948. };
  77949. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77950. if (!impostor.physicsBody.sleeping) {
  77951. //TODO check that
  77952. if (impostor.physicsBody.shapes.next) {
  77953. var parentShape = this._getLastShape(impostor.physicsBody);
  77954. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77955. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77956. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77957. }
  77958. else {
  77959. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77960. }
  77961. if (impostor.object.rotationQuaternion) {
  77962. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77963. impostor.object.rotationQuaternion.normalize();
  77964. }
  77965. }
  77966. };
  77967. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77968. var body = impostor.physicsBody;
  77969. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77970. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77971. body.syncShapes();
  77972. body.awake();
  77973. };
  77974. OimoJSPlugin.prototype._getLastShape = function (body) {
  77975. var lastShape = body.shapes;
  77976. while (lastShape.next) {
  77977. lastShape = lastShape.next;
  77978. }
  77979. return lastShape;
  77980. };
  77981. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77982. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77983. };
  77984. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77985. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77986. };
  77987. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77988. var v = impostor.physicsBody.linearVelocity;
  77989. if (!v) {
  77990. return null;
  77991. }
  77992. return new BABYLON.Vector3(v.x, v.y, v.z);
  77993. };
  77994. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77995. var v = impostor.physicsBody.angularVelocity;
  77996. if (!v) {
  77997. return null;
  77998. }
  77999. return new BABYLON.Vector3(v.x, v.y, v.z);
  78000. };
  78001. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78002. var staticBody = mass === 0;
  78003. //this will actually set the body's density and not its mass.
  78004. //But this is how oimo treats the mass variable.
  78005. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78006. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78007. };
  78008. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78009. return impostor.physicsBody.shapes.density;
  78010. };
  78011. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78012. return impostor.physicsBody.shapes.friction;
  78013. };
  78014. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78015. impostor.physicsBody.shapes.friction = friction;
  78016. };
  78017. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78018. return impostor.physicsBody.shapes.restitution;
  78019. };
  78020. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78021. impostor.physicsBody.shapes.restitution = restitution;
  78022. };
  78023. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78024. impostor.physicsBody.sleep();
  78025. };
  78026. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78027. impostor.physicsBody.awake();
  78028. };
  78029. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78030. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78031. if (minDistance !== void 0) {
  78032. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78033. }
  78034. };
  78035. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78036. //TODO separate rotational and transational motors.
  78037. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78038. if (motor) {
  78039. motor.setMotor(speed, maxForce);
  78040. }
  78041. };
  78042. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78043. //TODO separate rotational and transational motors.
  78044. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78045. if (motor) {
  78046. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78047. }
  78048. };
  78049. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78050. var body = impostor.physicsBody;
  78051. mesh.position.x = body.position.x;
  78052. mesh.position.y = body.position.y;
  78053. mesh.position.z = body.position.z;
  78054. if (mesh.rotationQuaternion) {
  78055. mesh.rotationQuaternion.x = body.orientation.x;
  78056. mesh.rotationQuaternion.y = body.orientation.y;
  78057. mesh.rotationQuaternion.z = body.orientation.z;
  78058. mesh.rotationQuaternion.w = body.orientation.s;
  78059. }
  78060. };
  78061. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78062. return impostor.physicsBody.shapes.radius;
  78063. };
  78064. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78065. var shape = impostor.physicsBody.shapes;
  78066. result.x = shape.halfWidth * 2;
  78067. result.y = shape.halfHeight * 2;
  78068. result.z = shape.halfDepth * 2;
  78069. };
  78070. OimoJSPlugin.prototype.dispose = function () {
  78071. this.world.clear();
  78072. };
  78073. return OimoJSPlugin;
  78074. }());
  78075. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78076. })(BABYLON || (BABYLON = {}));
  78077. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78078. var BABYLON;
  78079. (function (BABYLON) {
  78080. /*
  78081. * Based on jsTGALoader - Javascript loader for TGA file
  78082. * By Vincent Thibault
  78083. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78084. */
  78085. var TGATools = /** @class */ (function () {
  78086. function TGATools() {
  78087. }
  78088. TGATools.GetTGAHeader = function (data) {
  78089. var offset = 0;
  78090. var header = {
  78091. id_length: data[offset++],
  78092. colormap_type: data[offset++],
  78093. image_type: data[offset++],
  78094. colormap_index: data[offset++] | data[offset++] << 8,
  78095. colormap_length: data[offset++] | data[offset++] << 8,
  78096. colormap_size: data[offset++],
  78097. origin: [
  78098. data[offset++] | data[offset++] << 8,
  78099. data[offset++] | data[offset++] << 8
  78100. ],
  78101. width: data[offset++] | data[offset++] << 8,
  78102. height: data[offset++] | data[offset++] << 8,
  78103. pixel_size: data[offset++],
  78104. flags: data[offset++]
  78105. };
  78106. return header;
  78107. };
  78108. TGATools.UploadContent = function (gl, data) {
  78109. // Not enough data to contain header ?
  78110. if (data.length < 19) {
  78111. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78112. return;
  78113. }
  78114. // Read Header
  78115. var offset = 18;
  78116. var header = TGATools.GetTGAHeader(data);
  78117. // Assume it's a valid Targa file.
  78118. if (header.id_length + offset > data.length) {
  78119. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78120. return;
  78121. }
  78122. // Skip not needed data
  78123. offset += header.id_length;
  78124. var use_rle = false;
  78125. var use_pal = false;
  78126. var use_grey = false;
  78127. // Get some informations.
  78128. switch (header.image_type) {
  78129. case TGATools._TYPE_RLE_INDEXED:
  78130. use_rle = true;
  78131. case TGATools._TYPE_INDEXED:
  78132. use_pal = true;
  78133. break;
  78134. case TGATools._TYPE_RLE_RGB:
  78135. use_rle = true;
  78136. case TGATools._TYPE_RGB:
  78137. // use_rgb = true;
  78138. break;
  78139. case TGATools._TYPE_RLE_GREY:
  78140. use_rle = true;
  78141. case TGATools._TYPE_GREY:
  78142. use_grey = true;
  78143. break;
  78144. }
  78145. var pixel_data;
  78146. // var numAlphaBits = header.flags & 0xf;
  78147. var pixel_size = header.pixel_size >> 3;
  78148. var pixel_total = header.width * header.height * pixel_size;
  78149. // Read palettes
  78150. var palettes;
  78151. if (use_pal) {
  78152. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78153. }
  78154. // Read LRE
  78155. if (use_rle) {
  78156. pixel_data = new Uint8Array(pixel_total);
  78157. var c, count, i;
  78158. var localOffset = 0;
  78159. var pixels = new Uint8Array(pixel_size);
  78160. while (offset < pixel_total && localOffset < pixel_total) {
  78161. c = data[offset++];
  78162. count = (c & 0x7f) + 1;
  78163. // RLE pixels
  78164. if (c & 0x80) {
  78165. // Bind pixel tmp array
  78166. for (i = 0; i < pixel_size; ++i) {
  78167. pixels[i] = data[offset++];
  78168. }
  78169. // Copy pixel array
  78170. for (i = 0; i < count; ++i) {
  78171. pixel_data.set(pixels, localOffset + i * pixel_size);
  78172. }
  78173. localOffset += pixel_size * count;
  78174. }
  78175. else {
  78176. count *= pixel_size;
  78177. for (i = 0; i < count; ++i) {
  78178. pixel_data[localOffset + i] = data[offset++];
  78179. }
  78180. localOffset += count;
  78181. }
  78182. }
  78183. }
  78184. else {
  78185. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78186. }
  78187. // Load to texture
  78188. var x_start, y_start, x_step, y_step, y_end, x_end;
  78189. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78190. default:
  78191. case TGATools._ORIGIN_UL:
  78192. x_start = 0;
  78193. x_step = 1;
  78194. x_end = header.width;
  78195. y_start = 0;
  78196. y_step = 1;
  78197. y_end = header.height;
  78198. break;
  78199. case TGATools._ORIGIN_BL:
  78200. x_start = 0;
  78201. x_step = 1;
  78202. x_end = header.width;
  78203. y_start = header.height - 1;
  78204. y_step = -1;
  78205. y_end = -1;
  78206. break;
  78207. case TGATools._ORIGIN_UR:
  78208. x_start = header.width - 1;
  78209. x_step = -1;
  78210. x_end = -1;
  78211. y_start = 0;
  78212. y_step = 1;
  78213. y_end = header.height;
  78214. break;
  78215. case TGATools._ORIGIN_BR:
  78216. x_start = header.width - 1;
  78217. x_step = -1;
  78218. x_end = -1;
  78219. y_start = header.height - 1;
  78220. y_step = -1;
  78221. y_end = -1;
  78222. break;
  78223. }
  78224. // Load the specify method
  78225. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78226. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78227. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78228. };
  78229. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78230. var image = pixel_data, colormap = palettes;
  78231. var width = header.width, height = header.height;
  78232. var color, i = 0, x, y;
  78233. var imageData = new Uint8Array(width * height * 4);
  78234. for (y = y_start; y !== y_end; y += y_step) {
  78235. for (x = x_start; x !== x_end; x += x_step, i++) {
  78236. color = image[i];
  78237. imageData[(x + width * y) * 4 + 3] = 255;
  78238. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78239. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78240. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78241. }
  78242. }
  78243. return imageData;
  78244. };
  78245. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78246. var image = pixel_data;
  78247. var width = header.width, height = header.height;
  78248. var color, i = 0, x, y;
  78249. var imageData = new Uint8Array(width * height * 4);
  78250. for (y = y_start; y !== y_end; y += y_step) {
  78251. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78252. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78253. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78254. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78255. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78256. imageData[(x + width * y) * 4 + 0] = r;
  78257. imageData[(x + width * y) * 4 + 1] = g;
  78258. imageData[(x + width * y) * 4 + 2] = b;
  78259. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78260. }
  78261. }
  78262. return imageData;
  78263. };
  78264. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78265. var image = pixel_data;
  78266. var width = header.width, height = header.height;
  78267. var i = 0, x, y;
  78268. var imageData = new Uint8Array(width * height * 4);
  78269. for (y = y_start; y !== y_end; y += y_step) {
  78270. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78271. imageData[(x + width * y) * 4 + 3] = 255;
  78272. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78273. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78274. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78275. }
  78276. }
  78277. return imageData;
  78278. };
  78279. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78280. var image = pixel_data;
  78281. var width = header.width, height = header.height;
  78282. var i = 0, x, y;
  78283. var imageData = new Uint8Array(width * height * 4);
  78284. for (y = y_start; y !== y_end; y += y_step) {
  78285. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78286. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78287. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78288. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78289. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78290. }
  78291. }
  78292. return imageData;
  78293. };
  78294. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78295. var image = pixel_data;
  78296. var width = header.width, height = header.height;
  78297. var color, i = 0, x, y;
  78298. var imageData = new Uint8Array(width * height * 4);
  78299. for (y = y_start; y !== y_end; y += y_step) {
  78300. for (x = x_start; x !== x_end; x += x_step, i++) {
  78301. color = image[i];
  78302. imageData[(x + width * y) * 4 + 0] = color;
  78303. imageData[(x + width * y) * 4 + 1] = color;
  78304. imageData[(x + width * y) * 4 + 2] = color;
  78305. imageData[(x + width * y) * 4 + 3] = 255;
  78306. }
  78307. }
  78308. return imageData;
  78309. };
  78310. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78311. var image = pixel_data;
  78312. var width = header.width, height = header.height;
  78313. var i = 0, x, y;
  78314. var imageData = new Uint8Array(width * height * 4);
  78315. for (y = y_start; y !== y_end; y += y_step) {
  78316. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78317. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78318. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78319. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78320. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78321. }
  78322. }
  78323. return imageData;
  78324. };
  78325. //private static _TYPE_NO_DATA = 0;
  78326. TGATools._TYPE_INDEXED = 1;
  78327. TGATools._TYPE_RGB = 2;
  78328. TGATools._TYPE_GREY = 3;
  78329. TGATools._TYPE_RLE_INDEXED = 9;
  78330. TGATools._TYPE_RLE_RGB = 10;
  78331. TGATools._TYPE_RLE_GREY = 11;
  78332. TGATools._ORIGIN_MASK = 0x30;
  78333. TGATools._ORIGIN_SHIFT = 0x04;
  78334. TGATools._ORIGIN_BL = 0x00;
  78335. TGATools._ORIGIN_BR = 0x01;
  78336. TGATools._ORIGIN_UL = 0x02;
  78337. TGATools._ORIGIN_UR = 0x03;
  78338. return TGATools;
  78339. }());
  78340. BABYLON.TGATools = TGATools;
  78341. })(BABYLON || (BABYLON = {}));
  78342. //# sourceMappingURL=babylon.tga.js.map
  78343. var BABYLON;
  78344. (function (BABYLON) {
  78345. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78346. // All values and structures referenced from:
  78347. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78348. var DDS_MAGIC = 0x20534444;
  78349. var
  78350. //DDSD_CAPS = 0x1,
  78351. //DDSD_HEIGHT = 0x2,
  78352. //DDSD_WIDTH = 0x4,
  78353. //DDSD_PITCH = 0x8,
  78354. //DDSD_PIXELFORMAT = 0x1000,
  78355. DDSD_MIPMAPCOUNT = 0x20000;
  78356. //DDSD_LINEARSIZE = 0x80000,
  78357. //DDSD_DEPTH = 0x800000;
  78358. // var DDSCAPS_COMPLEX = 0x8,
  78359. // DDSCAPS_MIPMAP = 0x400000,
  78360. // DDSCAPS_TEXTURE = 0x1000;
  78361. var DDSCAPS2_CUBEMAP = 0x200;
  78362. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78363. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78364. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78365. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78366. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78367. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78368. // DDSCAPS2_VOLUME = 0x200000;
  78369. var
  78370. //DDPF_ALPHAPIXELS = 0x1,
  78371. //DDPF_ALPHA = 0x2,
  78372. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78373. //DDPF_YUV = 0x200,
  78374. DDPF_LUMINANCE = 0x20000;
  78375. function FourCCToInt32(value) {
  78376. return value.charCodeAt(0) +
  78377. (value.charCodeAt(1) << 8) +
  78378. (value.charCodeAt(2) << 16) +
  78379. (value.charCodeAt(3) << 24);
  78380. }
  78381. function Int32ToFourCC(value) {
  78382. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78383. }
  78384. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78385. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78386. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78387. var FOURCC_DX10 = FourCCToInt32("DX10");
  78388. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78389. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78390. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78391. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78392. var headerLengthInt = 31; // The header length in 32 bit ints
  78393. // Offsets into the header array
  78394. var off_magic = 0;
  78395. var off_size = 1;
  78396. var off_flags = 2;
  78397. var off_height = 3;
  78398. var off_width = 4;
  78399. var off_mipmapCount = 7;
  78400. var off_pfFlags = 20;
  78401. var off_pfFourCC = 21;
  78402. var off_RGBbpp = 22;
  78403. var off_RMask = 23;
  78404. var off_GMask = 24;
  78405. var off_BMask = 25;
  78406. var off_AMask = 26;
  78407. // var off_caps1 = 27;
  78408. var off_caps2 = 28;
  78409. // var off_caps3 = 29;
  78410. // var off_caps4 = 30;
  78411. var off_dxgiFormat = 32;
  78412. ;
  78413. var DDSTools = /** @class */ (function () {
  78414. function DDSTools() {
  78415. }
  78416. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78417. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78418. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78419. var mipmapCount = 1;
  78420. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78421. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78422. }
  78423. var fourCC = header[off_pfFourCC];
  78424. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78425. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78426. switch (fourCC) {
  78427. case FOURCC_D3DFMT_R16G16B16A16F:
  78428. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78429. break;
  78430. case FOURCC_D3DFMT_R32G32B32A32F:
  78431. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78432. break;
  78433. case FOURCC_DX10:
  78434. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78435. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78436. break;
  78437. }
  78438. }
  78439. return {
  78440. width: header[off_width],
  78441. height: header[off_height],
  78442. mipmapCount: mipmapCount,
  78443. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78444. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78445. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78446. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78447. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78448. dxgiFormat: dxgiFormat,
  78449. textureType: textureType
  78450. };
  78451. };
  78452. DDSTools._ToHalfFloat = function (value) {
  78453. if (!DDSTools._FloatView) {
  78454. DDSTools._FloatView = new Float32Array(1);
  78455. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78456. }
  78457. DDSTools._FloatView[0] = value;
  78458. var x = DDSTools._Int32View[0];
  78459. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78460. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78461. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78462. /* If zero, or denormal, or exponent underflows too much for a denormal
  78463. * half, return signed zero. */
  78464. if (e < 103) {
  78465. return bits;
  78466. }
  78467. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78468. if (e > 142) {
  78469. bits |= 0x7c00;
  78470. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78471. * not Inf, so make sure we set one mantissa bit too. */
  78472. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78473. return bits;
  78474. }
  78475. /* If exponent underflows but not too much, return a denormal */
  78476. if (e < 113) {
  78477. m |= 0x0800;
  78478. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78479. * to 1, which is OK. */
  78480. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78481. return bits;
  78482. }
  78483. bits |= ((e - 112) << 10) | (m >> 1);
  78484. bits += m & 1;
  78485. return bits;
  78486. };
  78487. DDSTools._FromHalfFloat = function (value) {
  78488. var s = (value & 0x8000) >> 15;
  78489. var e = (value & 0x7C00) >> 10;
  78490. var f = value & 0x03FF;
  78491. if (e === 0) {
  78492. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78493. }
  78494. else if (e == 0x1F) {
  78495. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78496. }
  78497. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78498. };
  78499. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78500. var destArray = new Float32Array(dataLength);
  78501. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78502. var index = 0;
  78503. for (var y = 0; y < height; y++) {
  78504. for (var x = 0; x < width; x++) {
  78505. var srcPos = (x + y * width) * 4;
  78506. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78507. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78508. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78509. if (DDSTools.StoreLODInAlphaChannel) {
  78510. destArray[index + 3] = lod;
  78511. }
  78512. else {
  78513. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78514. }
  78515. index += 4;
  78516. }
  78517. }
  78518. return destArray;
  78519. };
  78520. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78521. if (DDSTools.StoreLODInAlphaChannel) {
  78522. var destArray = new Uint16Array(dataLength);
  78523. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78524. var index = 0;
  78525. for (var y = 0; y < height; y++) {
  78526. for (var x = 0; x < width; x++) {
  78527. var srcPos = (x + y * width) * 4;
  78528. destArray[index] = srcData[srcPos];
  78529. destArray[index + 1] = srcData[srcPos + 1];
  78530. destArray[index + 2] = srcData[srcPos + 2];
  78531. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78532. index += 4;
  78533. }
  78534. }
  78535. return destArray;
  78536. }
  78537. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78538. };
  78539. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78540. if (DDSTools.StoreLODInAlphaChannel) {
  78541. var destArray = new Float32Array(dataLength);
  78542. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78543. var index = 0;
  78544. for (var y = 0; y < height; y++) {
  78545. for (var x = 0; x < width; x++) {
  78546. var srcPos = (x + y * width) * 4;
  78547. destArray[index] = srcData[srcPos];
  78548. destArray[index + 1] = srcData[srcPos + 1];
  78549. destArray[index + 2] = srcData[srcPos + 2];
  78550. destArray[index + 3] = lod;
  78551. index += 4;
  78552. }
  78553. }
  78554. return destArray;
  78555. }
  78556. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78557. };
  78558. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78559. var destArray = new Uint8Array(dataLength);
  78560. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78561. var index = 0;
  78562. for (var y = 0; y < height; y++) {
  78563. for (var x = 0; x < width; x++) {
  78564. var srcPos = (x + y * width) * 4;
  78565. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78566. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78567. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78568. if (DDSTools.StoreLODInAlphaChannel) {
  78569. destArray[index + 3] = lod;
  78570. }
  78571. else {
  78572. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78573. }
  78574. index += 4;
  78575. }
  78576. }
  78577. return destArray;
  78578. };
  78579. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78580. var destArray = new Uint8Array(dataLength);
  78581. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78582. var index = 0;
  78583. for (var y = 0; y < height; y++) {
  78584. for (var x = 0; x < width; x++) {
  78585. var srcPos = (x + y * width) * 4;
  78586. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78587. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78588. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78589. if (DDSTools.StoreLODInAlphaChannel) {
  78590. destArray[index + 3] = lod;
  78591. }
  78592. else {
  78593. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78594. }
  78595. index += 4;
  78596. }
  78597. }
  78598. return destArray;
  78599. };
  78600. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78601. var byteArray = new Uint8Array(dataLength);
  78602. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78603. var index = 0;
  78604. for (var y = 0; y < height; y++) {
  78605. for (var x = 0; x < width; x++) {
  78606. var srcPos = (x + y * width) * 4;
  78607. byteArray[index] = srcData[srcPos + rOffset];
  78608. byteArray[index + 1] = srcData[srcPos + gOffset];
  78609. byteArray[index + 2] = srcData[srcPos + bOffset];
  78610. byteArray[index + 3] = srcData[srcPos + aOffset];
  78611. index += 4;
  78612. }
  78613. }
  78614. return byteArray;
  78615. };
  78616. DDSTools._ExtractLongWordOrder = function (value) {
  78617. if (value === 0 || value === 255 || value === -16777216) {
  78618. return 0;
  78619. }
  78620. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78621. };
  78622. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78623. var byteArray = new Uint8Array(dataLength);
  78624. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78625. var index = 0;
  78626. for (var y = 0; y < height; y++) {
  78627. for (var x = 0; x < width; x++) {
  78628. var srcPos = (x + y * width) * 3;
  78629. byteArray[index] = srcData[srcPos + rOffset];
  78630. byteArray[index + 1] = srcData[srcPos + gOffset];
  78631. byteArray[index + 2] = srcData[srcPos + bOffset];
  78632. index += 3;
  78633. }
  78634. }
  78635. return byteArray;
  78636. };
  78637. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78638. var byteArray = new Uint8Array(dataLength);
  78639. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78640. var index = 0;
  78641. for (var y = 0; y < height; y++) {
  78642. for (var x = 0; x < width; x++) {
  78643. var srcPos = (x + y * width);
  78644. byteArray[index] = srcData[srcPos];
  78645. index++;
  78646. }
  78647. }
  78648. return byteArray;
  78649. };
  78650. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78651. if (lodIndex === void 0) { lodIndex = -1; }
  78652. var ext = engine.getCaps().s3tc;
  78653. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78654. var fourCC, width, height, dataLength = 0, dataOffset;
  78655. var byteArray, mipmapCount, mip;
  78656. var internalFormat = 0;
  78657. var format = 0;
  78658. var blockBytes = 1;
  78659. if (header[off_magic] !== DDS_MAGIC) {
  78660. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78661. return;
  78662. }
  78663. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78664. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78665. return;
  78666. }
  78667. if (info.isCompressed && !ext) {
  78668. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78669. return;
  78670. }
  78671. var bpp = header[off_RGBbpp];
  78672. dataOffset = header[off_size] + 4;
  78673. var computeFormats = false;
  78674. if (info.isFourCC) {
  78675. fourCC = header[off_pfFourCC];
  78676. switch (fourCC) {
  78677. case FOURCC_DXT1:
  78678. blockBytes = 8;
  78679. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78680. break;
  78681. case FOURCC_DXT3:
  78682. blockBytes = 16;
  78683. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78684. break;
  78685. case FOURCC_DXT5:
  78686. blockBytes = 16;
  78687. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78688. break;
  78689. case FOURCC_D3DFMT_R16G16B16A16F:
  78690. computeFormats = true;
  78691. break;
  78692. case FOURCC_D3DFMT_R32G32B32A32F:
  78693. computeFormats = true;
  78694. break;
  78695. case FOURCC_DX10:
  78696. // There is an additionnal header so dataOffset need to be changed
  78697. dataOffset += 5 * 4; // 5 uints
  78698. var supported = false;
  78699. switch (info.dxgiFormat) {
  78700. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78701. computeFormats = true;
  78702. supported = true;
  78703. break;
  78704. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78705. info.isRGB = true;
  78706. info.isFourCC = false;
  78707. bpp = 32;
  78708. supported = true;
  78709. break;
  78710. }
  78711. if (supported) {
  78712. break;
  78713. }
  78714. default:
  78715. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78716. return;
  78717. }
  78718. }
  78719. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78720. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78721. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78722. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78723. if (computeFormats) {
  78724. format = engine._getWebGLTextureType(info.textureType);
  78725. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78726. }
  78727. mipmapCount = 1;
  78728. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78729. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78730. }
  78731. for (var face = 0; face < faces; face++) {
  78732. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78733. width = header[off_width];
  78734. height = header[off_height];
  78735. for (mip = 0; mip < mipmapCount; ++mip) {
  78736. if (lodIndex === -1 || lodIndex === mip) {
  78737. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78738. var i = (lodIndex === -1) ? mip : 0;
  78739. if (!info.isCompressed && info.isFourCC) {
  78740. dataLength = width * height * 4;
  78741. var floatArray = null;
  78742. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78743. if (bpp === 128) {
  78744. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78745. }
  78746. else if (bpp === 64) {
  78747. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78748. }
  78749. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78750. format = engine._getWebGLTextureType(info.textureType);
  78751. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78752. }
  78753. else {
  78754. if (bpp === 128) {
  78755. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78756. }
  78757. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78758. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78759. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78760. format = engine._getWebGLTextureType(info.textureType);
  78761. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78762. }
  78763. else {
  78764. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78765. }
  78766. }
  78767. if (floatArray) {
  78768. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78769. }
  78770. }
  78771. else if (info.isRGB) {
  78772. if (bpp === 24) {
  78773. dataLength = width * height * 3;
  78774. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78775. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78776. }
  78777. else {
  78778. dataLength = width * height * 4;
  78779. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78780. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78781. }
  78782. }
  78783. else if (info.isLuminance) {
  78784. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78785. var unpaddedRowSize = width;
  78786. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78787. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78788. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78789. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78790. }
  78791. else {
  78792. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78793. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78794. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78795. }
  78796. }
  78797. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78798. width *= 0.5;
  78799. height *= 0.5;
  78800. width = Math.max(1.0, width);
  78801. height = Math.max(1.0, height);
  78802. }
  78803. if (currentFace !== undefined) {
  78804. // Loading a single face
  78805. break;
  78806. }
  78807. }
  78808. };
  78809. DDSTools.StoreLODInAlphaChannel = false;
  78810. return DDSTools;
  78811. }());
  78812. BABYLON.DDSTools = DDSTools;
  78813. })(BABYLON || (BABYLON = {}));
  78814. //# sourceMappingURL=babylon.dds.js.map
  78815. var BABYLON;
  78816. (function (BABYLON) {
  78817. /**
  78818. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78819. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78820. */
  78821. var KhronosTextureContainer = /** @class */ (function () {
  78822. /**
  78823. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78824. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78825. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78826. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78827. */
  78828. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78829. this.arrayBuffer = arrayBuffer;
  78830. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78831. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78832. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78833. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78834. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78835. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78836. BABYLON.Tools.Error("texture missing KTX identifier");
  78837. return;
  78838. }
  78839. // load the reset of the header in native 32 bit int
  78840. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78841. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78842. var oppositeEndianess = header[0] === 0x01020304;
  78843. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78844. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78845. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78846. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78847. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78848. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78849. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78850. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78851. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78852. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78853. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78854. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78855. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78856. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78857. if (this.glType !== 0) {
  78858. BABYLON.Tools.Error("only compressed formats currently supported");
  78859. return;
  78860. }
  78861. else {
  78862. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78863. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78864. }
  78865. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78866. BABYLON.Tools.Error("only 2D textures currently supported");
  78867. return;
  78868. }
  78869. if (this.numberOfArrayElements !== 0) {
  78870. BABYLON.Tools.Error("texture arrays not currently supported");
  78871. return;
  78872. }
  78873. if (this.numberOfFaces !== facesExpected) {
  78874. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78875. return;
  78876. }
  78877. // we now have a completely validated file, so could use existence of loadType as success
  78878. // would need to make this more elaborate & adjust checks above to support more than one load type
  78879. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78880. }
  78881. // not as fast hardware based, but will probably never need to use
  78882. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78883. return ((val & 0xFF) << 24)
  78884. | ((val & 0xFF00) << 8)
  78885. | ((val >> 8) & 0xFF00)
  78886. | ((val >> 24) & 0xFF);
  78887. };
  78888. /**
  78889. * It is assumed that the texture has already been created & is currently bound
  78890. */
  78891. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78892. switch (this.loadType) {
  78893. case KhronosTextureContainer.COMPRESSED_2D:
  78894. this._upload2DCompressedLevels(gl, loadMipmaps);
  78895. break;
  78896. case KhronosTextureContainer.TEX_2D:
  78897. case KhronosTextureContainer.COMPRESSED_3D:
  78898. case KhronosTextureContainer.TEX_3D:
  78899. }
  78900. };
  78901. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78902. // initialize width & height for level 1
  78903. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78904. var width = this.pixelWidth;
  78905. var height = this.pixelHeight;
  78906. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78907. for (var level = 0; level < mipmapCount; level++) {
  78908. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78909. for (var face = 0; face < this.numberOfFaces; face++) {
  78910. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78911. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78912. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78913. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78914. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78915. }
  78916. width = Math.max(1.0, width * 0.5);
  78917. height = Math.max(1.0, height * 0.5);
  78918. }
  78919. };
  78920. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78921. // load types
  78922. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78923. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78924. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78925. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78926. return KhronosTextureContainer;
  78927. }());
  78928. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78929. })(BABYLON || (BABYLON = {}));
  78930. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78931. var BABYLON;
  78932. (function (BABYLON) {
  78933. var Debug = /** @class */ (function () {
  78934. function Debug() {
  78935. }
  78936. Debug.AxesViewer = /** @class */ (function () {
  78937. function AxesViewer(scene, scaleLines) {
  78938. if (scaleLines === void 0) { scaleLines = 1; }
  78939. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78940. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78941. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78942. this.scaleLines = 1;
  78943. this.scaleLines = scaleLines;
  78944. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78945. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78946. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78947. this._xmesh.renderingGroupId = 2;
  78948. this._ymesh.renderingGroupId = 2;
  78949. this._zmesh.renderingGroupId = 2;
  78950. this._xmesh.material.checkReadyOnlyOnce = true;
  78951. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78952. this._ymesh.material.checkReadyOnlyOnce = true;
  78953. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78954. this._zmesh.material.checkReadyOnlyOnce = true;
  78955. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78956. this.scene = scene;
  78957. }
  78958. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78959. var scaleLines = this.scaleLines;
  78960. if (this._xmesh) {
  78961. this._xmesh.position.copyFrom(position);
  78962. }
  78963. if (this._ymesh) {
  78964. this._ymesh.position.copyFrom(position);
  78965. }
  78966. if (this._zmesh) {
  78967. this._zmesh.position.copyFrom(position);
  78968. }
  78969. var point2 = this._xline[1];
  78970. point2.x = xaxis.x * scaleLines;
  78971. point2.y = xaxis.y * scaleLines;
  78972. point2.z = xaxis.z * scaleLines;
  78973. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78974. point2 = this._yline[1];
  78975. point2.x = yaxis.x * scaleLines;
  78976. point2.y = yaxis.y * scaleLines;
  78977. point2.z = yaxis.z * scaleLines;
  78978. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78979. point2 = this._zline[1];
  78980. point2.x = zaxis.x * scaleLines;
  78981. point2.y = zaxis.y * scaleLines;
  78982. point2.z = zaxis.z * scaleLines;
  78983. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78984. };
  78985. AxesViewer.prototype.dispose = function () {
  78986. if (this._xmesh) {
  78987. this._xmesh.dispose();
  78988. }
  78989. if (this._ymesh) {
  78990. this._ymesh.dispose();
  78991. }
  78992. if (this._zmesh) {
  78993. this._zmesh.dispose();
  78994. }
  78995. this._xmesh = null;
  78996. this._ymesh = null;
  78997. this._zmesh = null;
  78998. this.scene = null;
  78999. };
  79000. return AxesViewer;
  79001. }());
  79002. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79003. __extends(BoneAxesViewer, _super);
  79004. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79005. if (scaleLines === void 0) { scaleLines = 1; }
  79006. var _this = _super.call(this, scene, scaleLines) || this;
  79007. _this.pos = BABYLON.Vector3.Zero();
  79008. _this.xaxis = BABYLON.Vector3.Zero();
  79009. _this.yaxis = BABYLON.Vector3.Zero();
  79010. _this.zaxis = BABYLON.Vector3.Zero();
  79011. _this.mesh = mesh;
  79012. _this.bone = bone;
  79013. return _this;
  79014. }
  79015. BoneAxesViewer.prototype.update = function () {
  79016. if (!this.mesh || !this.bone) {
  79017. return;
  79018. }
  79019. var bone = this.bone;
  79020. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79021. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79022. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79023. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79024. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79025. };
  79026. BoneAxesViewer.prototype.dispose = function () {
  79027. if (this.mesh) {
  79028. this.mesh = null;
  79029. this.bone = null;
  79030. _super.prototype.dispose.call(this);
  79031. }
  79032. };
  79033. return BoneAxesViewer;
  79034. }(Debug.AxesViewer));
  79035. Debug.PhysicsViewer = /** @class */ (function () {
  79036. function PhysicsViewer(scene) {
  79037. this._impostors = [];
  79038. this._meshes = [];
  79039. this._numMeshes = 0;
  79040. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79041. var physicEngine = this._scene.getPhysicsEngine();
  79042. if (physicEngine) {
  79043. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79044. }
  79045. }
  79046. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79047. var plugin = this._physicsEnginePlugin;
  79048. for (var i = 0; i < this._numMeshes; i++) {
  79049. var impostor = this._impostors[i];
  79050. if (!impostor) {
  79051. continue;
  79052. }
  79053. if (impostor.isDisposed) {
  79054. this.hideImpostor(this._impostors[i--]);
  79055. }
  79056. else {
  79057. var mesh = this._meshes[i];
  79058. if (mesh && plugin) {
  79059. plugin.syncMeshWithImpostor(mesh, impostor);
  79060. }
  79061. }
  79062. }
  79063. };
  79064. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79065. if (!this._scene) {
  79066. return;
  79067. }
  79068. for (var i = 0; i < this._numMeshes; i++) {
  79069. if (this._impostors[i] == impostor) {
  79070. return;
  79071. }
  79072. }
  79073. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79074. if (debugMesh) {
  79075. this._impostors[this._numMeshes] = impostor;
  79076. this._meshes[this._numMeshes] = debugMesh;
  79077. if (this._numMeshes === 0) {
  79078. this._renderFunction = this._updateDebugMeshes.bind(this);
  79079. this._scene.registerBeforeRender(this._renderFunction);
  79080. }
  79081. this._numMeshes++;
  79082. }
  79083. };
  79084. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79085. if (!impostor || !this._scene) {
  79086. return;
  79087. }
  79088. var removed = false;
  79089. for (var i = 0; i < this._numMeshes; i++) {
  79090. if (this._impostors[i] == impostor) {
  79091. var mesh = this._meshes[i];
  79092. if (!mesh) {
  79093. continue;
  79094. }
  79095. this._scene.removeMesh(mesh);
  79096. mesh.dispose();
  79097. this._numMeshes--;
  79098. if (this._numMeshes > 0) {
  79099. this._meshes[i] = this._meshes[this._numMeshes];
  79100. this._impostors[i] = this._impostors[this._numMeshes];
  79101. this._meshes[this._numMeshes] = null;
  79102. this._impostors[this._numMeshes] = null;
  79103. }
  79104. else {
  79105. this._meshes[0] = null;
  79106. this._impostors[0] = null;
  79107. }
  79108. removed = true;
  79109. break;
  79110. }
  79111. }
  79112. if (removed && this._numMeshes === 0) {
  79113. this._scene.unregisterBeforeRender(this._renderFunction);
  79114. }
  79115. };
  79116. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79117. if (!this._debugMaterial) {
  79118. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79119. this._debugMaterial.wireframe = true;
  79120. }
  79121. return this._debugMaterial;
  79122. };
  79123. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79124. if (!this._debugBoxMesh) {
  79125. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79126. this._debugBoxMesh.renderingGroupId = 1;
  79127. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79128. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79129. scene.removeMesh(this._debugBoxMesh);
  79130. }
  79131. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79132. };
  79133. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79134. if (!this._debugSphereMesh) {
  79135. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79136. this._debugSphereMesh.renderingGroupId = 1;
  79137. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79138. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79139. scene.removeMesh(this._debugSphereMesh);
  79140. }
  79141. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79142. };
  79143. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79144. var mesh = null;
  79145. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79146. mesh = this._getDebugBoxMesh(scene);
  79147. impostor.getBoxSizeToRef(mesh.scaling);
  79148. }
  79149. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79150. mesh = this._getDebugSphereMesh(scene);
  79151. var radius = impostor.getRadius();
  79152. mesh.scaling.x = radius * 2;
  79153. mesh.scaling.y = radius * 2;
  79154. mesh.scaling.z = radius * 2;
  79155. }
  79156. return mesh;
  79157. };
  79158. PhysicsViewer.prototype.dispose = function () {
  79159. for (var i = 0; i < this._numMeshes; i++) {
  79160. this.hideImpostor(this._impostors[i]);
  79161. }
  79162. if (this._debugBoxMesh) {
  79163. this._debugBoxMesh.dispose();
  79164. }
  79165. if (this._debugSphereMesh) {
  79166. this._debugSphereMesh.dispose();
  79167. }
  79168. if (this._debugMaterial) {
  79169. this._debugMaterial.dispose();
  79170. }
  79171. this._impostors.length = 0;
  79172. this._scene = null;
  79173. this._physicsEnginePlugin = null;
  79174. };
  79175. return PhysicsViewer;
  79176. }());
  79177. Debug.SkeletonViewer = /** @class */ (function () {
  79178. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79179. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79180. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79181. this.skeleton = skeleton;
  79182. this.mesh = mesh;
  79183. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79184. this.renderingGroupId = renderingGroupId;
  79185. this.color = BABYLON.Color3.White();
  79186. this._debugLines = new Array();
  79187. this._isEnabled = false;
  79188. this._scene = scene;
  79189. this.update();
  79190. this._renderFunction = this.update.bind(this);
  79191. }
  79192. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79193. get: function () {
  79194. return this._isEnabled;
  79195. },
  79196. set: function (value) {
  79197. if (this._isEnabled === value) {
  79198. return;
  79199. }
  79200. this._isEnabled = value;
  79201. if (value) {
  79202. this._scene.registerBeforeRender(this._renderFunction);
  79203. }
  79204. else {
  79205. this._scene.unregisterBeforeRender(this._renderFunction);
  79206. }
  79207. },
  79208. enumerable: true,
  79209. configurable: true
  79210. });
  79211. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79212. if (x === void 0) { x = 0; }
  79213. if (y === void 0) { y = 0; }
  79214. if (z === void 0) { z = 0; }
  79215. var tmat = BABYLON.Tmp.Matrix[0];
  79216. var parentBone = bone.getParent();
  79217. tmat.copyFrom(bone.getLocalMatrix());
  79218. if (x !== 0 || y !== 0 || z !== 0) {
  79219. var tmat2 = BABYLON.Tmp.Matrix[1];
  79220. BABYLON.Matrix.IdentityToRef(tmat2);
  79221. tmat2.m[12] = x;
  79222. tmat2.m[13] = y;
  79223. tmat2.m[14] = z;
  79224. tmat2.multiplyToRef(tmat, tmat);
  79225. }
  79226. if (parentBone) {
  79227. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79228. }
  79229. tmat.multiplyToRef(meshMat, tmat);
  79230. position.x = tmat.m[12];
  79231. position.y = tmat.m[13];
  79232. position.z = tmat.m[14];
  79233. };
  79234. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79235. var len = bones.length;
  79236. var meshPos = this.mesh.position;
  79237. for (var i = 0; i < len; i++) {
  79238. var bone = bones[i];
  79239. var points = this._debugLines[i];
  79240. if (!points) {
  79241. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79242. this._debugLines[i] = points;
  79243. }
  79244. this._getBonePosition(points[0], bone, meshMat);
  79245. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79246. points[0].subtractInPlace(meshPos);
  79247. points[1].subtractInPlace(meshPos);
  79248. }
  79249. };
  79250. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79251. var len = bones.length;
  79252. var boneNum = 0;
  79253. var meshPos = this.mesh.position;
  79254. for (var i = len - 1; i >= 0; i--) {
  79255. var childBone = bones[i];
  79256. var parentBone = childBone.getParent();
  79257. if (!parentBone) {
  79258. continue;
  79259. }
  79260. var points = this._debugLines[boneNum];
  79261. if (!points) {
  79262. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79263. this._debugLines[boneNum] = points;
  79264. }
  79265. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79266. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79267. points[0].subtractInPlace(meshPos);
  79268. points[1].subtractInPlace(meshPos);
  79269. boneNum++;
  79270. }
  79271. };
  79272. SkeletonViewer.prototype.update = function () {
  79273. if (this.autoUpdateBonesMatrices) {
  79274. this.skeleton.computeAbsoluteTransforms();
  79275. }
  79276. if (this.skeleton.bones[0].length === undefined) {
  79277. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79278. }
  79279. else {
  79280. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79281. }
  79282. if (!this._debugMesh) {
  79283. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79284. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79285. }
  79286. else {
  79287. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79288. }
  79289. this._debugMesh.position.copyFrom(this.mesh.position);
  79290. this._debugMesh.color = this.color;
  79291. };
  79292. SkeletonViewer.prototype.dispose = function () {
  79293. if (this._debugMesh) {
  79294. this.isEnabled = false;
  79295. this._debugMesh.dispose();
  79296. this._debugMesh = null;
  79297. }
  79298. };
  79299. return SkeletonViewer;
  79300. }());
  79301. return Debug;
  79302. }());
  79303. BABYLON.Debug = Debug;
  79304. })(BABYLON || (BABYLON = {}));
  79305. //# sourceMappingURL=babylon.debugModules.js.map
  79306. var BABYLON;
  79307. (function (BABYLON) {
  79308. var RayHelper = /** @class */ (function () {
  79309. function RayHelper(ray) {
  79310. this.ray = ray;
  79311. }
  79312. RayHelper.CreateAndShow = function (ray, scene, color) {
  79313. var helper = new RayHelper(ray);
  79314. helper.show(scene, color);
  79315. return helper;
  79316. };
  79317. RayHelper.prototype.show = function (scene, color) {
  79318. if (!this._renderFunction && this.ray) {
  79319. var ray = this.ray;
  79320. this._renderFunction = this._render.bind(this);
  79321. this._scene = scene;
  79322. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79323. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79324. if (this._renderFunction) {
  79325. this._scene.registerBeforeRender(this._renderFunction);
  79326. }
  79327. }
  79328. if (color && this._renderLine) {
  79329. this._renderLine.color.copyFrom(color);
  79330. }
  79331. };
  79332. RayHelper.prototype.hide = function () {
  79333. if (this._renderFunction && this._scene) {
  79334. this._scene.unregisterBeforeRender(this._renderFunction);
  79335. this._scene = null;
  79336. this._renderFunction = null;
  79337. if (this._renderLine) {
  79338. this._renderLine.dispose();
  79339. this._renderLine = null;
  79340. }
  79341. this._renderPoints = [];
  79342. }
  79343. };
  79344. RayHelper.prototype._render = function () {
  79345. var ray = this.ray;
  79346. if (!ray) {
  79347. return;
  79348. }
  79349. var point = this._renderPoints[1];
  79350. var len = Math.min(ray.length, 1000000);
  79351. point.copyFrom(ray.direction);
  79352. point.scaleInPlace(len);
  79353. point.addInPlace(ray.origin);
  79354. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79355. };
  79356. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79357. this._attachedToMesh = mesh;
  79358. var ray = this.ray;
  79359. if (!ray) {
  79360. return;
  79361. }
  79362. if (!ray.direction) {
  79363. ray.direction = BABYLON.Vector3.Zero();
  79364. }
  79365. if (!ray.origin) {
  79366. ray.origin = BABYLON.Vector3.Zero();
  79367. }
  79368. if (length) {
  79369. ray.length = length;
  79370. }
  79371. if (!meshSpaceOrigin) {
  79372. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79373. }
  79374. if (!meshSpaceDirection) {
  79375. // -1 so that this will work with Mesh.lookAt
  79376. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79377. }
  79378. if (!this._meshSpaceDirection) {
  79379. this._meshSpaceDirection = meshSpaceDirection.clone();
  79380. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79381. }
  79382. else {
  79383. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79384. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79385. }
  79386. if (!this._updateToMeshFunction) {
  79387. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79388. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79389. }
  79390. this._updateToMesh();
  79391. };
  79392. RayHelper.prototype.detachFromMesh = function () {
  79393. if (this._attachedToMesh) {
  79394. if (this._updateToMeshFunction) {
  79395. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79396. }
  79397. this._attachedToMesh = null;
  79398. this._updateToMeshFunction = null;
  79399. }
  79400. };
  79401. RayHelper.prototype._updateToMesh = function () {
  79402. var ray = this.ray;
  79403. if (!this._attachedToMesh || !ray) {
  79404. return;
  79405. }
  79406. if (this._attachedToMesh._isDisposed) {
  79407. this.detachFromMesh();
  79408. return;
  79409. }
  79410. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79411. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79412. };
  79413. RayHelper.prototype.dispose = function () {
  79414. this.hide();
  79415. this.detachFromMesh();
  79416. this.ray = null;
  79417. };
  79418. return RayHelper;
  79419. }());
  79420. BABYLON.RayHelper = RayHelper;
  79421. })(BABYLON || (BABYLON = {}));
  79422. //# sourceMappingURL=babylon.rayHelper.js.map
  79423. var BABYLON;
  79424. (function (BABYLON) {
  79425. // load the inspector using require, if not present in the global namespace.
  79426. var DebugLayer = /** @class */ (function () {
  79427. function DebugLayer(scene) {
  79428. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79429. this._scene = scene;
  79430. // load inspector using require, if it doesn't exist on the global namespace.
  79431. }
  79432. /** Creates the inspector window. */
  79433. DebugLayer.prototype._createInspector = function (config) {
  79434. if (config === void 0) { config = {}; }
  79435. var popup = config.popup || false;
  79436. var initialTab = config.initialTab || 0;
  79437. var parentElement = config.parentElement || null;
  79438. if (!this._inspector) {
  79439. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79440. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79441. } // else nothing to do,; instance is already existing
  79442. };
  79443. DebugLayer.prototype.isVisible = function () {
  79444. if (!this._inspector) {
  79445. return false;
  79446. }
  79447. return true;
  79448. };
  79449. DebugLayer.prototype.hide = function () {
  79450. if (this._inspector) {
  79451. try {
  79452. this._inspector.dispose();
  79453. }
  79454. catch (e) {
  79455. // If the inspector has been removed directly from the inspector tool
  79456. }
  79457. this._inspector = null;
  79458. }
  79459. };
  79460. DebugLayer.prototype.show = function (config) {
  79461. if (config === void 0) { config = {}; }
  79462. if (typeof this.BJSINSPECTOR == 'undefined') {
  79463. // Load inspector and add it to the DOM
  79464. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79465. }
  79466. else {
  79467. // Otherwise creates the inspector
  79468. this._createInspector(config);
  79469. }
  79470. };
  79471. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79472. return DebugLayer;
  79473. }());
  79474. BABYLON.DebugLayer = DebugLayer;
  79475. })(BABYLON || (BABYLON = {}));
  79476. //# sourceMappingURL=babylon.debugLayer.js.map
  79477. var BABYLON;
  79478. (function (BABYLON) {
  79479. var BoundingBoxRenderer = /** @class */ (function () {
  79480. function BoundingBoxRenderer(scene) {
  79481. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79482. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79483. this.showBackLines = true;
  79484. this.renderList = new BABYLON.SmartArray(32);
  79485. this._vertexBuffers = {};
  79486. this._scene = scene;
  79487. }
  79488. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79489. if (this._colorShader) {
  79490. return;
  79491. }
  79492. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79493. attributes: [BABYLON.VertexBuffer.PositionKind],
  79494. uniforms: ["world", "viewProjection", "color"]
  79495. });
  79496. var engine = this._scene.getEngine();
  79497. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79498. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79499. this._createIndexBuffer();
  79500. };
  79501. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79502. var engine = this._scene.getEngine();
  79503. 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]);
  79504. };
  79505. BoundingBoxRenderer.prototype._rebuild = function () {
  79506. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79507. if (vb) {
  79508. vb._rebuild();
  79509. }
  79510. this._createIndexBuffer();
  79511. };
  79512. BoundingBoxRenderer.prototype.reset = function () {
  79513. this.renderList.reset();
  79514. };
  79515. BoundingBoxRenderer.prototype.render = function () {
  79516. if (this.renderList.length === 0) {
  79517. return;
  79518. }
  79519. this._prepareRessources();
  79520. if (!this._colorShader.isReady()) {
  79521. return;
  79522. }
  79523. var engine = this._scene.getEngine();
  79524. engine.setDepthWrite(false);
  79525. this._colorShader._preBind();
  79526. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79527. var boundingBox = this.renderList.data[boundingBoxIndex];
  79528. var min = boundingBox.minimum;
  79529. var max = boundingBox.maximum;
  79530. var diff = max.subtract(min);
  79531. var median = min.add(diff.scale(0.5));
  79532. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79533. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79534. .multiply(boundingBox.getWorldMatrix());
  79535. // VBOs
  79536. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79537. if (this.showBackLines) {
  79538. // Back
  79539. engine.setDepthFunctionToGreaterOrEqual();
  79540. this._scene.resetCachedMaterial();
  79541. this._colorShader.setColor4("color", this.backColor.toColor4());
  79542. this._colorShader.bind(worldMatrix);
  79543. // Draw order
  79544. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79545. }
  79546. // Front
  79547. engine.setDepthFunctionToLess();
  79548. this._scene.resetCachedMaterial();
  79549. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79550. this._colorShader.bind(worldMatrix);
  79551. // Draw order
  79552. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79553. }
  79554. this._colorShader.unbind();
  79555. engine.setDepthFunctionToLessOrEqual();
  79556. engine.setDepthWrite(true);
  79557. };
  79558. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79559. this._prepareRessources();
  79560. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79561. return;
  79562. }
  79563. var engine = this._scene.getEngine();
  79564. engine.setDepthWrite(false);
  79565. engine.setColorWrite(false);
  79566. this._colorShader._preBind();
  79567. var boundingBox = mesh._boundingInfo.boundingBox;
  79568. var min = boundingBox.minimum;
  79569. var max = boundingBox.maximum;
  79570. var diff = max.subtract(min);
  79571. var median = min.add(diff.scale(0.5));
  79572. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79573. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79574. .multiply(boundingBox.getWorldMatrix());
  79575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79576. engine.setDepthFunctionToLess();
  79577. this._scene.resetCachedMaterial();
  79578. this._colorShader.bind(worldMatrix);
  79579. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79580. this._colorShader.unbind();
  79581. engine.setDepthFunctionToLessOrEqual();
  79582. engine.setDepthWrite(true);
  79583. engine.setColorWrite(true);
  79584. };
  79585. BoundingBoxRenderer.prototype.dispose = function () {
  79586. if (!this._colorShader) {
  79587. return;
  79588. }
  79589. this.renderList.dispose();
  79590. this._colorShader.dispose();
  79591. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79592. if (buffer) {
  79593. buffer.dispose();
  79594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79595. }
  79596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79597. };
  79598. return BoundingBoxRenderer;
  79599. }());
  79600. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79601. })(BABYLON || (BABYLON = {}));
  79602. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79603. var BABYLON;
  79604. (function (BABYLON) {
  79605. var MorphTarget = /** @class */ (function () {
  79606. function MorphTarget(name, influence) {
  79607. if (influence === void 0) { influence = 0; }
  79608. this.name = name;
  79609. this.animations = new Array();
  79610. this._positions = null;
  79611. this._normals = null;
  79612. this._tangents = null;
  79613. this.onInfluenceChanged = new BABYLON.Observable();
  79614. this.influence = influence;
  79615. }
  79616. Object.defineProperty(MorphTarget.prototype, "influence", {
  79617. get: function () {
  79618. return this._influence;
  79619. },
  79620. set: function (influence) {
  79621. if (this._influence === influence) {
  79622. return;
  79623. }
  79624. var previous = this._influence;
  79625. this._influence = influence;
  79626. if (this.onInfluenceChanged.hasObservers) {
  79627. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79628. }
  79629. },
  79630. enumerable: true,
  79631. configurable: true
  79632. });
  79633. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79634. get: function () {
  79635. return !!this._positions;
  79636. },
  79637. enumerable: true,
  79638. configurable: true
  79639. });
  79640. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79641. get: function () {
  79642. return !!this._normals;
  79643. },
  79644. enumerable: true,
  79645. configurable: true
  79646. });
  79647. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79648. get: function () {
  79649. return !!this._tangents;
  79650. },
  79651. enumerable: true,
  79652. configurable: true
  79653. });
  79654. MorphTarget.prototype.setPositions = function (data) {
  79655. this._positions = data;
  79656. };
  79657. MorphTarget.prototype.getPositions = function () {
  79658. return this._positions;
  79659. };
  79660. MorphTarget.prototype.setNormals = function (data) {
  79661. this._normals = data;
  79662. };
  79663. MorphTarget.prototype.getNormals = function () {
  79664. return this._normals;
  79665. };
  79666. MorphTarget.prototype.setTangents = function (data) {
  79667. this._tangents = data;
  79668. };
  79669. MorphTarget.prototype.getTangents = function () {
  79670. return this._tangents;
  79671. };
  79672. /**
  79673. * Serializes the current target into a Serialization object.
  79674. * Returns the serialized object.
  79675. */
  79676. MorphTarget.prototype.serialize = function () {
  79677. var serializationObject = {};
  79678. serializationObject.name = this.name;
  79679. serializationObject.influence = this.influence;
  79680. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79681. if (this.hasNormals) {
  79682. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79683. }
  79684. if (this.hasTangents) {
  79685. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79686. }
  79687. // Animations
  79688. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79689. return serializationObject;
  79690. };
  79691. // Statics
  79692. MorphTarget.Parse = function (serializationObject) {
  79693. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79694. result.setPositions(serializationObject.positions);
  79695. if (serializationObject.normals) {
  79696. result.setNormals(serializationObject.normals);
  79697. }
  79698. if (serializationObject.tangents) {
  79699. result.setTangents(serializationObject.tangents);
  79700. }
  79701. // Animations
  79702. if (serializationObject.animations) {
  79703. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79704. var parsedAnimation = serializationObject.animations[animationIndex];
  79705. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79706. }
  79707. }
  79708. return result;
  79709. };
  79710. MorphTarget.FromMesh = function (mesh, name, influence) {
  79711. if (!name) {
  79712. name = mesh.name;
  79713. }
  79714. var result = new MorphTarget(name, influence);
  79715. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79717. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79718. }
  79719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79720. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79721. }
  79722. return result;
  79723. };
  79724. return MorphTarget;
  79725. }());
  79726. BABYLON.MorphTarget = MorphTarget;
  79727. })(BABYLON || (BABYLON = {}));
  79728. //# sourceMappingURL=babylon.morphTarget.js.map
  79729. var BABYLON;
  79730. (function (BABYLON) {
  79731. var MorphTargetManager = /** @class */ (function () {
  79732. function MorphTargetManager(scene) {
  79733. if (scene === void 0) { scene = null; }
  79734. this._targets = new Array();
  79735. this._targetObservable = new Array();
  79736. this._activeTargets = new BABYLON.SmartArray(16);
  79737. this._supportsNormals = false;
  79738. this._supportsTangents = false;
  79739. this._vertexCount = 0;
  79740. this._uniqueId = 0;
  79741. this._tempInfluences = new Array();
  79742. if (!scene) {
  79743. scene = BABYLON.Engine.LastCreatedScene;
  79744. }
  79745. this._scene = scene;
  79746. if (this._scene) {
  79747. this._scene.morphTargetManagers.push(this);
  79748. this._uniqueId = this._scene.getUniqueId();
  79749. }
  79750. }
  79751. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79752. get: function () {
  79753. return this._uniqueId;
  79754. },
  79755. enumerable: true,
  79756. configurable: true
  79757. });
  79758. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79759. get: function () {
  79760. return this._vertexCount;
  79761. },
  79762. enumerable: true,
  79763. configurable: true
  79764. });
  79765. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79766. get: function () {
  79767. return this._supportsNormals;
  79768. },
  79769. enumerable: true,
  79770. configurable: true
  79771. });
  79772. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79773. get: function () {
  79774. return this._supportsTangents;
  79775. },
  79776. enumerable: true,
  79777. configurable: true
  79778. });
  79779. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79780. get: function () {
  79781. return this._targets.length;
  79782. },
  79783. enumerable: true,
  79784. configurable: true
  79785. });
  79786. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79787. get: function () {
  79788. return this._activeTargets.length;
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79794. get: function () {
  79795. return this._influences;
  79796. },
  79797. enumerable: true,
  79798. configurable: true
  79799. });
  79800. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79801. return this._activeTargets.data[index];
  79802. };
  79803. MorphTargetManager.prototype.getTarget = function (index) {
  79804. return this._targets[index];
  79805. };
  79806. MorphTargetManager.prototype.addTarget = function (target) {
  79807. var _this = this;
  79808. this._targets.push(target);
  79809. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79810. _this._syncActiveTargets(needUpdate);
  79811. }));
  79812. this._syncActiveTargets(true);
  79813. };
  79814. MorphTargetManager.prototype.removeTarget = function (target) {
  79815. var index = this._targets.indexOf(target);
  79816. if (index >= 0) {
  79817. this._targets.splice(index, 1);
  79818. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79819. this._syncActiveTargets(true);
  79820. }
  79821. };
  79822. /**
  79823. * Serializes the current manager into a Serialization object.
  79824. * Returns the serialized object.
  79825. */
  79826. MorphTargetManager.prototype.serialize = function () {
  79827. var serializationObject = {};
  79828. serializationObject.id = this.uniqueId;
  79829. serializationObject.targets = [];
  79830. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79831. var target = _a[_i];
  79832. serializationObject.targets.push(target.serialize());
  79833. }
  79834. return serializationObject;
  79835. };
  79836. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79837. var influenceCount = 0;
  79838. this._activeTargets.reset();
  79839. this._supportsNormals = true;
  79840. this._supportsTangents = true;
  79841. this._vertexCount = 0;
  79842. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79843. var target = _a[_i];
  79844. this._activeTargets.push(target);
  79845. this._tempInfluences[influenceCount++] = target.influence;
  79846. var positions = target.getPositions();
  79847. if (positions) {
  79848. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79849. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79850. var vertexCount = positions.length / 3;
  79851. if (this._vertexCount === 0) {
  79852. this._vertexCount = vertexCount;
  79853. }
  79854. else if (this._vertexCount !== vertexCount) {
  79855. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79856. return;
  79857. }
  79858. }
  79859. }
  79860. if (!this._influences || this._influences.length !== influenceCount) {
  79861. this._influences = new Float32Array(influenceCount);
  79862. }
  79863. for (var index = 0; index < influenceCount; index++) {
  79864. this._influences[index] = this._tempInfluences[index];
  79865. }
  79866. if (needUpdate && this._scene) {
  79867. // Flag meshes as dirty to resync with the active targets
  79868. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79869. var mesh = _c[_b];
  79870. if (mesh.morphTargetManager === this) {
  79871. mesh._syncGeometryWithMorphTargetManager();
  79872. }
  79873. }
  79874. }
  79875. };
  79876. // Statics
  79877. MorphTargetManager.Parse = function (serializationObject, scene) {
  79878. var result = new MorphTargetManager(scene);
  79879. result._uniqueId = serializationObject.id;
  79880. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79881. var targetData = _a[_i];
  79882. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79883. }
  79884. return result;
  79885. };
  79886. return MorphTargetManager;
  79887. }());
  79888. BABYLON.MorphTargetManager = MorphTargetManager;
  79889. })(BABYLON || (BABYLON = {}));
  79890. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79891. var BABYLON;
  79892. (function (BABYLON) {
  79893. var Octree = /** @class */ (function () {
  79894. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79895. if (maxDepth === void 0) { maxDepth = 2; }
  79896. this.maxDepth = maxDepth;
  79897. this.dynamicContent = new Array();
  79898. this._maxBlockCapacity = maxBlockCapacity || 64;
  79899. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79900. this._creationFunc = creationFunc;
  79901. }
  79902. // Methods
  79903. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79904. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79905. };
  79906. Octree.prototype.addMesh = function (entry) {
  79907. for (var index = 0; index < this.blocks.length; index++) {
  79908. var block = this.blocks[index];
  79909. block.addEntry(entry);
  79910. }
  79911. };
  79912. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79913. this._selectionContent.reset();
  79914. for (var index = 0; index < this.blocks.length; index++) {
  79915. var block = this.blocks[index];
  79916. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79917. }
  79918. if (allowDuplicate) {
  79919. this._selectionContent.concat(this.dynamicContent);
  79920. }
  79921. else {
  79922. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79923. }
  79924. return this._selectionContent;
  79925. };
  79926. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79927. this._selectionContent.reset();
  79928. for (var index = 0; index < this.blocks.length; index++) {
  79929. var block = this.blocks[index];
  79930. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79931. }
  79932. if (allowDuplicate) {
  79933. this._selectionContent.concat(this.dynamicContent);
  79934. }
  79935. else {
  79936. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79937. }
  79938. return this._selectionContent;
  79939. };
  79940. Octree.prototype.intersectsRay = function (ray) {
  79941. this._selectionContent.reset();
  79942. for (var index = 0; index < this.blocks.length; index++) {
  79943. var block = this.blocks[index];
  79944. block.intersectsRay(ray, this._selectionContent);
  79945. }
  79946. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79947. return this._selectionContent;
  79948. };
  79949. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79950. target.blocks = new Array();
  79951. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79952. // Segmenting space
  79953. for (var x = 0; x < 2; x++) {
  79954. for (var y = 0; y < 2; y++) {
  79955. for (var z = 0; z < 2; z++) {
  79956. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79957. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79958. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79959. block.addEntries(entries);
  79960. target.blocks.push(block);
  79961. }
  79962. }
  79963. }
  79964. };
  79965. Octree.CreationFuncForMeshes = function (entry, block) {
  79966. var boundingInfo = entry.getBoundingInfo();
  79967. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79968. block.entries.push(entry);
  79969. }
  79970. };
  79971. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79972. var boundingInfo = entry.getBoundingInfo();
  79973. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79974. block.entries.push(entry);
  79975. }
  79976. };
  79977. return Octree;
  79978. }());
  79979. BABYLON.Octree = Octree;
  79980. })(BABYLON || (BABYLON = {}));
  79981. //# sourceMappingURL=babylon.octree.js.map
  79982. var BABYLON;
  79983. (function (BABYLON) {
  79984. var OctreeBlock = /** @class */ (function () {
  79985. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79986. this.entries = new Array();
  79987. this._boundingVectors = new Array();
  79988. this._capacity = capacity;
  79989. this._depth = depth;
  79990. this._maxDepth = maxDepth;
  79991. this._creationFunc = creationFunc;
  79992. this._minPoint = minPoint;
  79993. this._maxPoint = maxPoint;
  79994. this._boundingVectors.push(minPoint.clone());
  79995. this._boundingVectors.push(maxPoint.clone());
  79996. this._boundingVectors.push(minPoint.clone());
  79997. this._boundingVectors[2].x = maxPoint.x;
  79998. this._boundingVectors.push(minPoint.clone());
  79999. this._boundingVectors[3].y = maxPoint.y;
  80000. this._boundingVectors.push(minPoint.clone());
  80001. this._boundingVectors[4].z = maxPoint.z;
  80002. this._boundingVectors.push(maxPoint.clone());
  80003. this._boundingVectors[5].z = minPoint.z;
  80004. this._boundingVectors.push(maxPoint.clone());
  80005. this._boundingVectors[6].x = minPoint.x;
  80006. this._boundingVectors.push(maxPoint.clone());
  80007. this._boundingVectors[7].y = minPoint.y;
  80008. }
  80009. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80010. // Property
  80011. get: function () {
  80012. return this._capacity;
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80018. get: function () {
  80019. return this._minPoint;
  80020. },
  80021. enumerable: true,
  80022. configurable: true
  80023. });
  80024. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80025. get: function () {
  80026. return this._maxPoint;
  80027. },
  80028. enumerable: true,
  80029. configurable: true
  80030. });
  80031. // Methods
  80032. OctreeBlock.prototype.addEntry = function (entry) {
  80033. if (this.blocks) {
  80034. for (var index = 0; index < this.blocks.length; index++) {
  80035. var block = this.blocks[index];
  80036. block.addEntry(entry);
  80037. }
  80038. return;
  80039. }
  80040. this._creationFunc(entry, this);
  80041. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80042. this.createInnerBlocks();
  80043. }
  80044. };
  80045. OctreeBlock.prototype.addEntries = function (entries) {
  80046. for (var index = 0; index < entries.length; index++) {
  80047. var mesh = entries[index];
  80048. this.addEntry(mesh);
  80049. }
  80050. };
  80051. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80052. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80053. if (this.blocks) {
  80054. for (var index = 0; index < this.blocks.length; index++) {
  80055. var block = this.blocks[index];
  80056. block.select(frustumPlanes, selection, allowDuplicate);
  80057. }
  80058. return;
  80059. }
  80060. if (allowDuplicate) {
  80061. selection.concat(this.entries);
  80062. }
  80063. else {
  80064. selection.concatWithNoDuplicate(this.entries);
  80065. }
  80066. }
  80067. };
  80068. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80069. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80070. if (this.blocks) {
  80071. for (var index = 0; index < this.blocks.length; index++) {
  80072. var block = this.blocks[index];
  80073. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80074. }
  80075. return;
  80076. }
  80077. if (allowDuplicate) {
  80078. selection.concat(this.entries);
  80079. }
  80080. else {
  80081. selection.concatWithNoDuplicate(this.entries);
  80082. }
  80083. }
  80084. };
  80085. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80086. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80087. if (this.blocks) {
  80088. for (var index = 0; index < this.blocks.length; index++) {
  80089. var block = this.blocks[index];
  80090. block.intersectsRay(ray, selection);
  80091. }
  80092. return;
  80093. }
  80094. selection.concatWithNoDuplicate(this.entries);
  80095. }
  80096. };
  80097. OctreeBlock.prototype.createInnerBlocks = function () {
  80098. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80099. };
  80100. return OctreeBlock;
  80101. }());
  80102. BABYLON.OctreeBlock = OctreeBlock;
  80103. })(BABYLON || (BABYLON = {}));
  80104. //# sourceMappingURL=babylon.octreeBlock.js.map
  80105. var BABYLON;
  80106. (function (BABYLON) {
  80107. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80108. __extends(VRDistortionCorrectionPostProcess, _super);
  80109. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80110. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80111. 'LensCenter',
  80112. 'Scale',
  80113. 'ScaleIn',
  80114. 'HmdWarpParam'
  80115. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80116. _this._isRightEye = isRightEye;
  80117. _this._distortionFactors = vrMetrics.distortionK;
  80118. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80119. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80120. _this.adaptScaleToCurrentViewport = true;
  80121. _this.onSizeChangedObservable.add(function () {
  80122. _this.aspectRatio = _this.width * .5 / _this.height;
  80123. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80124. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80125. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80126. });
  80127. _this.onApplyObservable.add(function (effect) {
  80128. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80129. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80130. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80131. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80132. });
  80133. return _this;
  80134. }
  80135. return VRDistortionCorrectionPostProcess;
  80136. }(BABYLON.PostProcess));
  80137. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80138. })(BABYLON || (BABYLON = {}));
  80139. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80140. var BABYLON;
  80141. (function (BABYLON) {
  80142. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80143. __extends(AnaglyphPostProcess, _super);
  80144. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80145. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80146. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80147. _this.onApplyObservable.add(function (effect) {
  80148. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80149. });
  80150. return _this;
  80151. }
  80152. return AnaglyphPostProcess;
  80153. }(BABYLON.PostProcess));
  80154. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80155. })(BABYLON || (BABYLON = {}));
  80156. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80157. var BABYLON;
  80158. (function (BABYLON) {
  80159. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80160. __extends(StereoscopicInterlacePostProcess, _super);
  80161. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80162. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80163. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80164. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80165. _this.onSizeChangedObservable.add(function () {
  80166. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80167. });
  80168. _this.onApplyObservable.add(function (effect) {
  80169. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80170. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80171. });
  80172. return _this;
  80173. }
  80174. return StereoscopicInterlacePostProcess;
  80175. }(BABYLON.PostProcess));
  80176. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80177. })(BABYLON || (BABYLON = {}));
  80178. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80179. var BABYLON;
  80180. (function (BABYLON) {
  80181. /**
  80182. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80183. * Screen rotation is taken into account.
  80184. */
  80185. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80186. function FreeCameraDeviceOrientationInput() {
  80187. var _this = this;
  80188. this._screenOrientationAngle = 0;
  80189. this._screenQuaternion = new BABYLON.Quaternion();
  80190. this._alpha = 0;
  80191. this._beta = 0;
  80192. this._gamma = 0;
  80193. this._orientationChanged = function () {
  80194. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80195. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80196. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80197. };
  80198. this._deviceOrientation = function (evt) {
  80199. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80200. _this._beta = evt.beta !== null ? evt.beta : 0;
  80201. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80202. };
  80203. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80204. this._orientationChanged();
  80205. }
  80206. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80207. get: function () {
  80208. return this._camera;
  80209. },
  80210. set: function (camera) {
  80211. this._camera = camera;
  80212. if (this._camera != null && !this._camera.rotationQuaternion) {
  80213. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80214. }
  80215. },
  80216. enumerable: true,
  80217. configurable: true
  80218. });
  80219. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80220. window.addEventListener("orientationchange", this._orientationChanged);
  80221. window.addEventListener("deviceorientation", this._deviceOrientation);
  80222. //In certain cases, the attach control is called AFTER orientation was changed,
  80223. //So this is needed.
  80224. this._orientationChanged();
  80225. };
  80226. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80227. window.removeEventListener("orientationchange", this._orientationChanged);
  80228. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80229. };
  80230. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80231. //if no device orientation provided, don't update the rotation.
  80232. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80233. if (!this._alpha)
  80234. return;
  80235. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80236. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80237. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80238. //Mirror on XY Plane
  80239. this._camera.rotationQuaternion.z *= -1;
  80240. this._camera.rotationQuaternion.w *= -1;
  80241. };
  80242. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80243. return "FreeCameraDeviceOrientationInput";
  80244. };
  80245. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80246. return "deviceOrientation";
  80247. };
  80248. return FreeCameraDeviceOrientationInput;
  80249. }());
  80250. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80251. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80252. })(BABYLON || (BABYLON = {}));
  80253. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80254. var BABYLON;
  80255. (function (BABYLON) {
  80256. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80257. function ArcRotateCameraVRDeviceOrientationInput() {
  80258. this.alphaCorrection = 1;
  80259. this.betaCorrection = 1;
  80260. this.gammaCorrection = 1;
  80261. this._alpha = 0;
  80262. this._gamma = 0;
  80263. this._dirty = false;
  80264. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80265. }
  80266. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80267. this.camera.attachControl(element, noPreventDefault);
  80268. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80269. };
  80270. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80271. if (evt.alpha !== null) {
  80272. this._alpha = +evt.alpha | 0;
  80273. }
  80274. if (evt.gamma !== null) {
  80275. this._gamma = +evt.gamma | 0;
  80276. }
  80277. this._dirty = true;
  80278. };
  80279. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80280. if (this._dirty) {
  80281. this._dirty = false;
  80282. if (this._gamma < 0) {
  80283. this._gamma = 180 + this._gamma;
  80284. }
  80285. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80286. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80287. }
  80288. };
  80289. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80290. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80291. };
  80292. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80293. return "ArcRotateCameraVRDeviceOrientationInput";
  80294. };
  80295. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80296. return "VRDeviceOrientation";
  80297. };
  80298. return ArcRotateCameraVRDeviceOrientationInput;
  80299. }());
  80300. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80301. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80302. })(BABYLON || (BABYLON = {}));
  80303. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80304. var BABYLON;
  80305. (function (BABYLON) {
  80306. var VRCameraMetrics = /** @class */ (function () {
  80307. function VRCameraMetrics() {
  80308. this.compensateDistortion = true;
  80309. }
  80310. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80311. get: function () {
  80312. return this.hResolution / (2 * this.vResolution);
  80313. },
  80314. enumerable: true,
  80315. configurable: true
  80316. });
  80317. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80318. get: function () {
  80319. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80320. },
  80321. enumerable: true,
  80322. configurable: true
  80323. });
  80324. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80325. get: function () {
  80326. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80327. var h = (4 * meters) / this.hScreenSize;
  80328. return BABYLON.Matrix.Translation(h, 0, 0);
  80329. },
  80330. enumerable: true,
  80331. configurable: true
  80332. });
  80333. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80334. get: function () {
  80335. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80336. var h = (4 * meters) / this.hScreenSize;
  80337. return BABYLON.Matrix.Translation(-h, 0, 0);
  80338. },
  80339. enumerable: true,
  80340. configurable: true
  80341. });
  80342. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80343. get: function () {
  80344. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80345. },
  80346. enumerable: true,
  80347. configurable: true
  80348. });
  80349. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80350. get: function () {
  80351. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80352. },
  80353. enumerable: true,
  80354. configurable: true
  80355. });
  80356. VRCameraMetrics.GetDefault = function () {
  80357. var result = new VRCameraMetrics();
  80358. result.hResolution = 1280;
  80359. result.vResolution = 800;
  80360. result.hScreenSize = 0.149759993;
  80361. result.vScreenSize = 0.0935999975;
  80362. result.vScreenCenter = 0.0467999987;
  80363. result.eyeToScreenDistance = 0.0410000011;
  80364. result.lensSeparationDistance = 0.0635000020;
  80365. result.interpupillaryDistance = 0.0640000030;
  80366. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80367. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80368. result.postProcessScaleFactor = 1.714605507808412;
  80369. result.lensCenterOffset = 0.151976421;
  80370. return result;
  80371. };
  80372. return VRCameraMetrics;
  80373. }());
  80374. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80375. })(BABYLON || (BABYLON = {}));
  80376. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80377. var BABYLON;
  80378. (function (BABYLON) {
  80379. /**
  80380. * This represents a WebVR camera.
  80381. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80382. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80383. */
  80384. var WebVRFreeCamera = /** @class */ (function (_super) {
  80385. __extends(WebVRFreeCamera, _super);
  80386. /**
  80387. * Instantiates a WebVRFreeCamera.
  80388. * @param name The name of the WebVRFreeCamera
  80389. * @param position The starting anchor position for the camera
  80390. * @param scene The scene the camera belongs to
  80391. * @param webVROptions a set of customizable options for the webVRCamera
  80392. */
  80393. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80394. if (webVROptions === void 0) { webVROptions = {}; }
  80395. var _this = _super.call(this, name, position, scene) || this;
  80396. _this.webVROptions = webVROptions;
  80397. /**
  80398. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80399. */
  80400. _this._vrDevice = null;
  80401. /**
  80402. * The rawPose of the vrDevice.
  80403. */
  80404. _this.rawPose = null;
  80405. _this._specsVersion = "1.1";
  80406. _this._attached = false;
  80407. _this._descendants = [];
  80408. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80409. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80410. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80411. _this._standingMatrix = null;
  80412. /**
  80413. * Represents device position in babylon space.
  80414. */
  80415. _this.devicePosition = BABYLON.Vector3.Zero();
  80416. /**
  80417. * Represents device rotation in babylon space.
  80418. */
  80419. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80420. /**
  80421. * The scale of the device to be used when translating from device space to babylon space.
  80422. */
  80423. _this.deviceScaleFactor = 1;
  80424. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80425. _this._worldToDevice = BABYLON.Matrix.Identity();
  80426. /**
  80427. * References to the webVR controllers for the vrDevice.
  80428. */
  80429. _this.controllers = [];
  80430. /**
  80431. * Emits an event when a controller is attached.
  80432. */
  80433. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80434. /**
  80435. * Emits an event when a controller's mesh has been loaded;
  80436. */
  80437. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80438. /**
  80439. * If the rig cameras be used as parent instead of this camera.
  80440. */
  80441. _this.rigParenting = true;
  80442. _this._defaultHeight = undefined;
  80443. _this._workingVector = BABYLON.Vector3.Zero();
  80444. _this._oneVector = BABYLON.Vector3.One();
  80445. _this._workingMatrix = BABYLON.Matrix.Identity();
  80446. _this._cache.position = BABYLON.Vector3.Zero();
  80447. if (webVROptions.defaultHeight) {
  80448. _this._defaultHeight = webVROptions.defaultHeight;
  80449. _this.position.y = _this._defaultHeight;
  80450. }
  80451. _this.minZ = 0.1;
  80452. //legacy support - the compensation boolean was removed.
  80453. if (arguments.length === 5) {
  80454. _this.webVROptions = arguments[4];
  80455. }
  80456. // default webVR options
  80457. if (_this.webVROptions.trackPosition == undefined) {
  80458. _this.webVROptions.trackPosition = true;
  80459. }
  80460. if (_this.webVROptions.controllerMeshes == undefined) {
  80461. _this.webVROptions.controllerMeshes = true;
  80462. }
  80463. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80464. _this.webVROptions.defaultLightingOnControllers = true;
  80465. }
  80466. _this.rotationQuaternion = new BABYLON.Quaternion();
  80467. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80468. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80469. }
  80470. //enable VR
  80471. var engine = _this.getEngine();
  80472. _this._onVREnabled = function (success) { if (success) {
  80473. _this.initControllers();
  80474. } };
  80475. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80476. engine.initWebVR().add(function (event) {
  80477. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80478. return;
  80479. }
  80480. _this._vrDevice = event.vrDisplay;
  80481. //reset the rig parameters.
  80482. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80483. if (_this._attached) {
  80484. _this.getEngine().enableVR();
  80485. }
  80486. });
  80487. if (typeof (VRFrameData) !== "undefined")
  80488. _this._frameData = new VRFrameData();
  80489. /**
  80490. * The idea behind the following lines:
  80491. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80492. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80493. * the second will not show it correctly.
  80494. *
  80495. * To solve this - each object that has the camera as parent will be added to a protected array.
  80496. * When the rig camera renders, it will take this array and set all of those to be its children.
  80497. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80498. * Amazing!
  80499. */
  80500. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80501. if (camera.parent === _this && _this.rigParenting) {
  80502. _this._descendants = _this.getDescendants(true, function (n) {
  80503. // don't take the cameras or the controllers!
  80504. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80505. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80506. return !isController && !isRigCamera;
  80507. });
  80508. _this._descendants.forEach(function (node) {
  80509. node.parent = camera;
  80510. });
  80511. }
  80512. });
  80513. scene.onAfterCameraRenderObservable.add(function (camera) {
  80514. if (camera.parent === _this && _this.rigParenting) {
  80515. _this._descendants.forEach(function (node) {
  80516. node.parent = _this;
  80517. });
  80518. }
  80519. });
  80520. return _this;
  80521. }
  80522. /**
  80523. * Gets the device distance from the ground in meters.
  80524. * @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.
  80525. */
  80526. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80527. if (this._standingMatrix) {
  80528. // Add standing matrix offset to get real offset from ground in room
  80529. this._standingMatrix.getTranslationToRef(this._workingVector);
  80530. return this._deviceRoomPosition.y + this._workingVector.y;
  80531. }
  80532. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80533. return this._defaultHeight || 0;
  80534. };
  80535. /**
  80536. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80537. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80538. */
  80539. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80540. var _this = this;
  80541. if (callback === void 0) { callback = function (bool) { }; }
  80542. // Use standing matrix if available
  80543. this.getEngine().initWebVRAsync().then(function (result) {
  80544. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80545. callback(false);
  80546. }
  80547. else {
  80548. _this._standingMatrix = new BABYLON.Matrix();
  80549. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80550. if (!_this.getScene().useRightHandedSystem) {
  80551. [2, 6, 8, 9, 14].forEach(function (num) {
  80552. if (_this._standingMatrix) {
  80553. _this._standingMatrix.m[num] *= -1;
  80554. }
  80555. });
  80556. }
  80557. callback(true);
  80558. }
  80559. });
  80560. };
  80561. /**
  80562. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80563. * @returns A promise with a boolean set to if the standing matrix is supported.
  80564. */
  80565. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80566. var _this = this;
  80567. return new Promise(function (res, rej) {
  80568. _this.useStandingMatrix(function (supported) {
  80569. res(supported);
  80570. });
  80571. });
  80572. };
  80573. /**
  80574. * Disposes the camera
  80575. */
  80576. WebVRFreeCamera.prototype.dispose = function () {
  80577. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80578. _super.prototype.dispose.call(this);
  80579. };
  80580. /**
  80581. * Gets a vrController by name.
  80582. * @param name The name of the controller to retreive
  80583. * @returns the controller matching the name specified or null if not found
  80584. */
  80585. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80586. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80587. var gp = _a[_i];
  80588. if (gp.hand === name) {
  80589. return gp;
  80590. }
  80591. }
  80592. return null;
  80593. };
  80594. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80595. /**
  80596. * The controller corrisponding to the users left hand.
  80597. */
  80598. get: function () {
  80599. if (!this._leftController) {
  80600. this._leftController = this.getControllerByName("left");
  80601. }
  80602. return this._leftController;
  80603. },
  80604. enumerable: true,
  80605. configurable: true
  80606. });
  80607. ;
  80608. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80609. /**
  80610. * The controller corrisponding to the users right hand.
  80611. */
  80612. get: function () {
  80613. if (!this._rightController) {
  80614. this._rightController = this.getControllerByName("right");
  80615. }
  80616. return this._rightController;
  80617. },
  80618. enumerable: true,
  80619. configurable: true
  80620. });
  80621. ;
  80622. /**
  80623. * Casts a ray forward from the vrCamera's gaze.
  80624. * @param length Length of the ray (default: 100)
  80625. * @returns the ray corrisponding to the gaze
  80626. */
  80627. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80628. if (length === void 0) { length = 100; }
  80629. if (this.leftCamera) {
  80630. // Use left eye to avoid computation to compute center on every call
  80631. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80632. }
  80633. else {
  80634. return _super.prototype.getForwardRay.call(this, length);
  80635. }
  80636. };
  80637. /**
  80638. * Updates the camera based on device's frame data
  80639. */
  80640. WebVRFreeCamera.prototype._checkInputs = function () {
  80641. if (this._vrDevice && this._vrDevice.isPresenting) {
  80642. this._vrDevice.getFrameData(this._frameData);
  80643. this.updateFromDevice(this._frameData.pose);
  80644. }
  80645. _super.prototype._checkInputs.call(this);
  80646. };
  80647. /**
  80648. * Updates the poseControlled values based on the input device pose.
  80649. * @param poseData Pose coming from the device
  80650. */
  80651. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80652. if (poseData && poseData.orientation) {
  80653. this.rawPose = poseData;
  80654. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80655. if (this.getScene().useRightHandedSystem) {
  80656. this._deviceRoomRotationQuaternion.z *= -1;
  80657. this._deviceRoomRotationQuaternion.w *= -1;
  80658. }
  80659. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80660. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80661. if (this.getScene().useRightHandedSystem) {
  80662. this._deviceRoomPosition.z *= -1;
  80663. }
  80664. }
  80665. }
  80666. };
  80667. /**
  80668. * WebVR's attach control will start broadcasting frames to the device.
  80669. * Note that in certain browsers (chrome for example) this function must be called
  80670. * within a user-interaction callback. Example:
  80671. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80672. *
  80673. * @param element html element to attach the vrDevice to
  80674. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80675. */
  80676. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80677. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80678. this._attached = true;
  80679. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80680. if (this._vrDevice) {
  80681. this.getEngine().enableVR();
  80682. }
  80683. };
  80684. /**
  80685. * Detaches the camera from the html element and disables VR
  80686. *
  80687. * @param element html element to detach from
  80688. */
  80689. WebVRFreeCamera.prototype.detachControl = function (element) {
  80690. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80691. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80692. _super.prototype.detachControl.call(this, element);
  80693. this._attached = false;
  80694. this.getEngine().disableVR();
  80695. };
  80696. /**
  80697. * @returns the name of this class
  80698. */
  80699. WebVRFreeCamera.prototype.getClassName = function () {
  80700. return "WebVRFreeCamera";
  80701. };
  80702. /**
  80703. * Calls resetPose on the vrDisplay
  80704. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80705. */
  80706. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80707. //uses the vrDisplay's "resetPose()".
  80708. //pitch and roll won't be affected.
  80709. this._vrDevice.resetPose();
  80710. };
  80711. /**
  80712. * Updates the rig cameras (left and right eye)
  80713. */
  80714. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80715. var camLeft = this._rigCameras[0];
  80716. var camRight = this._rigCameras[1];
  80717. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80718. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80719. camLeft.position.copyFrom(this._deviceRoomPosition);
  80720. camRight.position.copyFrom(this._deviceRoomPosition);
  80721. };
  80722. /**
  80723. * Updates the cached values of the camera
  80724. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80725. */
  80726. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80727. var _this = this;
  80728. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80729. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80730. if (!this.updateCacheCalled) {
  80731. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80732. this.updateCacheCalled = true;
  80733. this.update();
  80734. }
  80735. // Set working vector to the device position in room space rotated by the new rotation
  80736. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80737. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80738. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80739. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80740. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80741. // Add translation from anchor position
  80742. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80743. this._workingVector.addInPlace(this.position);
  80744. this._workingVector.subtractInPlace(this._cache.position);
  80745. this._deviceToWorld.setTranslation(this._workingVector);
  80746. // Set an inverted matrix to be used when updating the camera
  80747. this._deviceToWorld.invertToRef(this._worldToDevice);
  80748. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80749. this.controllers.forEach(function (controller) {
  80750. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80751. controller.update();
  80752. });
  80753. }
  80754. if (!ignoreParentClass) {
  80755. _super.prototype._updateCache.call(this);
  80756. }
  80757. this.updateCacheCalled = false;
  80758. };
  80759. /**
  80760. * Updates the current device position and rotation in the babylon world
  80761. */
  80762. WebVRFreeCamera.prototype.update = function () {
  80763. // Get current device position in babylon world
  80764. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80765. // Get current device rotation in babylon world
  80766. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80767. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80768. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80769. _super.prototype.update.call(this);
  80770. };
  80771. /**
  80772. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80773. * @returns an identity matrix
  80774. */
  80775. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80776. return BABYLON.Matrix.Identity();
  80777. };
  80778. /**
  80779. * This function is called by the two RIG cameras.
  80780. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80781. */
  80782. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80783. var _this = this;
  80784. // Update the parent camera prior to using a child camera to avoid desynchronization
  80785. var parentCamera = this._cameraRigParams["parentCamera"];
  80786. parentCamera._updateCache();
  80787. //WebVR 1.1
  80788. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80789. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80790. if (!this.getScene().useRightHandedSystem) {
  80791. [2, 6, 8, 9, 14].forEach(function (num) {
  80792. _this._webvrViewMatrix.m[num] *= -1;
  80793. });
  80794. }
  80795. // update the camera rotation matrix
  80796. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80797. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80798. // Computing target and final matrix
  80799. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80800. // should the view matrix be updated with scale and position offset?
  80801. if (parentCamera.deviceScaleFactor !== 1) {
  80802. this._webvrViewMatrix.invert();
  80803. // scale the position, if set
  80804. if (parentCamera.deviceScaleFactor) {
  80805. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80806. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80807. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80808. }
  80809. this._webvrViewMatrix.invert();
  80810. }
  80811. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80812. return this._webvrViewMatrix;
  80813. };
  80814. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80815. var _this = this;
  80816. var parentCamera = this.parent;
  80817. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80818. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80819. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80820. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80821. //babylon compatible matrix
  80822. if (!this.getScene().useRightHandedSystem) {
  80823. [8, 9, 10, 11].forEach(function (num) {
  80824. _this._projectionMatrix.m[num] *= -1;
  80825. });
  80826. }
  80827. return this._projectionMatrix;
  80828. };
  80829. /**
  80830. * Initializes the controllers and their meshes
  80831. */
  80832. WebVRFreeCamera.prototype.initControllers = function () {
  80833. var _this = this;
  80834. this.controllers = [];
  80835. var manager = this.getScene().gamepadManager;
  80836. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80837. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80838. var webVrController = gamepad;
  80839. if (webVrController.defaultModel) {
  80840. webVrController.defaultModel.setEnabled(false);
  80841. }
  80842. if (webVrController.hand === "right") {
  80843. _this._rightController = null;
  80844. }
  80845. if (webVrController.hand === "left") {
  80846. _this._leftController = null;
  80847. }
  80848. var controllerIndex = _this.controllers.indexOf(webVrController);
  80849. if (controllerIndex !== -1) {
  80850. _this.controllers.splice(controllerIndex, 1);
  80851. }
  80852. }
  80853. });
  80854. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80855. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80856. var webVrController_1 = gamepad;
  80857. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80858. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80859. if (_this.webVROptions.controllerMeshes) {
  80860. if (webVrController_1.defaultModel) {
  80861. webVrController_1.defaultModel.setEnabled(true);
  80862. }
  80863. else {
  80864. // Load the meshes
  80865. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80866. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80867. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80868. if (_this.webVROptions.defaultLightingOnControllers) {
  80869. if (!_this._lightOnControllers) {
  80870. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80871. }
  80872. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80873. var children = mesh.getChildren();
  80874. if (children.length !== 0) {
  80875. children.forEach(function (mesh) {
  80876. light.includedOnlyMeshes.push(mesh);
  80877. activateLightOnSubMeshes_1(mesh, light);
  80878. });
  80879. }
  80880. };
  80881. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80882. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80883. }
  80884. });
  80885. }
  80886. }
  80887. webVrController_1.attachToPoseControlledCamera(_this);
  80888. // since this is async - sanity check. Is the controller already stored?
  80889. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80890. //add to the controllers array
  80891. _this.controllers.push(webVrController_1);
  80892. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80893. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80894. // So we're overriding setting left & right manually to be sure
  80895. var firstViveWandDetected = false;
  80896. for (var i = 0; i < _this.controllers.length; i++) {
  80897. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80898. if (!firstViveWandDetected) {
  80899. firstViveWandDetected = true;
  80900. _this.controllers[i].hand = "left";
  80901. }
  80902. else {
  80903. _this.controllers[i].hand = "right";
  80904. }
  80905. }
  80906. }
  80907. //did we find enough controllers? Great! let the developer know.
  80908. if (_this.controllers.length >= 2) {
  80909. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80910. }
  80911. }
  80912. }
  80913. });
  80914. };
  80915. return WebVRFreeCamera;
  80916. }(BABYLON.FreeCamera));
  80917. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80918. })(BABYLON || (BABYLON = {}));
  80919. //# sourceMappingURL=babylon.webVRCamera.js.map
  80920. var BABYLON;
  80921. (function (BABYLON) {
  80922. // We're mainly based on the logic defined into the FreeCamera code
  80923. /**
  80924. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80925. * being tilted forward or back and left or right.
  80926. */
  80927. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80928. __extends(DeviceOrientationCamera, _super);
  80929. /**
  80930. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80931. * @param name The name of the camera
  80932. * @param position The start position camera
  80933. * @param scene The scene the camera belongs to
  80934. */
  80935. function DeviceOrientationCamera(name, position, scene) {
  80936. var _this = _super.call(this, name, position, scene) || this;
  80937. _this._quaternionCache = new BABYLON.Quaternion();
  80938. _this.inputs.addDeviceOrientation();
  80939. return _this;
  80940. }
  80941. /**
  80942. * Gets the current instance class name ("DeviceOrientationCamera").
  80943. * This helps avoiding instanceof at run time.
  80944. * @returns the class name
  80945. */
  80946. DeviceOrientationCamera.prototype.getClassName = function () {
  80947. return "DeviceOrientationCamera";
  80948. };
  80949. /**
  80950. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80951. */
  80952. DeviceOrientationCamera.prototype._checkInputs = function () {
  80953. _super.prototype._checkInputs.call(this);
  80954. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80955. if (this._initialQuaternion) {
  80956. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80957. }
  80958. };
  80959. /**
  80960. * Reset the camera to its default orientation on the specified axis only.
  80961. * @param axis The axis to reset
  80962. */
  80963. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80964. var _this = this;
  80965. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80966. //can only work if this camera has a rotation quaternion already.
  80967. if (!this.rotationQuaternion)
  80968. return;
  80969. if (!this._initialQuaternion) {
  80970. this._initialQuaternion = new BABYLON.Quaternion();
  80971. }
  80972. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80973. ['x', 'y', 'z'].forEach(function (axisName) {
  80974. if (!axis[axisName]) {
  80975. _this._initialQuaternion[axisName] = 0;
  80976. }
  80977. else {
  80978. _this._initialQuaternion[axisName] *= -1;
  80979. }
  80980. });
  80981. this._initialQuaternion.normalize();
  80982. //force rotation update
  80983. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80984. };
  80985. return DeviceOrientationCamera;
  80986. }(BABYLON.FreeCamera));
  80987. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80988. })(BABYLON || (BABYLON = {}));
  80989. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80990. var BABYLON;
  80991. (function (BABYLON) {
  80992. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80993. __extends(VRDeviceOrientationFreeCamera, _super);
  80994. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80995. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80996. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80997. var _this = _super.call(this, name, position, scene) || this;
  80998. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80999. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81000. return _this;
  81001. }
  81002. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81003. return "VRDeviceOrientationFreeCamera";
  81004. };
  81005. return VRDeviceOrientationFreeCamera;
  81006. }(BABYLON.DeviceOrientationCamera));
  81007. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81008. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81009. __extends(VRDeviceOrientationGamepadCamera, _super);
  81010. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81011. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81012. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81013. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81014. _this.inputs.addGamepad();
  81015. return _this;
  81016. }
  81017. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81018. return "VRDeviceOrientationGamepadCamera";
  81019. };
  81020. return VRDeviceOrientationGamepadCamera;
  81021. }(VRDeviceOrientationFreeCamera));
  81022. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81023. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81024. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81025. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81026. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81027. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81028. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81029. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81031. _this.inputs.addVRDeviceOrientation();
  81032. return _this;
  81033. }
  81034. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81035. return "VRDeviceOrientationArcRotateCamera";
  81036. };
  81037. return VRDeviceOrientationArcRotateCamera;
  81038. }(BABYLON.ArcRotateCamera));
  81039. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81040. })(BABYLON || (BABYLON = {}));
  81041. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81042. var BABYLON;
  81043. (function (BABYLON) {
  81044. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81045. __extends(AnaglyphFreeCamera, _super);
  81046. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81047. var _this = _super.call(this, name, position, scene) || this;
  81048. _this.interaxialDistance = interaxialDistance;
  81049. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81050. return _this;
  81051. }
  81052. AnaglyphFreeCamera.prototype.getClassName = function () {
  81053. return "AnaglyphFreeCamera";
  81054. };
  81055. return AnaglyphFreeCamera;
  81056. }(BABYLON.FreeCamera));
  81057. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81058. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81059. __extends(AnaglyphArcRotateCamera, _super);
  81060. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81061. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81062. _this.interaxialDistance = interaxialDistance;
  81063. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81064. return _this;
  81065. }
  81066. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81067. return "AnaglyphArcRotateCamera";
  81068. };
  81069. return AnaglyphArcRotateCamera;
  81070. }(BABYLON.ArcRotateCamera));
  81071. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81072. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81073. __extends(AnaglyphGamepadCamera, _super);
  81074. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81075. var _this = _super.call(this, name, position, scene) || this;
  81076. _this.interaxialDistance = interaxialDistance;
  81077. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81078. return _this;
  81079. }
  81080. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81081. return "AnaglyphGamepadCamera";
  81082. };
  81083. return AnaglyphGamepadCamera;
  81084. }(BABYLON.GamepadCamera));
  81085. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81086. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81087. __extends(AnaglyphUniversalCamera, _super);
  81088. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81089. var _this = _super.call(this, name, position, scene) || this;
  81090. _this.interaxialDistance = interaxialDistance;
  81091. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81092. return _this;
  81093. }
  81094. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81095. return "AnaglyphUniversalCamera";
  81096. };
  81097. return AnaglyphUniversalCamera;
  81098. }(BABYLON.UniversalCamera));
  81099. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81100. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81101. __extends(StereoscopicFreeCamera, _super);
  81102. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81103. var _this = _super.call(this, name, position, scene) || this;
  81104. _this.interaxialDistance = interaxialDistance;
  81105. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81106. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81107. return _this;
  81108. }
  81109. StereoscopicFreeCamera.prototype.getClassName = function () {
  81110. return "StereoscopicFreeCamera";
  81111. };
  81112. return StereoscopicFreeCamera;
  81113. }(BABYLON.FreeCamera));
  81114. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81115. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81116. __extends(StereoscopicArcRotateCamera, _super);
  81117. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81118. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81119. _this.interaxialDistance = interaxialDistance;
  81120. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81121. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81122. return _this;
  81123. }
  81124. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81125. return "StereoscopicArcRotateCamera";
  81126. };
  81127. return StereoscopicArcRotateCamera;
  81128. }(BABYLON.ArcRotateCamera));
  81129. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81130. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81131. __extends(StereoscopicGamepadCamera, _super);
  81132. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81133. var _this = _super.call(this, name, position, scene) || this;
  81134. _this.interaxialDistance = interaxialDistance;
  81135. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81136. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81137. return _this;
  81138. }
  81139. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81140. return "StereoscopicGamepadCamera";
  81141. };
  81142. return StereoscopicGamepadCamera;
  81143. }(BABYLON.GamepadCamera));
  81144. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81145. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81146. __extends(StereoscopicUniversalCamera, _super);
  81147. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81148. var _this = _super.call(this, name, position, scene) || this;
  81149. _this.interaxialDistance = interaxialDistance;
  81150. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81151. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81152. return _this;
  81153. }
  81154. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81155. return "StereoscopicUniversalCamera";
  81156. };
  81157. return StereoscopicUniversalCamera;
  81158. }(BABYLON.UniversalCamera));
  81159. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81160. })(BABYLON || (BABYLON = {}));
  81161. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81162. var BABYLON;
  81163. (function (BABYLON) {
  81164. var VRExperienceHelperGazer = /** @class */ (function () {
  81165. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81166. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81167. this.scene = scene;
  81168. this._pointerDownOnMeshAsked = false;
  81169. this._isActionableMesh = false;
  81170. this._teleportationRequestInitiated = false;
  81171. this._teleportationBackRequestInitiated = false;
  81172. this._dpadPressed = true;
  81173. this._activePointer = false;
  81174. this._id = VRExperienceHelperGazer._idCounter++;
  81175. // Gaze tracker
  81176. if (!gazeTrackerToClone) {
  81177. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81178. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81179. this._gazeTracker.isPickable = false;
  81180. this._gazeTracker.isVisible = false;
  81181. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81182. targetMat.specularColor = BABYLON.Color3.Black();
  81183. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81184. targetMat.backFaceCulling = false;
  81185. this._gazeTracker.material = targetMat;
  81186. }
  81187. else {
  81188. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81189. }
  81190. }
  81191. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81192. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81193. };
  81194. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81195. this._pointerDownOnMeshAsked = true;
  81196. if (this._currentMeshSelected && this._currentHit) {
  81197. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81198. }
  81199. };
  81200. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81201. if (this._currentMeshSelected && this._currentHit) {
  81202. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81203. }
  81204. this._pointerDownOnMeshAsked = false;
  81205. };
  81206. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81207. this._activePointer = true;
  81208. };
  81209. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81210. this._activePointer = false;
  81211. };
  81212. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81213. };
  81214. VRExperienceHelperGazer.prototype.dispose = function () {
  81215. this._interactionsEnabled = false;
  81216. this._teleportationEnabled = false;
  81217. };
  81218. VRExperienceHelperGazer._idCounter = 0;
  81219. return VRExperienceHelperGazer;
  81220. }());
  81221. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81222. __extends(VRExperienceHelperControllerGazer, _super);
  81223. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81224. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81225. _this.webVRController = webVRController;
  81226. // Laser pointer
  81227. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81228. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81229. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81230. laserPointerMaterial.alpha = 0.6;
  81231. _this._laserPointer.material = laserPointerMaterial;
  81232. _this._laserPointer.rotation.x = Math.PI / 2;
  81233. _this._laserPointer.position.z = -0.5;
  81234. _this._laserPointer.isVisible = false;
  81235. if (!webVRController.mesh) {
  81236. // Create an empty mesh that is used prior to loading the high quality model
  81237. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81238. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81239. preloadPointerPose.rotation.x = -0.7;
  81240. preloadMesh.addChild(preloadPointerPose);
  81241. webVRController.attachToMesh(preloadMesh);
  81242. }
  81243. _this._setLaserPointerParent(webVRController.mesh);
  81244. return _this;
  81245. }
  81246. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81247. return this.webVRController.getForwardRay(length);
  81248. };
  81249. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81250. _super.prototype._activatePointer.call(this);
  81251. this._laserPointer.isVisible = true;
  81252. };
  81253. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81254. _super.prototype._deactivatePointer.call(this);
  81255. this._laserPointer.isVisible = false;
  81256. };
  81257. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81258. this._laserPointer.material.emissiveColor = color;
  81259. };
  81260. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81261. var makeNotPick = function (root) {
  81262. root.name += " laserPointer";
  81263. root.getChildMeshes().forEach(function (c) {
  81264. makeNotPick(c);
  81265. });
  81266. };
  81267. makeNotPick(mesh);
  81268. var childMeshes = mesh.getChildMeshes();
  81269. this.webVRController._pointingPoseNode = null;
  81270. for (var i = 0; i < childMeshes.length; i++) {
  81271. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81272. mesh = childMeshes[i];
  81273. this.webVRController._pointingPoseNode = mesh;
  81274. break;
  81275. }
  81276. }
  81277. this._laserPointer.parent = mesh;
  81278. };
  81279. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81280. this._laserPointer.scaling.y = distance;
  81281. this._laserPointer.position.z = -distance / 2;
  81282. };
  81283. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81284. _super.prototype.dispose.call(this);
  81285. this._laserPointer.dispose();
  81286. };
  81287. return VRExperienceHelperControllerGazer;
  81288. }(VRExperienceHelperGazer));
  81289. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81290. __extends(VRExperienceHelperCameraGazer, _super);
  81291. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81292. var _this = _super.call(this, scene) || this;
  81293. _this.getCamera = getCamera;
  81294. return _this;
  81295. }
  81296. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81297. var camera = this.getCamera();
  81298. if (camera) {
  81299. return camera.getForwardRay(length);
  81300. }
  81301. else {
  81302. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81303. }
  81304. };
  81305. return VRExperienceHelperCameraGazer;
  81306. }(VRExperienceHelperGazer));
  81307. /**
  81308. * Helps to quickly add VR support to an existing scene.
  81309. * See http://doc.babylonjs.com/how_to/webvr_helper
  81310. */
  81311. var VRExperienceHelper = /** @class */ (function () {
  81312. /**
  81313. * Instantiates a VRExperienceHelper.
  81314. * Helps to quickly add VR support to an existing scene.
  81315. * @param scene The scene the VRExperienceHelper belongs to.
  81316. * @param webVROptions Options to modify the vr experience helper's behavior.
  81317. */
  81318. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81319. if (webVROptions === void 0) { webVROptions = {}; }
  81320. var _this = this;
  81321. this.webVROptions = webVROptions;
  81322. // Can the system support WebVR, even if a headset isn't plugged in?
  81323. this._webVRsupported = false;
  81324. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81325. this._webVRready = false;
  81326. // Are we waiting for the requestPresent callback to complete?
  81327. this._webVRrequesting = false;
  81328. // Are we presenting to the headset right now?
  81329. this._webVRpresenting = false;
  81330. // Are we presenting in the fullscreen fallback?
  81331. this._fullscreenVRpresenting = false;
  81332. /**
  81333. * Observable raised when entering VR.
  81334. */
  81335. this.onEnteringVRObservable = new BABYLON.Observable();
  81336. /**
  81337. * Observable raised when exiting VR.
  81338. */
  81339. this.onExitingVRObservable = new BABYLON.Observable();
  81340. /**
  81341. * Observable raised when controller mesh is loaded.
  81342. */
  81343. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81344. this._useCustomVRButton = false;
  81345. this._teleportationRequested = false;
  81346. this._teleportActive = false;
  81347. this._floorMeshesCollection = [];
  81348. this._rotationAllowed = true;
  81349. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81350. this._rotationRightAsked = false;
  81351. this._rotationLeftAsked = false;
  81352. this._isDefaultTeleportationTarget = true;
  81353. this._teleportationFillColor = "#444444";
  81354. this._teleportationBorderColor = "#FFFFFF";
  81355. this._rotationAngle = 0;
  81356. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81357. this._padSensibilityUp = 0.65;
  81358. this._padSensibilityDown = 0.35;
  81359. this.leftController = null;
  81360. this.rightController = null;
  81361. /**
  81362. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81363. */
  81364. this.onNewMeshSelected = new BABYLON.Observable();
  81365. /**
  81366. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81367. */
  81368. this.onNewMeshPicked = new BABYLON.Observable();
  81369. /**
  81370. * Observable raised before camera teleportation
  81371. */
  81372. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81373. /**
  81374. * Observable raised after camera teleportation
  81375. */
  81376. this.onAfterCameraTeleport = new BABYLON.Observable();
  81377. /**
  81378. * Observable raised when current selected mesh gets unselected
  81379. */
  81380. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81381. /**
  81382. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81383. */
  81384. this.teleportationEnabled = true;
  81385. this._teleportationInitialized = false;
  81386. this._interactionsEnabled = false;
  81387. this._interactionsRequested = false;
  81388. this._displayGaze = true;
  81389. this._displayLaserPointer = true;
  81390. this._onResize = function () {
  81391. _this.moveButtonToBottomRight();
  81392. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81393. _this.exitVR();
  81394. }
  81395. };
  81396. this._onFullscreenChange = function () {
  81397. if (document.fullscreen !== undefined) {
  81398. _this._fullscreenVRpresenting = document.fullscreen;
  81399. }
  81400. else if (document.mozFullScreen !== undefined) {
  81401. _this._fullscreenVRpresenting = document.mozFullScreen;
  81402. }
  81403. else if (document.webkitIsFullScreen !== undefined) {
  81404. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81405. }
  81406. else if (document.msIsFullScreen !== undefined) {
  81407. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81408. }
  81409. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81410. _this.exitVR();
  81411. if (!_this._useCustomVRButton) {
  81412. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81413. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81414. }
  81415. }
  81416. };
  81417. this.beforeRender = function () {
  81418. if (_this.leftController && _this.leftController._activePointer) {
  81419. _this._castRayAndSelectObject(_this.leftController);
  81420. }
  81421. if (_this.rightController && _this.rightController._activePointer) {
  81422. _this._castRayAndSelectObject(_this.rightController);
  81423. }
  81424. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81425. _this._castRayAndSelectObject(_this._cameraGazer);
  81426. }
  81427. else {
  81428. _this._cameraGazer._gazeTracker.isVisible = false;
  81429. }
  81430. };
  81431. this._onNewGamepadConnected = function (gamepad) {
  81432. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81433. if (gamepad.leftStick) {
  81434. gamepad.onleftstickchanged(function (stickValues) {
  81435. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81436. // Listening to classic/xbox gamepad only if no VR controller is active
  81437. if ((!_this.leftController && !_this.rightController) ||
  81438. ((_this.leftController && !_this.leftController._activePointer) &&
  81439. (_this.rightController && !_this.rightController._activePointer))) {
  81440. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81441. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81442. }
  81443. }
  81444. });
  81445. }
  81446. if (gamepad.rightStick) {
  81447. gamepad.onrightstickchanged(function (stickValues) {
  81448. if (_this._teleportationInitialized) {
  81449. _this._checkRotate(stickValues, _this._cameraGazer);
  81450. }
  81451. });
  81452. }
  81453. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81454. gamepad.onbuttondown(function (buttonPressed) {
  81455. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81456. _this._cameraGazer._selectionPointerDown();
  81457. }
  81458. });
  81459. gamepad.onbuttonup(function (buttonPressed) {
  81460. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81461. _this._cameraGazer._selectionPointerUp();
  81462. }
  81463. });
  81464. }
  81465. }
  81466. else {
  81467. var webVRController = gamepad;
  81468. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81469. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81470. _this.rightController = controller;
  81471. }
  81472. else {
  81473. _this.leftController = controller;
  81474. }
  81475. _this._tryEnableInteractionOnController(controller);
  81476. }
  81477. };
  81478. // 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
  81479. this._tryEnableInteractionOnController = function (controller) {
  81480. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81481. _this._enableInteractionOnController(controller);
  81482. }
  81483. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81484. _this._enableTeleportationOnController(controller);
  81485. }
  81486. };
  81487. this._onNewGamepadDisconnected = function (gamepad) {
  81488. if (gamepad instanceof BABYLON.WebVRController) {
  81489. if (gamepad.hand === "left" && _this.leftController != null) {
  81490. _this.leftController.dispose();
  81491. _this.leftController = null;
  81492. }
  81493. if (gamepad.hand === "right" && _this.rightController != null) {
  81494. _this.rightController.dispose();
  81495. _this.rightController = null;
  81496. }
  81497. }
  81498. };
  81499. this._workingVector = BABYLON.Vector3.Zero();
  81500. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81501. this._workingMatrix = BABYLON.Matrix.Identity();
  81502. this._scene = scene;
  81503. this._canvas = scene.getEngine().getRenderingCanvas();
  81504. // Parse options
  81505. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81506. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81507. }
  81508. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81509. webVROptions.createDeviceOrientationCamera = true;
  81510. }
  81511. if (webVROptions.defaultHeight === undefined) {
  81512. webVROptions.defaultHeight = 1.7;
  81513. }
  81514. if (webVROptions.useCustomVRButton) {
  81515. this._useCustomVRButton = true;
  81516. if (webVROptions.customVRButton) {
  81517. this._btnVR = webVROptions.customVRButton;
  81518. }
  81519. }
  81520. if (webVROptions.rayLength) {
  81521. this._rayLength = webVROptions.rayLength;
  81522. }
  81523. this._defaultHeight = webVROptions.defaultHeight;
  81524. if (webVROptions.positionScale) {
  81525. this._rayLength *= webVROptions.positionScale;
  81526. this._defaultHeight *= webVROptions.positionScale;
  81527. }
  81528. // Set position
  81529. if (this._scene.activeCamera) {
  81530. this._position = this._scene.activeCamera.position.clone();
  81531. }
  81532. else {
  81533. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81534. }
  81535. // Set non-vr camera
  81536. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81537. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81538. // Copy data from existing camera
  81539. if (this._scene.activeCamera) {
  81540. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81541. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81542. // Set rotation from previous camera
  81543. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81544. var targetCamera = this._scene.activeCamera;
  81545. if (targetCamera.rotationQuaternion) {
  81546. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81547. }
  81548. else {
  81549. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81550. }
  81551. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81552. }
  81553. }
  81554. this._scene.activeCamera = this._deviceOrientationCamera;
  81555. if (this._canvas) {
  81556. this._scene.activeCamera.attachControl(this._canvas);
  81557. }
  81558. }
  81559. else {
  81560. this._existingCamera = this._scene.activeCamera;
  81561. }
  81562. // Create VR cameras
  81563. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81564. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81565. }
  81566. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81567. this._webVRCamera.useStandingMatrix();
  81568. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81569. // Create default button
  81570. if (!this._useCustomVRButton) {
  81571. this._btnVR = document.createElement("BUTTON");
  81572. this._btnVR.className = "babylonVRicon";
  81573. this._btnVR.id = "babylonVRiconbtn";
  81574. this._btnVR.title = "Click to switch to VR";
  81575. 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) }";
  81576. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81577. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81578. // css += ".babylonVRicon.vrdisplaysupported { }";
  81579. // css += ".babylonVRicon.vrdisplayready { }";
  81580. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81581. var style = document.createElement('style');
  81582. style.appendChild(document.createTextNode(css));
  81583. document.getElementsByTagName('head')[0].appendChild(style);
  81584. this.moveButtonToBottomRight();
  81585. }
  81586. // VR button click event
  81587. if (this._btnVR) {
  81588. this._btnVR.addEventListener("click", function () {
  81589. if (!_this.isInVRMode) {
  81590. _this.enterVR();
  81591. }
  81592. else {
  81593. _this.exitVR();
  81594. }
  81595. });
  81596. }
  81597. // Window events
  81598. window.addEventListener("resize", this._onResize);
  81599. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81600. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81601. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81602. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81603. // Display vr button when headset is connected
  81604. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81605. this.displayVRButton();
  81606. }
  81607. else {
  81608. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81609. if (e.vrDisplay) {
  81610. _this.displayVRButton();
  81611. }
  81612. });
  81613. }
  81614. // Exiting VR mode using 'ESC' key on desktop
  81615. this._onKeyDown = function (event) {
  81616. if (event.keyCode === 27 && _this.isInVRMode) {
  81617. _this.exitVR();
  81618. }
  81619. };
  81620. document.addEventListener("keydown", this._onKeyDown);
  81621. // Exiting VR mode double tapping the touch screen
  81622. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81623. if (_this.isInVRMode) {
  81624. _this.exitVR();
  81625. if (_this._fullscreenVRpresenting) {
  81626. _this._scene.getEngine().switchFullscreen(true);
  81627. }
  81628. }
  81629. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81630. // Listen for WebVR display changes
  81631. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81632. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81633. this._onVRRequestPresentStart = function () {
  81634. _this._webVRrequesting = true;
  81635. _this.updateButtonVisibility();
  81636. };
  81637. this._onVRRequestPresentComplete = function (success) {
  81638. _this._webVRrequesting = false;
  81639. _this.updateButtonVisibility();
  81640. };
  81641. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81642. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81643. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81644. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81645. scene.onDisposeObservable.add(function () {
  81646. _this.dispose();
  81647. });
  81648. // Gamepad connection events
  81649. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81650. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81651. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81652. this.updateButtonVisibility();
  81653. //create easing functions
  81654. this._circleEase = new BABYLON.CircleEase();
  81655. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81656. }
  81657. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81658. /** Return this.onEnteringVRObservable
  81659. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81660. */
  81661. get: function () {
  81662. return this.onEnteringVRObservable;
  81663. },
  81664. enumerable: true,
  81665. configurable: true
  81666. });
  81667. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81668. /** Return this.onExitingVRObservable
  81669. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81670. */
  81671. get: function () {
  81672. return this.onExitingVRObservable;
  81673. },
  81674. enumerable: true,
  81675. configurable: true
  81676. });
  81677. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81678. /** Return this.onControllerMeshLoadedObservable
  81679. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81680. */
  81681. get: function () {
  81682. return this.onControllerMeshLoadedObservable;
  81683. },
  81684. enumerable: true,
  81685. configurable: true
  81686. });
  81687. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81688. /**
  81689. * The mesh used to display where the user is going to teleport.
  81690. */
  81691. get: function () {
  81692. return this._teleportationTarget;
  81693. },
  81694. /**
  81695. * Sets the mesh to be used to display where the user is going to teleport.
  81696. */
  81697. set: function (value) {
  81698. if (value) {
  81699. value.name = "teleportationTarget";
  81700. this._isDefaultTeleportationTarget = false;
  81701. this._teleportationTarget = value;
  81702. }
  81703. },
  81704. enumerable: true,
  81705. configurable: true
  81706. });
  81707. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81708. /**
  81709. * The mesh used to display where the user is selecting,
  81710. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81711. * See http://doc.babylonjs.com/resources/baking_transformations
  81712. */
  81713. get: function () {
  81714. return this._cameraGazer._gazeTracker;
  81715. },
  81716. set: function (value) {
  81717. if (value) {
  81718. this._cameraGazer._gazeTracker = value;
  81719. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81720. this._cameraGazer._gazeTracker.isPickable = false;
  81721. this._cameraGazer._gazeTracker.isVisible = false;
  81722. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81723. if (this.leftController) {
  81724. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81725. }
  81726. if (this.rightController) {
  81727. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81728. }
  81729. }
  81730. },
  81731. enumerable: true,
  81732. configurable: true
  81733. });
  81734. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81735. /**
  81736. * If the ray of the gaze should be displayed.
  81737. */
  81738. get: function () {
  81739. return this._displayGaze;
  81740. },
  81741. /**
  81742. * Sets if the ray of the gaze should be displayed.
  81743. */
  81744. set: function (value) {
  81745. this._displayGaze = value;
  81746. if (!value) {
  81747. this._cameraGazer._gazeTracker.isVisible = false;
  81748. if (this.leftController) {
  81749. this.leftController._gazeTracker.isVisible = false;
  81750. }
  81751. if (this.rightController) {
  81752. this.rightController._gazeTracker.isVisible = false;
  81753. }
  81754. }
  81755. },
  81756. enumerable: true,
  81757. configurable: true
  81758. });
  81759. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81760. /**
  81761. * If the ray of the LaserPointer should be displayed.
  81762. */
  81763. get: function () {
  81764. return this._displayLaserPointer;
  81765. },
  81766. /**
  81767. * Sets if the ray of the LaserPointer should be displayed.
  81768. */
  81769. set: function (value) {
  81770. this._displayLaserPointer = value;
  81771. if (!value) {
  81772. if (this.rightController) {
  81773. this.rightController._deactivatePointer();
  81774. this.rightController._gazeTracker.isVisible = false;
  81775. }
  81776. if (this.leftController) {
  81777. this.leftController._deactivatePointer();
  81778. this.leftController._gazeTracker.isVisible = false;
  81779. }
  81780. }
  81781. else {
  81782. if (this.rightController) {
  81783. this.rightController._activatePointer();
  81784. }
  81785. else if (this.leftController) {
  81786. this.leftController._activatePointer();
  81787. }
  81788. }
  81789. },
  81790. enumerable: true,
  81791. configurable: true
  81792. });
  81793. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81794. /**
  81795. * The deviceOrientationCamera used as the camera when not in VR.
  81796. */
  81797. get: function () {
  81798. return this._deviceOrientationCamera;
  81799. },
  81800. enumerable: true,
  81801. configurable: true
  81802. });
  81803. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81804. /**
  81805. * Based on the current WebVR support, returns the current VR camera used.
  81806. */
  81807. get: function () {
  81808. if (this._webVRready) {
  81809. return this._webVRCamera;
  81810. }
  81811. else {
  81812. return this._scene.activeCamera;
  81813. }
  81814. },
  81815. enumerable: true,
  81816. configurable: true
  81817. });
  81818. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81819. /**
  81820. * The webVRCamera which is used when in VR.
  81821. */
  81822. get: function () {
  81823. return this._webVRCamera;
  81824. },
  81825. enumerable: true,
  81826. configurable: true
  81827. });
  81828. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81829. /**
  81830. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81831. */
  81832. get: function () {
  81833. return this._vrDeviceOrientationCamera;
  81834. },
  81835. enumerable: true,
  81836. configurable: true
  81837. });
  81838. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81839. get: function () {
  81840. var result = this._cameraGazer._teleportationRequestInitiated
  81841. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81842. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81843. return result;
  81844. },
  81845. enumerable: true,
  81846. configurable: true
  81847. });
  81848. // Raised when one of the controller has loaded successfully its associated default mesh
  81849. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81850. if (this.leftController && this.leftController.webVRController == webVRController) {
  81851. if (webVRController.mesh) {
  81852. this.leftController._setLaserPointerParent(webVRController.mesh);
  81853. }
  81854. }
  81855. if (this.rightController && this.rightController.webVRController == webVRController) {
  81856. if (webVRController.mesh) {
  81857. this.rightController._setLaserPointerParent(webVRController.mesh);
  81858. }
  81859. }
  81860. try {
  81861. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81862. }
  81863. catch (err) {
  81864. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81865. }
  81866. };
  81867. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81868. /**
  81869. * Gets a value indicating if we are currently in VR mode.
  81870. */
  81871. get: function () {
  81872. return this._webVRpresenting || this._fullscreenVRpresenting;
  81873. },
  81874. enumerable: true,
  81875. configurable: true
  81876. });
  81877. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81878. var vrDisplay = this._scene.getEngine().getVRDevice();
  81879. if (vrDisplay) {
  81880. var wasPresenting = this._webVRpresenting;
  81881. // A VR display is connected
  81882. this._webVRpresenting = vrDisplay.isPresenting;
  81883. if (wasPresenting && !this._webVRpresenting)
  81884. this.exitVR();
  81885. }
  81886. else {
  81887. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81888. }
  81889. this.updateButtonVisibility();
  81890. };
  81891. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81892. this._webVRsupported = eventArgs.vrSupported;
  81893. this._webVRready = !!eventArgs.vrDisplay;
  81894. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81895. this.updateButtonVisibility();
  81896. };
  81897. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81898. if (this._canvas && !this._useCustomVRButton) {
  81899. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81900. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81901. }
  81902. };
  81903. VRExperienceHelper.prototype.displayVRButton = function () {
  81904. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81905. document.body.appendChild(this._btnVR);
  81906. this._btnVRDisplayed = true;
  81907. }
  81908. };
  81909. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81910. if (!this._btnVR || this._useCustomVRButton) {
  81911. return;
  81912. }
  81913. this._btnVR.className = "babylonVRicon";
  81914. if (this.isInVRMode) {
  81915. this._btnVR.className += " vrdisplaypresenting";
  81916. }
  81917. else {
  81918. if (this._webVRready)
  81919. this._btnVR.className += " vrdisplayready";
  81920. if (this._webVRsupported)
  81921. this._btnVR.className += " vrdisplaysupported";
  81922. if (this._webVRrequesting)
  81923. this._btnVR.className += " vrdisplayrequesting";
  81924. }
  81925. };
  81926. /**
  81927. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81928. * Otherwise, will use the fullscreen API.
  81929. */
  81930. VRExperienceHelper.prototype.enterVR = function () {
  81931. if (this.onEnteringVRObservable) {
  81932. try {
  81933. this.onEnteringVRObservable.notifyObservers(this);
  81934. }
  81935. catch (err) {
  81936. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81937. }
  81938. }
  81939. if (this._scene.activeCamera) {
  81940. this._position = this._scene.activeCamera.position.clone();
  81941. // make sure that we return to the last active camera
  81942. this._existingCamera = this._scene.activeCamera;
  81943. }
  81944. if (this._webVRrequesting)
  81945. return;
  81946. // If WebVR is supported and a headset is connected
  81947. if (this._webVRready) {
  81948. if (!this._webVRpresenting) {
  81949. this._webVRCamera.position = this._position;
  81950. this._scene.activeCamera = this._webVRCamera;
  81951. }
  81952. }
  81953. else if (this._vrDeviceOrientationCamera) {
  81954. this._vrDeviceOrientationCamera.position = this._position;
  81955. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81956. this._scene.getEngine().switchFullscreen(true);
  81957. this.updateButtonVisibility();
  81958. }
  81959. if (this._scene.activeCamera && this._canvas) {
  81960. this._scene.activeCamera.attachControl(this._canvas);
  81961. }
  81962. if (this._interactionsEnabled) {
  81963. this._scene.registerBeforeRender(this.beforeRender);
  81964. }
  81965. };
  81966. /**
  81967. * Attempt to exit VR, or fullscreen.
  81968. */
  81969. VRExperienceHelper.prototype.exitVR = function () {
  81970. if (this.onExitingVRObservable) {
  81971. try {
  81972. this.onExitingVRObservable.notifyObservers(this);
  81973. }
  81974. catch (err) {
  81975. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81976. }
  81977. }
  81978. if (this._webVRpresenting) {
  81979. this._scene.getEngine().disableVR();
  81980. }
  81981. if (this._scene.activeCamera) {
  81982. this._position = this._scene.activeCamera.position.clone();
  81983. }
  81984. if (this._deviceOrientationCamera) {
  81985. this._deviceOrientationCamera.position = this._position;
  81986. this._scene.activeCamera = this._deviceOrientationCamera;
  81987. if (this._canvas) {
  81988. this._scene.activeCamera.attachControl(this._canvas);
  81989. }
  81990. }
  81991. else if (this._existingCamera) {
  81992. this._existingCamera.position = this._position;
  81993. this._scene.activeCamera = this._existingCamera;
  81994. }
  81995. this.updateButtonVisibility();
  81996. if (this._interactionsEnabled) {
  81997. this._scene.unregisterBeforeRender(this.beforeRender);
  81998. }
  81999. };
  82000. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82001. /**
  82002. * The position of the vr experience helper.
  82003. */
  82004. get: function () {
  82005. return this._position;
  82006. },
  82007. /**
  82008. * Sets the position of the vr experience helper.
  82009. */
  82010. set: function (value) {
  82011. this._position = value;
  82012. if (this._scene.activeCamera) {
  82013. this._scene.activeCamera.position = value;
  82014. }
  82015. },
  82016. enumerable: true,
  82017. configurable: true
  82018. });
  82019. /**
  82020. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82021. */
  82022. VRExperienceHelper.prototype.enableInteractions = function () {
  82023. var _this = this;
  82024. if (!this._interactionsEnabled) {
  82025. this._interactionsRequested = true;
  82026. if (this.leftController) {
  82027. this._enableInteractionOnController(this.leftController);
  82028. }
  82029. if (this.rightController) {
  82030. this._enableInteractionOnController(this.rightController);
  82031. }
  82032. this.raySelectionPredicate = function (mesh) {
  82033. return mesh.isVisible;
  82034. };
  82035. this.meshSelectionPredicate = function (mesh) {
  82036. return true;
  82037. };
  82038. this._raySelectionPredicate = function (mesh) {
  82039. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82040. && mesh.name.indexOf("teleportationTarget") === -1
  82041. && mesh.name.indexOf("torusTeleportation") === -1
  82042. && mesh.name.indexOf("laserPointer") === -1)) {
  82043. return _this.raySelectionPredicate(mesh);
  82044. }
  82045. return false;
  82046. };
  82047. this._interactionsEnabled = true;
  82048. }
  82049. };
  82050. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82051. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82052. if (this._floorMeshesCollection[i].id === mesh.id) {
  82053. return true;
  82054. }
  82055. }
  82056. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82057. return true;
  82058. }
  82059. return false;
  82060. };
  82061. /**
  82062. * Adds a floor mesh to be used for teleportation.
  82063. * @param floorMesh the mesh to be used for teleportation.
  82064. */
  82065. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82066. if (!this._floorMeshesCollection) {
  82067. return;
  82068. }
  82069. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82070. return;
  82071. }
  82072. this._floorMeshesCollection.push(floorMesh);
  82073. };
  82074. /**
  82075. * Removes a floor mesh from being used for teleportation.
  82076. * @param floorMesh the mesh to be removed.
  82077. */
  82078. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82079. if (!this._floorMeshesCollection) {
  82080. return;
  82081. }
  82082. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82083. if (meshIndex !== -1) {
  82084. this._floorMeshesCollection.splice(meshIndex, 1);
  82085. }
  82086. };
  82087. /**
  82088. * Enables interactions and teleportation using the VR controllers and gaze.
  82089. * @param vrTeleportationOptions options to modify teleportation behavior.
  82090. */
  82091. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82092. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82093. if (!this._teleportationInitialized) {
  82094. this._teleportationRequested = true;
  82095. this.enableInteractions();
  82096. if (vrTeleportationOptions.floorMeshName) {
  82097. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82098. }
  82099. if (vrTeleportationOptions.floorMeshes) {
  82100. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82101. }
  82102. if (this.leftController != null) {
  82103. this._enableTeleportationOnController(this.leftController);
  82104. }
  82105. if (this.rightController != null) {
  82106. this._enableTeleportationOnController(this.rightController);
  82107. }
  82108. // Creates an image processing post process for the vignette not relying
  82109. // on the main scene configuration for image processing to reduce setup and spaces
  82110. // (gamma/linear) conflicts.
  82111. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82112. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82113. imageProcessingConfiguration.vignetteEnabled = true;
  82114. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82115. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82116. this._teleportationInitialized = true;
  82117. if (this._isDefaultTeleportationTarget) {
  82118. this._createTeleportationCircles();
  82119. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82120. }
  82121. }
  82122. };
  82123. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82124. var _this = this;
  82125. var controllerMesh = controller.webVRController.mesh;
  82126. if (controllerMesh) {
  82127. controller._interactionsEnabled = true;
  82128. controller._activatePointer();
  82129. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82130. // Enabling / disabling laserPointer
  82131. if (_this._displayLaserPointer && stateObject.value === 1) {
  82132. if (controller._activePointer) {
  82133. controller._deactivatePointer();
  82134. }
  82135. else {
  82136. controller._activatePointer();
  82137. }
  82138. if (_this.displayGaze) {
  82139. controller._gazeTracker.isVisible = controller._activePointer;
  82140. }
  82141. }
  82142. });
  82143. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82144. if (!controller._pointerDownOnMeshAsked) {
  82145. if (stateObject.value > _this._padSensibilityUp) {
  82146. controller._selectionPointerDown();
  82147. }
  82148. }
  82149. else if (stateObject.value < _this._padSensibilityDown) {
  82150. controller._selectionPointerUp();
  82151. }
  82152. });
  82153. }
  82154. };
  82155. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82156. // Dont teleport if another gaze already requested teleportation
  82157. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82158. return;
  82159. }
  82160. if (!gazer._teleportationRequestInitiated) {
  82161. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82162. gazer._activatePointer();
  82163. gazer._teleportationRequestInitiated = true;
  82164. }
  82165. }
  82166. else {
  82167. // Listening to the proper controller values changes to confirm teleportation
  82168. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82169. if (this._teleportActive) {
  82170. this._teleportCamera(this._haloCenter);
  82171. }
  82172. gazer._teleportationRequestInitiated = false;
  82173. }
  82174. }
  82175. };
  82176. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82177. // Only rotate when user is not currently selecting a teleportation location
  82178. if (gazer._teleportationRequestInitiated) {
  82179. return;
  82180. }
  82181. if (!this._rotationLeftAsked) {
  82182. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82183. this._rotationLeftAsked = true;
  82184. if (this._rotationAllowed) {
  82185. this._rotateCamera(false);
  82186. }
  82187. }
  82188. }
  82189. else {
  82190. if (stateObject.x > -this._padSensibilityDown) {
  82191. this._rotationLeftAsked = false;
  82192. }
  82193. }
  82194. if (!this._rotationRightAsked) {
  82195. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82196. this._rotationRightAsked = true;
  82197. if (this._rotationAllowed) {
  82198. this._rotateCamera(true);
  82199. }
  82200. }
  82201. }
  82202. else {
  82203. if (stateObject.x < this._padSensibilityDown) {
  82204. this._rotationRightAsked = false;
  82205. }
  82206. }
  82207. };
  82208. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82209. // Only teleport backwards when user is not currently selecting a teleportation location
  82210. if (gazer._teleportationRequestInitiated) {
  82211. return;
  82212. }
  82213. // Teleport backwards
  82214. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82215. if (!gazer._teleportationBackRequestInitiated) {
  82216. if (!this.currentVRCamera) {
  82217. return;
  82218. }
  82219. // Get rotation and position of the current camera
  82220. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82221. var position = this.currentVRCamera.position;
  82222. // If the camera has device position, use that instead
  82223. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82224. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82225. position = this.currentVRCamera.devicePosition;
  82226. }
  82227. // Get matrix with only the y rotation of the device rotation
  82228. rotation.toEulerAnglesToRef(this._workingVector);
  82229. this._workingVector.z = 0;
  82230. this._workingVector.x = 0;
  82231. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82232. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82233. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82234. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82235. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82236. var ray = new BABYLON.Ray(position, this._workingVector);
  82237. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82238. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82239. this._teleportCamera(hit.pickedPoint);
  82240. }
  82241. gazer._teleportationBackRequestInitiated = true;
  82242. }
  82243. }
  82244. else {
  82245. gazer._teleportationBackRequestInitiated = false;
  82246. }
  82247. };
  82248. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82249. var _this = this;
  82250. var controllerMesh = controller.webVRController.mesh;
  82251. if (controllerMesh) {
  82252. if (!controller._interactionsEnabled) {
  82253. this._enableInteractionOnController(controller);
  82254. }
  82255. controller._interactionsEnabled = true;
  82256. controller._teleportationEnabled = true;
  82257. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82258. controller._dpadPressed = false;
  82259. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82260. controller._dpadPressed = stateObject.pressed;
  82261. if (!controller._dpadPressed) {
  82262. _this._rotationLeftAsked = false;
  82263. _this._rotationRightAsked = false;
  82264. controller._teleportationBackRequestInitiated = false;
  82265. }
  82266. });
  82267. }
  82268. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82269. if (_this.teleportationEnabled) {
  82270. _this._checkTeleportBackwards(stateObject, controller);
  82271. _this._checkTeleportWithRay(stateObject, controller);
  82272. }
  82273. _this._checkRotate(stateObject, controller);
  82274. });
  82275. }
  82276. };
  82277. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82278. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82279. this._teleportationTarget.isPickable = false;
  82280. var length = 512;
  82281. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82282. dynamicTexture.hasAlpha = true;
  82283. var context = dynamicTexture.getContext();
  82284. var centerX = length / 2;
  82285. var centerY = length / 2;
  82286. var radius = 200;
  82287. context.beginPath();
  82288. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82289. context.fillStyle = this._teleportationFillColor;
  82290. context.fill();
  82291. context.lineWidth = 10;
  82292. context.strokeStyle = this._teleportationBorderColor;
  82293. context.stroke();
  82294. context.closePath();
  82295. dynamicTexture.update();
  82296. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82297. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82298. this._teleportationTarget.material = teleportationCircleMaterial;
  82299. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82300. torus.isPickable = false;
  82301. torus.parent = this._teleportationTarget;
  82302. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82303. var keys = [];
  82304. keys.push({
  82305. frame: 0,
  82306. value: 0
  82307. });
  82308. keys.push({
  82309. frame: 30,
  82310. value: 0.4
  82311. });
  82312. keys.push({
  82313. frame: 60,
  82314. value: 0
  82315. });
  82316. animationInnerCircle.setKeys(keys);
  82317. var easingFunction = new BABYLON.SineEase();
  82318. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82319. animationInnerCircle.setEasingFunction(easingFunction);
  82320. torus.animations = [];
  82321. torus.animations.push(animationInnerCircle);
  82322. this._scene.beginAnimation(torus, 0, 60, true);
  82323. this._hideTeleportationTarget();
  82324. };
  82325. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82326. this._teleportActive = true;
  82327. if (this._teleportationInitialized) {
  82328. this._teleportationTarget.isVisible = true;
  82329. if (this._isDefaultTeleportationTarget) {
  82330. this._teleportationTarget.getChildren()[0].isVisible = true;
  82331. }
  82332. }
  82333. };
  82334. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82335. this._teleportActive = false;
  82336. if (this._teleportationInitialized) {
  82337. this._teleportationTarget.isVisible = false;
  82338. if (this._isDefaultTeleportationTarget) {
  82339. this._teleportationTarget.getChildren()[0].isVisible = false;
  82340. }
  82341. }
  82342. };
  82343. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82344. var _this = this;
  82345. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82346. return;
  82347. }
  82348. if (right) {
  82349. this._rotationAngle++;
  82350. }
  82351. else {
  82352. this._rotationAngle--;
  82353. }
  82354. this.currentVRCamera.animations = [];
  82355. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82356. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82357. var animationRotationKeys = [];
  82358. animationRotationKeys.push({
  82359. frame: 0,
  82360. value: this.currentVRCamera.rotationQuaternion
  82361. });
  82362. animationRotationKeys.push({
  82363. frame: 6,
  82364. value: target
  82365. });
  82366. animationRotation.setKeys(animationRotationKeys);
  82367. animationRotation.setEasingFunction(this._circleEase);
  82368. this.currentVRCamera.animations.push(animationRotation);
  82369. this._postProcessMove.animations = [];
  82370. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82371. var vignetteWeightKeys = [];
  82372. vignetteWeightKeys.push({
  82373. frame: 0,
  82374. value: 0
  82375. });
  82376. vignetteWeightKeys.push({
  82377. frame: 3,
  82378. value: 4
  82379. });
  82380. vignetteWeightKeys.push({
  82381. frame: 6,
  82382. value: 0
  82383. });
  82384. animationPP.setKeys(vignetteWeightKeys);
  82385. animationPP.setEasingFunction(this._circleEase);
  82386. this._postProcessMove.animations.push(animationPP);
  82387. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82388. var vignetteStretchKeys = [];
  82389. vignetteStretchKeys.push({
  82390. frame: 0,
  82391. value: 0
  82392. });
  82393. vignetteStretchKeys.push({
  82394. frame: 3,
  82395. value: 10
  82396. });
  82397. vignetteStretchKeys.push({
  82398. frame: 6,
  82399. value: 0
  82400. });
  82401. animationPP2.setKeys(vignetteStretchKeys);
  82402. animationPP2.setEasingFunction(this._circleEase);
  82403. this._postProcessMove.animations.push(animationPP2);
  82404. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82405. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82406. this._postProcessMove.samples = 4;
  82407. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82408. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82409. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82410. });
  82411. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82412. };
  82413. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82414. if (hit.pickedPoint) {
  82415. if (gazer._teleportationRequestInitiated) {
  82416. this._displayTeleportationTarget();
  82417. this._haloCenter.copyFrom(hit.pickedPoint);
  82418. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82419. }
  82420. var pickNormal = hit.getNormal(true, false);
  82421. if (pickNormal) {
  82422. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82423. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82424. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82425. }
  82426. this._teleportationTarget.position.y += 0.1;
  82427. }
  82428. };
  82429. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82430. var _this = this;
  82431. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82432. return;
  82433. }
  82434. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82435. // offset of the headset from the anchor.
  82436. if (this.webVRCamera.leftCamera) {
  82437. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82438. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82439. location.subtractToRef(this._workingVector, this._workingVector);
  82440. }
  82441. else {
  82442. this._workingVector.copyFrom(location);
  82443. }
  82444. // Add height to account for user's height offset
  82445. if (this.isInVRMode) {
  82446. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82447. }
  82448. else {
  82449. this._workingVector.y += this._defaultHeight;
  82450. }
  82451. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82452. // Create animation from the camera's position to the new location
  82453. this.currentVRCamera.animations = [];
  82454. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82455. var animationCameraTeleportationKeys = [{
  82456. frame: 0,
  82457. value: this.currentVRCamera.position
  82458. },
  82459. {
  82460. frame: 11,
  82461. value: this._workingVector
  82462. }
  82463. ];
  82464. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82465. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82466. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82467. this._postProcessMove.animations = [];
  82468. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82469. var vignetteWeightKeys = [];
  82470. vignetteWeightKeys.push({
  82471. frame: 0,
  82472. value: 0
  82473. });
  82474. vignetteWeightKeys.push({
  82475. frame: 5,
  82476. value: 8
  82477. });
  82478. vignetteWeightKeys.push({
  82479. frame: 11,
  82480. value: 0
  82481. });
  82482. animationPP.setKeys(vignetteWeightKeys);
  82483. this._postProcessMove.animations.push(animationPP);
  82484. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82485. var vignetteStretchKeys = [];
  82486. vignetteStretchKeys.push({
  82487. frame: 0,
  82488. value: 0
  82489. });
  82490. vignetteStretchKeys.push({
  82491. frame: 5,
  82492. value: 10
  82493. });
  82494. vignetteStretchKeys.push({
  82495. frame: 11,
  82496. value: 0
  82497. });
  82498. animationPP2.setKeys(vignetteStretchKeys);
  82499. this._postProcessMove.animations.push(animationPP2);
  82500. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82501. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82502. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82503. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82504. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82505. });
  82506. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82507. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82508. });
  82509. this._hideTeleportationTarget();
  82510. };
  82511. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82512. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82513. return;
  82514. }
  82515. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82516. // Moving the gazeTracker on the mesh face targetted
  82517. if (hit && hit.pickedPoint) {
  82518. if (this._displayGaze) {
  82519. var multiplier = 1;
  82520. gazer._gazeTracker.isVisible = true;
  82521. if (gazer._isActionableMesh) {
  82522. multiplier = 3;
  82523. }
  82524. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82525. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82526. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82527. var pickNormal = hit.getNormal();
  82528. // To avoid z-fighting
  82529. var deltaFighting = 0.002;
  82530. if (pickNormal) {
  82531. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82532. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82533. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82534. }
  82535. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82536. if (gazer._gazeTracker.position.x < 0) {
  82537. gazer._gazeTracker.position.x += deltaFighting;
  82538. }
  82539. else {
  82540. gazer._gazeTracker.position.x -= deltaFighting;
  82541. }
  82542. if (gazer._gazeTracker.position.y < 0) {
  82543. gazer._gazeTracker.position.y += deltaFighting;
  82544. }
  82545. else {
  82546. gazer._gazeTracker.position.y -= deltaFighting;
  82547. }
  82548. if (gazer._gazeTracker.position.z < 0) {
  82549. gazer._gazeTracker.position.z += deltaFighting;
  82550. }
  82551. else {
  82552. gazer._gazeTracker.position.z -= deltaFighting;
  82553. }
  82554. }
  82555. // Changing the size of the laser pointer based on the distance from the targetted point
  82556. gazer._updatePointerDistance(hit.distance);
  82557. }
  82558. else {
  82559. gazer._gazeTracker.isVisible = false;
  82560. }
  82561. if (hit && hit.pickedMesh) {
  82562. gazer._currentHit = hit;
  82563. if (gazer._pointerDownOnMeshAsked) {
  82564. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82565. }
  82566. // The object selected is the floor, we're in a teleportation scenario
  82567. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82568. // Moving the teleportation area to this targetted point
  82569. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82570. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82571. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82572. }
  82573. gazer._currentMeshSelected = null;
  82574. if (gazer._teleportationRequestInitiated) {
  82575. this._moveTeleportationSelectorTo(hit, gazer);
  82576. }
  82577. return;
  82578. }
  82579. // If not, we're in a selection scenario
  82580. //this._teleportationAllowed = false;
  82581. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82582. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82583. this.onNewMeshPicked.notifyObservers(hit);
  82584. gazer._currentMeshSelected = hit.pickedMesh;
  82585. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82586. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82587. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82588. gazer._isActionableMesh = true;
  82589. }
  82590. else {
  82591. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82592. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82593. gazer._isActionableMesh = false;
  82594. }
  82595. try {
  82596. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82597. }
  82598. catch (err) {
  82599. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82600. }
  82601. }
  82602. else {
  82603. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82604. gazer._currentMeshSelected = null;
  82605. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82606. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82607. }
  82608. }
  82609. }
  82610. else {
  82611. gazer._currentHit = null;
  82612. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82613. gazer._currentMeshSelected = null;
  82614. //this._teleportationAllowed = false;
  82615. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82616. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82617. }
  82618. };
  82619. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82620. if (mesh) {
  82621. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82622. }
  82623. };
  82624. /**
  82625. * Sets the color of the laser ray from the vr controllers.
  82626. * @param color new color for the ray.
  82627. */
  82628. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82629. if (this.leftController) {
  82630. this.leftController._setLaserPointerColor(color);
  82631. }
  82632. if (this.rightController) {
  82633. this.rightController._setLaserPointerColor(color);
  82634. }
  82635. };
  82636. /**
  82637. * Sets the color of the ray from the vr headsets gaze.
  82638. * @param color new color for the ray.
  82639. */
  82640. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82641. if (!this._cameraGazer._gazeTracker.material) {
  82642. return;
  82643. }
  82644. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82645. if (this.leftController) {
  82646. this.leftController._gazeTracker.material.emissiveColor = color;
  82647. }
  82648. if (this.rightController) {
  82649. this.rightController._gazeTracker.material.emissiveColor = color;
  82650. }
  82651. };
  82652. /**
  82653. * Exits VR and disposes of the vr experience helper
  82654. */
  82655. VRExperienceHelper.prototype.dispose = function () {
  82656. if (this.isInVRMode) {
  82657. this.exitVR();
  82658. }
  82659. if (this._postProcessMove) {
  82660. this._postProcessMove.dispose();
  82661. }
  82662. if (this._webVRCamera) {
  82663. this._webVRCamera.dispose();
  82664. }
  82665. if (this._vrDeviceOrientationCamera) {
  82666. this._vrDeviceOrientationCamera.dispose();
  82667. }
  82668. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82669. document.body.removeChild(this._btnVR);
  82670. }
  82671. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82672. this._deviceOrientationCamera.dispose();
  82673. }
  82674. if (this._cameraGazer) {
  82675. this._cameraGazer.dispose();
  82676. }
  82677. if (this.leftController) {
  82678. this.leftController.dispose();
  82679. }
  82680. if (this.rightController) {
  82681. this.rightController.dispose();
  82682. }
  82683. if (this._teleportationTarget) {
  82684. this._teleportationTarget.dispose();
  82685. }
  82686. this._floorMeshesCollection = [];
  82687. document.removeEventListener("keydown", this._onKeyDown);
  82688. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82689. window.removeEventListener("resize", this._onResize);
  82690. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82691. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82692. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82693. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82694. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82695. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82696. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82697. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82698. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82699. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82700. this._scene.unregisterBeforeRender(this.beforeRender);
  82701. };
  82702. /**
  82703. * Gets the name of the VRExperienceHelper class
  82704. * @returns "VRExperienceHelper"
  82705. */
  82706. VRExperienceHelper.prototype.getClassName = function () {
  82707. return "VRExperienceHelper";
  82708. };
  82709. return VRExperienceHelper;
  82710. }());
  82711. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82712. })(BABYLON || (BABYLON = {}));
  82713. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82714. // Mainly based on these 2 articles :
  82715. // 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
  82716. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82717. var BABYLON;
  82718. (function (BABYLON) {
  82719. var JoystickAxis;
  82720. (function (JoystickAxis) {
  82721. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82722. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82723. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82724. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82725. var VirtualJoystick = /** @class */ (function () {
  82726. function VirtualJoystick(leftJoystick) {
  82727. var _this = this;
  82728. if (leftJoystick) {
  82729. this._leftJoystick = true;
  82730. }
  82731. else {
  82732. this._leftJoystick = false;
  82733. }
  82734. VirtualJoystick._globalJoystickIndex++;
  82735. // By default left & right arrow keys are moving the X
  82736. // and up & down keys are moving the Y
  82737. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82738. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82739. this.reverseLeftRight = false;
  82740. this.reverseUpDown = false;
  82741. // collections of pointers
  82742. this._touches = new BABYLON.StringDictionary();
  82743. this.deltaPosition = BABYLON.Vector3.Zero();
  82744. this._joystickSensibility = 25;
  82745. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82746. this._onResize = function (evt) {
  82747. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82748. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82749. if (VirtualJoystick.vjCanvas) {
  82750. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82751. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82752. }
  82753. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82754. };
  82755. // injecting a canvas element on top of the canvas 3D game
  82756. if (!VirtualJoystick.vjCanvas) {
  82757. window.addEventListener("resize", this._onResize, false);
  82758. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82759. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82760. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82761. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82762. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82763. VirtualJoystick.vjCanvas.style.width = "100%";
  82764. VirtualJoystick.vjCanvas.style.height = "100%";
  82765. VirtualJoystick.vjCanvas.style.position = "absolute";
  82766. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82767. VirtualJoystick.vjCanvas.style.top = "0px";
  82768. VirtualJoystick.vjCanvas.style.left = "0px";
  82769. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82770. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82771. // Support for jQuery PEP polyfill
  82772. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82773. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82774. if (!context) {
  82775. throw new Error("Unable to create canvas for virtual joystick");
  82776. }
  82777. VirtualJoystick.vjCanvasContext = context;
  82778. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82779. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82780. document.body.appendChild(VirtualJoystick.vjCanvas);
  82781. }
  82782. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82783. this.pressed = false;
  82784. // default joystick color
  82785. this._joystickColor = "cyan";
  82786. this._joystickPointerID = -1;
  82787. // current joystick position
  82788. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82789. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82790. // origin joystick position
  82791. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82792. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82793. this._onPointerDownHandlerRef = function (evt) {
  82794. _this._onPointerDown(evt);
  82795. };
  82796. this._onPointerMoveHandlerRef = function (evt) {
  82797. _this._onPointerMove(evt);
  82798. };
  82799. this._onPointerUpHandlerRef = function (evt) {
  82800. _this._onPointerUp(evt);
  82801. };
  82802. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82803. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82804. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82805. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82806. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82807. evt.preventDefault(); // Disables system menu
  82808. }, false);
  82809. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82810. }
  82811. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82812. this._joystickSensibility = newJoystickSensibility;
  82813. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82814. };
  82815. VirtualJoystick.prototype._onPointerDown = function (e) {
  82816. var positionOnScreenCondition;
  82817. e.preventDefault();
  82818. if (this._leftJoystick === true) {
  82819. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82820. }
  82821. else {
  82822. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82823. }
  82824. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82825. // First contact will be dedicated to the virtual joystick
  82826. this._joystickPointerID = e.pointerId;
  82827. this._joystickPointerStartPos.x = e.clientX;
  82828. this._joystickPointerStartPos.y = e.clientY;
  82829. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82830. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82831. this._deltaJoystickVector.x = 0;
  82832. this._deltaJoystickVector.y = 0;
  82833. this.pressed = true;
  82834. this._touches.add(e.pointerId.toString(), e);
  82835. }
  82836. else {
  82837. // You can only trigger the action buttons with a joystick declared
  82838. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82839. this._action();
  82840. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82841. }
  82842. }
  82843. };
  82844. VirtualJoystick.prototype._onPointerMove = function (e) {
  82845. // If the current pointer is the one associated to the joystick (first touch contact)
  82846. if (this._joystickPointerID == e.pointerId) {
  82847. this._joystickPointerPos.x = e.clientX;
  82848. this._joystickPointerPos.y = e.clientY;
  82849. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82850. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82851. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82852. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82853. switch (this._axisTargetedByLeftAndRight) {
  82854. case JoystickAxis.X:
  82855. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82856. break;
  82857. case JoystickAxis.Y:
  82858. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82859. break;
  82860. case JoystickAxis.Z:
  82861. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82862. break;
  82863. }
  82864. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82865. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82866. switch (this._axisTargetedByUpAndDown) {
  82867. case JoystickAxis.X:
  82868. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82869. break;
  82870. case JoystickAxis.Y:
  82871. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82872. break;
  82873. case JoystickAxis.Z:
  82874. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82875. break;
  82876. }
  82877. }
  82878. else {
  82879. var data = this._touches.get(e.pointerId.toString());
  82880. if (data) {
  82881. data.x = e.clientX;
  82882. data.y = e.clientY;
  82883. }
  82884. }
  82885. };
  82886. VirtualJoystick.prototype._onPointerUp = function (e) {
  82887. if (this._joystickPointerID == e.pointerId) {
  82888. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82889. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82890. this._joystickPointerID = -1;
  82891. this.pressed = false;
  82892. }
  82893. else {
  82894. var touch = this._touches.get(e.pointerId.toString());
  82895. if (touch) {
  82896. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82897. }
  82898. }
  82899. this._deltaJoystickVector.x = 0;
  82900. this._deltaJoystickVector.y = 0;
  82901. this._touches.remove(e.pointerId.toString());
  82902. };
  82903. /**
  82904. * Change the color of the virtual joystick
  82905. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82906. */
  82907. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82908. this._joystickColor = newColor;
  82909. };
  82910. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82911. this._action = action;
  82912. };
  82913. // Define which axis you'd like to control for left & right
  82914. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82915. switch (axis) {
  82916. case JoystickAxis.X:
  82917. case JoystickAxis.Y:
  82918. case JoystickAxis.Z:
  82919. this._axisTargetedByLeftAndRight = axis;
  82920. break;
  82921. default:
  82922. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82923. break;
  82924. }
  82925. };
  82926. // Define which axis you'd like to control for up & down
  82927. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82928. switch (axis) {
  82929. case JoystickAxis.X:
  82930. case JoystickAxis.Y:
  82931. case JoystickAxis.Z:
  82932. this._axisTargetedByUpAndDown = axis;
  82933. break;
  82934. default:
  82935. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82936. break;
  82937. }
  82938. };
  82939. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82940. var _this = this;
  82941. if (this.pressed) {
  82942. this._touches.forEach(function (key, touch) {
  82943. if (touch.pointerId === _this._joystickPointerID) {
  82944. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82945. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82946. VirtualJoystick.vjCanvasContext.beginPath();
  82947. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82948. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82949. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82950. VirtualJoystick.vjCanvasContext.stroke();
  82951. VirtualJoystick.vjCanvasContext.closePath();
  82952. VirtualJoystick.vjCanvasContext.beginPath();
  82953. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82954. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82955. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82956. VirtualJoystick.vjCanvasContext.stroke();
  82957. VirtualJoystick.vjCanvasContext.closePath();
  82958. VirtualJoystick.vjCanvasContext.beginPath();
  82959. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82960. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82961. VirtualJoystick.vjCanvasContext.stroke();
  82962. VirtualJoystick.vjCanvasContext.closePath();
  82963. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82964. }
  82965. else {
  82966. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82967. VirtualJoystick.vjCanvasContext.beginPath();
  82968. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82969. VirtualJoystick.vjCanvasContext.beginPath();
  82970. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82971. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82972. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82973. VirtualJoystick.vjCanvasContext.stroke();
  82974. VirtualJoystick.vjCanvasContext.closePath();
  82975. touch.prevX = touch.x;
  82976. touch.prevY = touch.y;
  82977. }
  82978. ;
  82979. });
  82980. }
  82981. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82982. };
  82983. VirtualJoystick.prototype.releaseCanvas = function () {
  82984. if (VirtualJoystick.vjCanvas) {
  82985. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82986. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82987. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82988. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82989. window.removeEventListener("resize", this._onResize);
  82990. document.body.removeChild(VirtualJoystick.vjCanvas);
  82991. VirtualJoystick.vjCanvas = null;
  82992. }
  82993. };
  82994. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82995. VirtualJoystick._globalJoystickIndex = 0;
  82996. return VirtualJoystick;
  82997. }());
  82998. BABYLON.VirtualJoystick = VirtualJoystick;
  82999. })(BABYLON || (BABYLON = {}));
  83000. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83001. var BABYLON;
  83002. (function (BABYLON) {
  83003. // We're mainly based on the logic defined into the FreeCamera code
  83004. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83005. __extends(VirtualJoysticksCamera, _super);
  83006. function VirtualJoysticksCamera(name, position, scene) {
  83007. var _this = _super.call(this, name, position, scene) || this;
  83008. _this.inputs.addVirtualJoystick();
  83009. return _this;
  83010. }
  83011. VirtualJoysticksCamera.prototype.getClassName = function () {
  83012. return "VirtualJoysticksCamera";
  83013. };
  83014. return VirtualJoysticksCamera;
  83015. }(BABYLON.FreeCamera));
  83016. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83017. })(BABYLON || (BABYLON = {}));
  83018. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83019. var BABYLON;
  83020. (function (BABYLON) {
  83021. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83022. function FreeCameraVirtualJoystickInput() {
  83023. }
  83024. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83025. return this._leftjoystick;
  83026. };
  83027. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83028. return this._rightjoystick;
  83029. };
  83030. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83031. if (this._leftjoystick) {
  83032. var camera = this.camera;
  83033. var speed = camera._computeLocalCameraSpeed() * 50;
  83034. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83035. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83036. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83037. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83038. if (!this._leftjoystick.pressed) {
  83039. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83040. }
  83041. if (!this._rightjoystick.pressed) {
  83042. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83043. }
  83044. }
  83045. };
  83046. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83047. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83048. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83049. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83050. this._leftjoystick.setJoystickSensibility(0.15);
  83051. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83052. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83053. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83054. this._rightjoystick.reverseUpDown = true;
  83055. this._rightjoystick.setJoystickSensibility(0.05);
  83056. this._rightjoystick.setJoystickColor("yellow");
  83057. };
  83058. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83059. this._leftjoystick.releaseCanvas();
  83060. this._rightjoystick.releaseCanvas();
  83061. };
  83062. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83063. return "FreeCameraVirtualJoystickInput";
  83064. };
  83065. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83066. return "virtualJoystick";
  83067. };
  83068. return FreeCameraVirtualJoystickInput;
  83069. }());
  83070. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83071. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83072. })(BABYLON || (BABYLON = {}));
  83073. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83074. var BABYLON;
  83075. (function (BABYLON) {
  83076. var SimplificationSettings = /** @class */ (function () {
  83077. function SimplificationSettings(quality, distance, optimizeMesh) {
  83078. this.quality = quality;
  83079. this.distance = distance;
  83080. this.optimizeMesh = optimizeMesh;
  83081. }
  83082. return SimplificationSettings;
  83083. }());
  83084. BABYLON.SimplificationSettings = SimplificationSettings;
  83085. var SimplificationQueue = /** @class */ (function () {
  83086. function SimplificationQueue() {
  83087. this.running = false;
  83088. this._simplificationArray = [];
  83089. }
  83090. SimplificationQueue.prototype.addTask = function (task) {
  83091. this._simplificationArray.push(task);
  83092. };
  83093. SimplificationQueue.prototype.executeNext = function () {
  83094. var task = this._simplificationArray.pop();
  83095. if (task) {
  83096. this.running = true;
  83097. this.runSimplification(task);
  83098. }
  83099. else {
  83100. this.running = false;
  83101. }
  83102. };
  83103. SimplificationQueue.prototype.runSimplification = function (task) {
  83104. var _this = this;
  83105. if (task.parallelProcessing) {
  83106. //parallel simplifier
  83107. task.settings.forEach(function (setting) {
  83108. var simplifier = _this.getSimplifier(task);
  83109. simplifier.simplify(setting, function (newMesh) {
  83110. task.mesh.addLODLevel(setting.distance, newMesh);
  83111. newMesh.isVisible = true;
  83112. //check if it is the last
  83113. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83114. //all done, run the success callback.
  83115. task.successCallback();
  83116. }
  83117. _this.executeNext();
  83118. });
  83119. });
  83120. }
  83121. else {
  83122. //single simplifier.
  83123. var simplifier = this.getSimplifier(task);
  83124. var runDecimation = function (setting, callback) {
  83125. simplifier.simplify(setting, function (newMesh) {
  83126. task.mesh.addLODLevel(setting.distance, newMesh);
  83127. newMesh.isVisible = true;
  83128. //run the next quality level
  83129. callback();
  83130. });
  83131. };
  83132. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83133. runDecimation(task.settings[loop.index], function () {
  83134. loop.executeNext();
  83135. });
  83136. }, function () {
  83137. //execution ended, run the success callback.
  83138. if (task.successCallback) {
  83139. task.successCallback();
  83140. }
  83141. _this.executeNext();
  83142. });
  83143. }
  83144. };
  83145. SimplificationQueue.prototype.getSimplifier = function (task) {
  83146. switch (task.simplificationType) {
  83147. case SimplificationType.QUADRATIC:
  83148. default:
  83149. return new QuadraticErrorSimplification(task.mesh);
  83150. }
  83151. };
  83152. return SimplificationQueue;
  83153. }());
  83154. BABYLON.SimplificationQueue = SimplificationQueue;
  83155. /**
  83156. * The implemented types of simplification.
  83157. * At the moment only Quadratic Error Decimation is implemented.
  83158. */
  83159. var SimplificationType;
  83160. (function (SimplificationType) {
  83161. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83162. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83163. var DecimationTriangle = /** @class */ (function () {
  83164. function DecimationTriangle(vertices) {
  83165. this.vertices = vertices;
  83166. this.error = new Array(4);
  83167. this.deleted = false;
  83168. this.isDirty = false;
  83169. this.deletePending = false;
  83170. this.borderFactor = 0;
  83171. }
  83172. return DecimationTriangle;
  83173. }());
  83174. BABYLON.DecimationTriangle = DecimationTriangle;
  83175. var DecimationVertex = /** @class */ (function () {
  83176. function DecimationVertex(position, id) {
  83177. this.position = position;
  83178. this.id = id;
  83179. this.isBorder = true;
  83180. this.q = new QuadraticMatrix();
  83181. this.triangleCount = 0;
  83182. this.triangleStart = 0;
  83183. this.originalOffsets = [];
  83184. }
  83185. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83186. this.position.copyFrom(newPosition);
  83187. };
  83188. return DecimationVertex;
  83189. }());
  83190. BABYLON.DecimationVertex = DecimationVertex;
  83191. var QuadraticMatrix = /** @class */ (function () {
  83192. function QuadraticMatrix(data) {
  83193. this.data = new Array(10);
  83194. for (var i = 0; i < 10; ++i) {
  83195. if (data && data[i]) {
  83196. this.data[i] = data[i];
  83197. }
  83198. else {
  83199. this.data[i] = 0;
  83200. }
  83201. }
  83202. }
  83203. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83204. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83205. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83206. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83207. return det;
  83208. };
  83209. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83210. for (var i = 0; i < 10; ++i) {
  83211. this.data[i] += matrix.data[i];
  83212. }
  83213. };
  83214. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83215. for (var i = 0; i < 10; ++i) {
  83216. this.data[i] += data[i];
  83217. }
  83218. };
  83219. QuadraticMatrix.prototype.add = function (matrix) {
  83220. var m = new QuadraticMatrix();
  83221. for (var i = 0; i < 10; ++i) {
  83222. m.data[i] = this.data[i] + matrix.data[i];
  83223. }
  83224. return m;
  83225. };
  83226. QuadraticMatrix.FromData = function (a, b, c, d) {
  83227. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83228. };
  83229. //returning an array to avoid garbage collection
  83230. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83231. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83232. };
  83233. return QuadraticMatrix;
  83234. }());
  83235. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83236. var Reference = /** @class */ (function () {
  83237. function Reference(vertexId, triangleId) {
  83238. this.vertexId = vertexId;
  83239. this.triangleId = triangleId;
  83240. }
  83241. return Reference;
  83242. }());
  83243. BABYLON.Reference = Reference;
  83244. /**
  83245. * An implementation of the Quadratic Error simplification algorithm.
  83246. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83247. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83248. * @author RaananW
  83249. */
  83250. var QuadraticErrorSimplification = /** @class */ (function () {
  83251. function QuadraticErrorSimplification(_mesh) {
  83252. this._mesh = _mesh;
  83253. this.syncIterations = 5000;
  83254. this.aggressiveness = 7;
  83255. this.decimationIterations = 100;
  83256. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83257. }
  83258. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83259. var _this = this;
  83260. this.initDecimatedMesh();
  83261. //iterating through the submeshes array, one after the other.
  83262. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83263. _this.initWithMesh(loop.index, function () {
  83264. _this.runDecimation(settings, loop.index, function () {
  83265. loop.executeNext();
  83266. });
  83267. }, settings.optimizeMesh);
  83268. }, function () {
  83269. setTimeout(function () {
  83270. successCallback(_this._reconstructedMesh);
  83271. }, 0);
  83272. });
  83273. };
  83274. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83275. var _this = this;
  83276. var targetCount = ~~(this.triangles.length * settings.quality);
  83277. var deletedTriangles = 0;
  83278. var triangleCount = this.triangles.length;
  83279. var iterationFunction = function (iteration, callback) {
  83280. setTimeout(function () {
  83281. if (iteration % 5 === 0) {
  83282. _this.updateMesh(iteration === 0);
  83283. }
  83284. for (var i = 0; i < _this.triangles.length; ++i) {
  83285. _this.triangles[i].isDirty = false;
  83286. }
  83287. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83288. var trianglesIterator = function (i) {
  83289. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83290. var t = _this.triangles[tIdx];
  83291. if (!t)
  83292. return;
  83293. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83294. return;
  83295. }
  83296. for (var j = 0; j < 3; ++j) {
  83297. if (t.error[j] < threshold) {
  83298. var deleted0 = [];
  83299. var deleted1 = [];
  83300. var v0 = t.vertices[j];
  83301. var v1 = t.vertices[(j + 1) % 3];
  83302. if (v0.isBorder || v1.isBorder)
  83303. continue;
  83304. var p = BABYLON.Vector3.Zero();
  83305. var n = BABYLON.Vector3.Zero();
  83306. var uv = BABYLON.Vector2.Zero();
  83307. var color = new BABYLON.Color4(0, 0, 0, 1);
  83308. _this.calculateError(v0, v1, p, n, uv, color);
  83309. var delTr = new Array();
  83310. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83311. continue;
  83312. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83313. continue;
  83314. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83315. continue;
  83316. var uniqueArray = new Array();
  83317. delTr.forEach(function (deletedT) {
  83318. if (uniqueArray.indexOf(deletedT) === -1) {
  83319. deletedT.deletePending = true;
  83320. uniqueArray.push(deletedT);
  83321. }
  83322. });
  83323. if (uniqueArray.length % 2 !== 0) {
  83324. continue;
  83325. }
  83326. v0.q = v1.q.add(v0.q);
  83327. v0.updatePosition(p);
  83328. var tStart = _this.references.length;
  83329. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83330. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83331. var tCount = _this.references.length - tStart;
  83332. if (tCount <= v0.triangleCount) {
  83333. if (tCount) {
  83334. for (var c = 0; c < tCount; c++) {
  83335. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83336. }
  83337. }
  83338. }
  83339. else {
  83340. v0.triangleStart = tStart;
  83341. }
  83342. v0.triangleCount = tCount;
  83343. break;
  83344. }
  83345. }
  83346. };
  83347. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83348. }, 0);
  83349. };
  83350. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83351. if (triangleCount - deletedTriangles <= targetCount)
  83352. loop.breakLoop();
  83353. else {
  83354. iterationFunction(loop.index, function () {
  83355. loop.executeNext();
  83356. });
  83357. }
  83358. }, function () {
  83359. setTimeout(function () {
  83360. //reconstruct this part of the mesh
  83361. _this.reconstructMesh(submeshIndex);
  83362. successCallback();
  83363. }, 0);
  83364. });
  83365. };
  83366. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83367. var _this = this;
  83368. this.vertices = [];
  83369. this.triangles = [];
  83370. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83371. var indices = this._mesh.getIndices();
  83372. var submesh = this._mesh.subMeshes[submeshIndex];
  83373. var findInVertices = function (positionToSearch) {
  83374. if (optimizeMesh) {
  83375. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83376. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83377. return _this.vertices[ii];
  83378. }
  83379. }
  83380. }
  83381. return null;
  83382. };
  83383. var vertexReferences = [];
  83384. var vertexInit = function (i) {
  83385. if (!positionData) {
  83386. return;
  83387. }
  83388. var offset = i + submesh.verticesStart;
  83389. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83390. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83391. vertex.originalOffsets.push(offset);
  83392. if (vertex.id === _this.vertices.length) {
  83393. _this.vertices.push(vertex);
  83394. }
  83395. vertexReferences.push(vertex.id);
  83396. };
  83397. //var totalVertices = mesh.getTotalVertices();
  83398. var totalVertices = submesh.verticesCount;
  83399. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83400. var indicesInit = function (i) {
  83401. if (!indices) {
  83402. return;
  83403. }
  83404. var offset = (submesh.indexStart / 3) + i;
  83405. var pos = (offset * 3);
  83406. var i0 = indices[pos + 0];
  83407. var i1 = indices[pos + 1];
  83408. var i2 = indices[pos + 2];
  83409. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83410. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83411. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83412. var triangle = new DecimationTriangle([v0, v1, v2]);
  83413. triangle.originalOffset = pos;
  83414. _this.triangles.push(triangle);
  83415. };
  83416. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83417. _this.init(callback);
  83418. });
  83419. });
  83420. };
  83421. QuadraticErrorSimplification.prototype.init = function (callback) {
  83422. var _this = this;
  83423. var triangleInit1 = function (i) {
  83424. var t = _this.triangles[i];
  83425. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83426. for (var j = 0; j < 3; j++) {
  83427. 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))));
  83428. }
  83429. };
  83430. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83431. var triangleInit2 = function (i) {
  83432. var t = _this.triangles[i];
  83433. for (var j = 0; j < 3; ++j) {
  83434. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83435. }
  83436. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83437. };
  83438. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83439. callback();
  83440. });
  83441. });
  83442. };
  83443. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83444. var newTriangles = [];
  83445. var i;
  83446. for (i = 0; i < this.vertices.length; ++i) {
  83447. this.vertices[i].triangleCount = 0;
  83448. }
  83449. var t;
  83450. var j;
  83451. for (i = 0; i < this.triangles.length; ++i) {
  83452. if (!this.triangles[i].deleted) {
  83453. t = this.triangles[i];
  83454. for (j = 0; j < 3; ++j) {
  83455. t.vertices[j].triangleCount = 1;
  83456. }
  83457. newTriangles.push(t);
  83458. }
  83459. }
  83460. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83461. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83462. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83463. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83464. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83465. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83466. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83467. var vertexCount = 0;
  83468. for (i = 0; i < this.vertices.length; ++i) {
  83469. var vertex = this.vertices[i];
  83470. vertex.id = vertexCount;
  83471. if (vertex.triangleCount) {
  83472. vertex.originalOffsets.forEach(function (originalOffset) {
  83473. if (!normalData) {
  83474. return;
  83475. }
  83476. newPositionData.push(vertex.position.x);
  83477. newPositionData.push(vertex.position.y);
  83478. newPositionData.push(vertex.position.z);
  83479. newNormalData.push(normalData[originalOffset * 3]);
  83480. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83481. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83482. if (uvs && uvs.length) {
  83483. newUVsData.push(uvs[(originalOffset * 2)]);
  83484. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83485. }
  83486. else if (colorsData && colorsData.length) {
  83487. newColorsData.push(colorsData[(originalOffset * 4)]);
  83488. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83489. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83490. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83491. }
  83492. ++vertexCount;
  83493. });
  83494. }
  83495. }
  83496. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83497. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83498. var submeshesArray = this._reconstructedMesh.subMeshes;
  83499. this._reconstructedMesh.subMeshes = [];
  83500. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83501. var originalIndices = this._mesh.getIndices();
  83502. for (i = 0; i < newTriangles.length; ++i) {
  83503. t = newTriangles[i]; //now get the new referencing point for each vertex
  83504. [0, 1, 2].forEach(function (idx) {
  83505. var id = originalIndices[t.originalOffset + idx];
  83506. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83507. if (offset < 0)
  83508. offset = 0;
  83509. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83510. });
  83511. }
  83512. //overwriting the old vertex buffers and indices.
  83513. this._reconstructedMesh.setIndices(newIndicesArray);
  83514. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83515. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83516. if (newUVsData.length > 0)
  83517. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83518. if (newColorsData.length > 0)
  83519. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83520. //create submesh
  83521. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83522. if (submeshIndex > 0) {
  83523. this._reconstructedMesh.subMeshes = [];
  83524. submeshesArray.forEach(function (submesh) {
  83525. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83526. });
  83527. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83528. }
  83529. };
  83530. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83531. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83532. this._reconstructedMesh.material = this._mesh.material;
  83533. this._reconstructedMesh.parent = this._mesh.parent;
  83534. this._reconstructedMesh.isVisible = false;
  83535. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83536. };
  83537. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83538. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83539. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83540. if (t.deleted)
  83541. continue;
  83542. var s = this.references[vertex1.triangleStart + i].vertexId;
  83543. var v1 = t.vertices[(s + 1) % 3];
  83544. var v2 = t.vertices[(s + 2) % 3];
  83545. if ((v1 === vertex2 || v2 === vertex2)) {
  83546. deletedArray[i] = true;
  83547. delTr.push(t);
  83548. continue;
  83549. }
  83550. var d1 = v1.position.subtract(point);
  83551. d1 = d1.normalize();
  83552. var d2 = v2.position.subtract(point);
  83553. d2 = d2.normalize();
  83554. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83555. return true;
  83556. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83557. deletedArray[i] = false;
  83558. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83559. return true;
  83560. }
  83561. return false;
  83562. };
  83563. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83564. var newDeleted = deletedTriangles;
  83565. for (var i = 0; i < vertex.triangleCount; ++i) {
  83566. var ref = this.references[vertex.triangleStart + i];
  83567. var t = this.triangles[ref.triangleId];
  83568. if (t.deleted)
  83569. continue;
  83570. if (deletedArray[i] && t.deletePending) {
  83571. t.deleted = true;
  83572. newDeleted++;
  83573. continue;
  83574. }
  83575. t.vertices[ref.vertexId] = origVertex;
  83576. t.isDirty = true;
  83577. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83578. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83579. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83580. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83581. this.references.push(ref);
  83582. }
  83583. return newDeleted;
  83584. };
  83585. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83586. for (var i = 0; i < this.vertices.length; ++i) {
  83587. var vCount = [];
  83588. var vId = [];
  83589. var v = this.vertices[i];
  83590. var j;
  83591. for (j = 0; j < v.triangleCount; ++j) {
  83592. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83593. for (var ii = 0; ii < 3; ii++) {
  83594. var ofs = 0;
  83595. var vv = triangle.vertices[ii];
  83596. while (ofs < vCount.length) {
  83597. if (vId[ofs] === vv.id)
  83598. break;
  83599. ++ofs;
  83600. }
  83601. if (ofs === vCount.length) {
  83602. vCount.push(1);
  83603. vId.push(vv.id);
  83604. }
  83605. else {
  83606. vCount[ofs]++;
  83607. }
  83608. }
  83609. }
  83610. for (j = 0; j < vCount.length; ++j) {
  83611. if (vCount[j] === 1) {
  83612. this.vertices[vId[j]].isBorder = true;
  83613. }
  83614. else {
  83615. this.vertices[vId[j]].isBorder = false;
  83616. }
  83617. }
  83618. }
  83619. };
  83620. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83621. if (identifyBorders === void 0) { identifyBorders = false; }
  83622. var i;
  83623. if (!identifyBorders) {
  83624. var newTrianglesVector = [];
  83625. for (i = 0; i < this.triangles.length; ++i) {
  83626. if (!this.triangles[i].deleted) {
  83627. newTrianglesVector.push(this.triangles[i]);
  83628. }
  83629. }
  83630. this.triangles = newTrianglesVector;
  83631. }
  83632. for (i = 0; i < this.vertices.length; ++i) {
  83633. this.vertices[i].triangleCount = 0;
  83634. this.vertices[i].triangleStart = 0;
  83635. }
  83636. var t;
  83637. var j;
  83638. var v;
  83639. for (i = 0; i < this.triangles.length; ++i) {
  83640. t = this.triangles[i];
  83641. for (j = 0; j < 3; ++j) {
  83642. v = t.vertices[j];
  83643. v.triangleCount++;
  83644. }
  83645. }
  83646. var tStart = 0;
  83647. for (i = 0; i < this.vertices.length; ++i) {
  83648. this.vertices[i].triangleStart = tStart;
  83649. tStart += this.vertices[i].triangleCount;
  83650. this.vertices[i].triangleCount = 0;
  83651. }
  83652. var newReferences = new Array(this.triangles.length * 3);
  83653. for (i = 0; i < this.triangles.length; ++i) {
  83654. t = this.triangles[i];
  83655. for (j = 0; j < 3; ++j) {
  83656. v = t.vertices[j];
  83657. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83658. v.triangleCount++;
  83659. }
  83660. }
  83661. this.references = newReferences;
  83662. if (identifyBorders) {
  83663. this.identifyBorder();
  83664. }
  83665. };
  83666. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83667. var x = point.x;
  83668. var y = point.y;
  83669. var z = point.z;
  83670. 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
  83671. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83672. };
  83673. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83674. var q = vertex1.q.add(vertex2.q);
  83675. var border = vertex1.isBorder && vertex2.isBorder;
  83676. var error = 0;
  83677. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83678. if (qDet !== 0 && !border) {
  83679. if (!pointResult) {
  83680. pointResult = BABYLON.Vector3.Zero();
  83681. }
  83682. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83683. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83684. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83685. error = this.vertexError(q, pointResult);
  83686. }
  83687. else {
  83688. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83689. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83690. var error1 = this.vertexError(q, vertex1.position);
  83691. var error2 = this.vertexError(q, vertex2.position);
  83692. var error3 = this.vertexError(q, p3);
  83693. error = Math.min(error1, error2, error3);
  83694. if (error === error1) {
  83695. if (pointResult) {
  83696. pointResult.copyFrom(vertex1.position);
  83697. }
  83698. }
  83699. else if (error === error2) {
  83700. if (pointResult) {
  83701. pointResult.copyFrom(vertex2.position);
  83702. }
  83703. }
  83704. else {
  83705. if (pointResult) {
  83706. pointResult.copyFrom(p3);
  83707. }
  83708. }
  83709. }
  83710. return error;
  83711. };
  83712. return QuadraticErrorSimplification;
  83713. }());
  83714. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83715. })(BABYLON || (BABYLON = {}));
  83716. //# sourceMappingURL=babylon.meshSimplification.js.map
  83717. var BABYLON;
  83718. (function (BABYLON) {
  83719. var MeshLODLevel = /** @class */ (function () {
  83720. function MeshLODLevel(distance, mesh) {
  83721. this.distance = distance;
  83722. this.mesh = mesh;
  83723. }
  83724. return MeshLODLevel;
  83725. }());
  83726. BABYLON.MeshLODLevel = MeshLODLevel;
  83727. })(BABYLON || (BABYLON = {}));
  83728. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83729. var BABYLON;
  83730. (function (BABYLON) {
  83731. /**
  83732. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83733. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83734. */
  83735. var SceneOptimization = /** @class */ (function () {
  83736. /**
  83737. * Creates the SceneOptimization object
  83738. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83739. * @param desc defines the description associated with the optimization
  83740. */
  83741. function SceneOptimization(
  83742. /**
  83743. * Defines the priority of this optimization (0 by default which means first in the list)
  83744. */
  83745. priority) {
  83746. if (priority === void 0) { priority = 0; }
  83747. this.priority = priority;
  83748. }
  83749. /**
  83750. * Gets a string describing the action executed by the current optimization
  83751. * @returns description string
  83752. */
  83753. SceneOptimization.prototype.getDescription = function () {
  83754. return "";
  83755. };
  83756. /**
  83757. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83758. * @param scene defines the current scene where to apply this optimization
  83759. * @param optimizer defines the current optimizer
  83760. * @returns true if everything that can be done was applied
  83761. */
  83762. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83763. return true;
  83764. };
  83765. ;
  83766. return SceneOptimization;
  83767. }());
  83768. BABYLON.SceneOptimization = SceneOptimization;
  83769. /**
  83770. * Defines an optimization used to reduce the size of render target textures
  83771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83772. */
  83773. var TextureOptimization = /** @class */ (function (_super) {
  83774. __extends(TextureOptimization, _super);
  83775. /**
  83776. * Creates the TextureOptimization object
  83777. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83778. * @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
  83779. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83780. */
  83781. function TextureOptimization(
  83782. /**
  83783. * Defines the priority of this optimization (0 by default which means first in the list)
  83784. */
  83785. priority,
  83786. /**
  83787. * 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
  83788. */
  83789. maximumSize,
  83790. /**
  83791. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83792. */
  83793. step) {
  83794. if (priority === void 0) { priority = 0; }
  83795. if (maximumSize === void 0) { maximumSize = 1024; }
  83796. if (step === void 0) { step = 0.5; }
  83797. var _this = _super.call(this, priority) || this;
  83798. _this.priority = priority;
  83799. _this.maximumSize = maximumSize;
  83800. _this.step = step;
  83801. return _this;
  83802. }
  83803. /**
  83804. * Gets a string describing the action executed by the current optimization
  83805. * @returns description string
  83806. */
  83807. TextureOptimization.prototype.getDescription = function () {
  83808. return "Reducing render target texture size to " + this.maximumSize;
  83809. };
  83810. /**
  83811. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83812. * @param scene defines the current scene where to apply this optimization
  83813. * @param optimizer defines the current optimizer
  83814. * @returns true if everything that can be done was applied
  83815. */
  83816. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83817. var allDone = true;
  83818. for (var index = 0; index < scene.textures.length; index++) {
  83819. var texture = scene.textures[index];
  83820. if (!texture.canRescale || texture.getContext) {
  83821. continue;
  83822. }
  83823. var currentSize = texture.getSize();
  83824. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83825. if (maxDimension > this.maximumSize) {
  83826. texture.scale(this.step);
  83827. allDone = false;
  83828. }
  83829. }
  83830. return allDone;
  83831. };
  83832. return TextureOptimization;
  83833. }(SceneOptimization));
  83834. BABYLON.TextureOptimization = TextureOptimization;
  83835. /**
  83836. * Defines an optimization used to increase or decrease the rendering resolution
  83837. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83838. */
  83839. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83840. __extends(HardwareScalingOptimization, _super);
  83841. /**
  83842. * Creates the HardwareScalingOptimization object
  83843. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83844. * @param maximumScale defines the maximum scale to use (2 by default)
  83845. * @param step defines the step to use between two passes (0.5 by default)
  83846. */
  83847. function HardwareScalingOptimization(
  83848. /**
  83849. * Defines the priority of this optimization (0 by default which means first in the list)
  83850. */
  83851. priority,
  83852. /**
  83853. * Defines the maximum scale to use (2 by default)
  83854. */
  83855. maximumScale,
  83856. /**
  83857. * Defines the step to use between two passes (0.5 by default)
  83858. */
  83859. step) {
  83860. if (priority === void 0) { priority = 0; }
  83861. if (maximumScale === void 0) { maximumScale = 2; }
  83862. if (step === void 0) { step = 0.25; }
  83863. var _this = _super.call(this, priority) || this;
  83864. _this.priority = priority;
  83865. _this.maximumScale = maximumScale;
  83866. _this.step = step;
  83867. _this._currentScale = -1;
  83868. _this._directionOffset = 1;
  83869. return _this;
  83870. }
  83871. /**
  83872. * Gets a string describing the action executed by the current optimization
  83873. * @return description string
  83874. */
  83875. HardwareScalingOptimization.prototype.getDescription = function () {
  83876. return "Setting hardware scaling level to " + this._currentScale;
  83877. };
  83878. /**
  83879. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83880. * @param scene defines the current scene where to apply this optimization
  83881. * @param optimizer defines the current optimizer
  83882. * @returns true if everything that can be done was applied
  83883. */
  83884. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83885. if (this._currentScale === -1) {
  83886. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83887. if (this._currentScale > this.maximumScale) {
  83888. this._directionOffset = -1;
  83889. }
  83890. }
  83891. this._currentScale += this._directionOffset * this.step;
  83892. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83893. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83894. };
  83895. ;
  83896. return HardwareScalingOptimization;
  83897. }(SceneOptimization));
  83898. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83899. /**
  83900. * Defines an optimization used to remove shadows
  83901. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83902. */
  83903. var ShadowsOptimization = /** @class */ (function (_super) {
  83904. __extends(ShadowsOptimization, _super);
  83905. function ShadowsOptimization() {
  83906. return _super !== null && _super.apply(this, arguments) || this;
  83907. }
  83908. /**
  83909. * Gets a string describing the action executed by the current optimization
  83910. * @return description string
  83911. */
  83912. ShadowsOptimization.prototype.getDescription = function () {
  83913. return "Turning shadows on/off";
  83914. };
  83915. /**
  83916. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83917. * @param scene defines the current scene where to apply this optimization
  83918. * @param optimizer defines the current optimizer
  83919. * @returns true if everything that can be done was applied
  83920. */
  83921. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83922. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83923. return true;
  83924. };
  83925. ;
  83926. return ShadowsOptimization;
  83927. }(SceneOptimization));
  83928. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83929. /**
  83930. * Defines an optimization used to turn post-processes off
  83931. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83932. */
  83933. var PostProcessesOptimization = /** @class */ (function (_super) {
  83934. __extends(PostProcessesOptimization, _super);
  83935. function PostProcessesOptimization() {
  83936. return _super !== null && _super.apply(this, arguments) || this;
  83937. }
  83938. /**
  83939. * Gets a string describing the action executed by the current optimization
  83940. * @return description string
  83941. */
  83942. PostProcessesOptimization.prototype.getDescription = function () {
  83943. return "Turning post-processes on/off";
  83944. };
  83945. /**
  83946. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83947. * @param scene defines the current scene where to apply this optimization
  83948. * @param optimizer defines the current optimizer
  83949. * @returns true if everything that can be done was applied
  83950. */
  83951. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83952. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83953. return true;
  83954. };
  83955. ;
  83956. return PostProcessesOptimization;
  83957. }(SceneOptimization));
  83958. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83959. /**
  83960. * Defines an optimization used to turn lens flares off
  83961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83962. */
  83963. var LensFlaresOptimization = /** @class */ (function (_super) {
  83964. __extends(LensFlaresOptimization, _super);
  83965. function LensFlaresOptimization() {
  83966. return _super !== null && _super.apply(this, arguments) || this;
  83967. }
  83968. /**
  83969. * Gets a string describing the action executed by the current optimization
  83970. * @return description string
  83971. */
  83972. LensFlaresOptimization.prototype.getDescription = function () {
  83973. return "Turning lens flares on/off";
  83974. };
  83975. /**
  83976. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83977. * @param scene defines the current scene where to apply this optimization
  83978. * @param optimizer defines the current optimizer
  83979. * @returns true if everything that can be done was applied
  83980. */
  83981. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83982. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83983. return true;
  83984. };
  83985. ;
  83986. return LensFlaresOptimization;
  83987. }(SceneOptimization));
  83988. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83989. /**
  83990. * Defines an optimization based on user defined callback.
  83991. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83992. */
  83993. var CustomOptimization = /** @class */ (function (_super) {
  83994. __extends(CustomOptimization, _super);
  83995. function CustomOptimization() {
  83996. return _super !== null && _super.apply(this, arguments) || this;
  83997. }
  83998. /**
  83999. * Gets a string describing the action executed by the current optimization
  84000. * @returns description string
  84001. */
  84002. CustomOptimization.prototype.getDescription = function () {
  84003. if (this.onGetDescription) {
  84004. return this.onGetDescription();
  84005. }
  84006. return "Running user defined callback";
  84007. };
  84008. /**
  84009. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84010. * @param scene defines the current scene where to apply this optimization
  84011. * @param optimizer defines the current optimizer
  84012. * @returns true if everything that can be done was applied
  84013. */
  84014. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84015. if (this.onApply) {
  84016. return this.onApply(scene, optimizer);
  84017. }
  84018. return true;
  84019. };
  84020. ;
  84021. return CustomOptimization;
  84022. }(SceneOptimization));
  84023. BABYLON.CustomOptimization = CustomOptimization;
  84024. /**
  84025. * Defines an optimization used to turn particles off
  84026. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84027. */
  84028. var ParticlesOptimization = /** @class */ (function (_super) {
  84029. __extends(ParticlesOptimization, _super);
  84030. function ParticlesOptimization() {
  84031. return _super !== null && _super.apply(this, arguments) || this;
  84032. }
  84033. /**
  84034. * Gets a string describing the action executed by the current optimization
  84035. * @return description string
  84036. */
  84037. ParticlesOptimization.prototype.getDescription = function () {
  84038. return "Turning particles on/off";
  84039. };
  84040. /**
  84041. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84042. * @param scene defines the current scene where to apply this optimization
  84043. * @param optimizer defines the current optimizer
  84044. * @returns true if everything that can be done was applied
  84045. */
  84046. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84047. scene.particlesEnabled = optimizer.isInImprovementMode;
  84048. return true;
  84049. };
  84050. ;
  84051. return ParticlesOptimization;
  84052. }(SceneOptimization));
  84053. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84054. /**
  84055. * Defines an optimization used to turn render targets off
  84056. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84057. */
  84058. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84059. __extends(RenderTargetsOptimization, _super);
  84060. function RenderTargetsOptimization() {
  84061. return _super !== null && _super.apply(this, arguments) || this;
  84062. }
  84063. /**
  84064. * Gets a string describing the action executed by the current optimization
  84065. * @return description string
  84066. */
  84067. RenderTargetsOptimization.prototype.getDescription = function () {
  84068. return "Turning render targets off";
  84069. };
  84070. /**
  84071. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84072. * @param scene defines the current scene where to apply this optimization
  84073. * @param optimizer defines the current optimizer
  84074. * @returns true if everything that can be done was applied
  84075. */
  84076. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84077. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84078. return true;
  84079. };
  84080. ;
  84081. return RenderTargetsOptimization;
  84082. }(SceneOptimization));
  84083. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84084. /**
  84085. * Defines an optimization used to merge meshes with compatible materials
  84086. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84087. */
  84088. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84089. __extends(MergeMeshesOptimization, _super);
  84090. function MergeMeshesOptimization() {
  84091. var _this = _super !== null && _super.apply(this, arguments) || this;
  84092. _this._canBeMerged = function (abstractMesh) {
  84093. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84094. return false;
  84095. }
  84096. var mesh = abstractMesh;
  84097. if (!mesh.isVisible || !mesh.isEnabled()) {
  84098. return false;
  84099. }
  84100. if (mesh.instances.length > 0) {
  84101. return false;
  84102. }
  84103. if (mesh.skeleton || mesh.hasLODLevels) {
  84104. return false;
  84105. }
  84106. if (mesh.parent) {
  84107. return false;
  84108. }
  84109. return true;
  84110. };
  84111. return _this;
  84112. }
  84113. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84114. /**
  84115. * Gets or sets a boolean which defines if optimization octree has to be updated
  84116. */
  84117. get: function () {
  84118. return MergeMeshesOptimization._UpdateSelectionTree;
  84119. },
  84120. /**
  84121. * Gets or sets a boolean which defines if optimization octree has to be updated
  84122. */
  84123. set: function (value) {
  84124. MergeMeshesOptimization._UpdateSelectionTree = value;
  84125. },
  84126. enumerable: true,
  84127. configurable: true
  84128. });
  84129. /**
  84130. * Gets a string describing the action executed by the current optimization
  84131. * @return description string
  84132. */
  84133. MergeMeshesOptimization.prototype.getDescription = function () {
  84134. return "Merging similar meshes together";
  84135. };
  84136. /**
  84137. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84138. * @param scene defines the current scene where to apply this optimization
  84139. * @param optimizer defines the current optimizer
  84140. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84141. * @returns true if everything that can be done was applied
  84142. */
  84143. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84144. var globalPool = scene.meshes.slice(0);
  84145. var globalLength = globalPool.length;
  84146. for (var index = 0; index < globalLength; index++) {
  84147. var currentPool = new Array();
  84148. var current = globalPool[index];
  84149. // Checks
  84150. if (!this._canBeMerged(current)) {
  84151. continue;
  84152. }
  84153. currentPool.push(current);
  84154. // Find compatible meshes
  84155. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84156. var otherMesh = globalPool[subIndex];
  84157. if (!this._canBeMerged(otherMesh)) {
  84158. continue;
  84159. }
  84160. if (otherMesh.material !== current.material) {
  84161. continue;
  84162. }
  84163. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84164. continue;
  84165. }
  84166. currentPool.push(otherMesh);
  84167. globalLength--;
  84168. globalPool.splice(subIndex, 1);
  84169. subIndex--;
  84170. }
  84171. if (currentPool.length < 2) {
  84172. continue;
  84173. }
  84174. // Merge meshes
  84175. BABYLON.Mesh.MergeMeshes(currentPool);
  84176. }
  84177. if (updateSelectionTree != undefined) {
  84178. if (updateSelectionTree) {
  84179. scene.createOrUpdateSelectionOctree();
  84180. }
  84181. }
  84182. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84183. scene.createOrUpdateSelectionOctree();
  84184. }
  84185. return true;
  84186. };
  84187. ;
  84188. MergeMeshesOptimization._UpdateSelectionTree = false;
  84189. return MergeMeshesOptimization;
  84190. }(SceneOptimization));
  84191. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84192. /**
  84193. * Defines a list of options used by SceneOptimizer
  84194. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84195. */
  84196. var SceneOptimizerOptions = /** @class */ (function () {
  84197. /**
  84198. * Creates a new list of options used by SceneOptimizer
  84199. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84200. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84201. */
  84202. function SceneOptimizerOptions(
  84203. /**
  84204. * Defines the target frame rate to reach (60 by default)
  84205. */
  84206. targetFrameRate,
  84207. /**
  84208. * Defines the interval between two checkes (2000ms by default)
  84209. */
  84210. trackerDuration) {
  84211. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84212. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84213. this.targetFrameRate = targetFrameRate;
  84214. this.trackerDuration = trackerDuration;
  84215. /**
  84216. * Gets the list of optimizations to apply
  84217. */
  84218. this.optimizations = new Array();
  84219. }
  84220. /**
  84221. * Add a new optimization
  84222. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84223. * @returns the current SceneOptimizerOptions
  84224. */
  84225. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84226. this.optimizations.push(optimization);
  84227. return this;
  84228. };
  84229. /**
  84230. * Add a new custom optimization
  84231. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84232. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84233. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84234. * @returns the current SceneOptimizerOptions
  84235. */
  84236. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84237. if (priority === void 0) { priority = 0; }
  84238. var optimization = new CustomOptimization(priority);
  84239. optimization.onApply = onApply;
  84240. optimization.onGetDescription = onGetDescription;
  84241. this.optimizations.push(optimization);
  84242. return this;
  84243. };
  84244. /**
  84245. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84246. * @param targetFrameRate defines the target frame rate (60 by default)
  84247. * @returns a SceneOptimizerOptions object
  84248. */
  84249. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84250. var result = new SceneOptimizerOptions(targetFrameRate);
  84251. var priority = 0;
  84252. result.addOptimization(new MergeMeshesOptimization(priority));
  84253. result.addOptimization(new ShadowsOptimization(priority));
  84254. result.addOptimization(new LensFlaresOptimization(priority));
  84255. // Next priority
  84256. priority++;
  84257. result.addOptimization(new PostProcessesOptimization(priority));
  84258. result.addOptimization(new ParticlesOptimization(priority));
  84259. // Next priority
  84260. priority++;
  84261. result.addOptimization(new TextureOptimization(priority, 1024));
  84262. return result;
  84263. };
  84264. /**
  84265. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84266. * @param targetFrameRate defines the target frame rate (60 by default)
  84267. * @returns a SceneOptimizerOptions object
  84268. */
  84269. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84270. var result = new SceneOptimizerOptions(targetFrameRate);
  84271. var priority = 0;
  84272. result.addOptimization(new MergeMeshesOptimization(priority));
  84273. result.addOptimization(new ShadowsOptimization(priority));
  84274. result.addOptimization(new LensFlaresOptimization(priority));
  84275. // Next priority
  84276. priority++;
  84277. result.addOptimization(new PostProcessesOptimization(priority));
  84278. result.addOptimization(new ParticlesOptimization(priority));
  84279. // Next priority
  84280. priority++;
  84281. result.addOptimization(new TextureOptimization(priority, 512));
  84282. // Next priority
  84283. priority++;
  84284. result.addOptimization(new RenderTargetsOptimization(priority));
  84285. // Next priority
  84286. priority++;
  84287. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84288. return result;
  84289. };
  84290. /**
  84291. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84292. * @param targetFrameRate defines the target frame rate (60 by default)
  84293. * @returns a SceneOptimizerOptions object
  84294. */
  84295. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84296. var result = new SceneOptimizerOptions(targetFrameRate);
  84297. var priority = 0;
  84298. result.addOptimization(new MergeMeshesOptimization(priority));
  84299. result.addOptimization(new ShadowsOptimization(priority));
  84300. result.addOptimization(new LensFlaresOptimization(priority));
  84301. // Next priority
  84302. priority++;
  84303. result.addOptimization(new PostProcessesOptimization(priority));
  84304. result.addOptimization(new ParticlesOptimization(priority));
  84305. // Next priority
  84306. priority++;
  84307. result.addOptimization(new TextureOptimization(priority, 256));
  84308. // Next priority
  84309. priority++;
  84310. result.addOptimization(new RenderTargetsOptimization(priority));
  84311. // Next priority
  84312. priority++;
  84313. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84314. return result;
  84315. };
  84316. return SceneOptimizerOptions;
  84317. }());
  84318. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84319. /**
  84320. * Class used to run optimizations in order to reach a target frame rate
  84321. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84322. */
  84323. var SceneOptimizer = /** @class */ (function () {
  84324. /**
  84325. * Creates a new SceneOptimizer
  84326. * @param scene defines the scene to work on
  84327. * @param options defines the options to use with the SceneOptimizer
  84328. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84329. * @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)
  84330. */
  84331. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84332. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84333. if (improvementMode === void 0) { improvementMode = false; }
  84334. var _this = this;
  84335. this._isRunning = false;
  84336. this._currentPriorityLevel = 0;
  84337. this._targetFrameRate = 60;
  84338. this._trackerDuration = 2000;
  84339. this._currentFrameRate = 0;
  84340. this._improvementMode = false;
  84341. /**
  84342. * Defines an observable called when the optimizer reaches the target frame rate
  84343. */
  84344. this.onSuccessObservable = new BABYLON.Observable();
  84345. /**
  84346. * Defines an observable called when the optimizer enables an optimization
  84347. */
  84348. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84349. /**
  84350. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84351. */
  84352. this.onFailureObservable = new BABYLON.Observable();
  84353. if (!options) {
  84354. this._options = new SceneOptimizerOptions();
  84355. }
  84356. else {
  84357. this._options = options;
  84358. }
  84359. if (this._options.targetFrameRate) {
  84360. this._targetFrameRate = this._options.targetFrameRate;
  84361. }
  84362. if (this._options.trackerDuration) {
  84363. this._trackerDuration = this._options.trackerDuration;
  84364. }
  84365. if (autoGeneratePriorities) {
  84366. var priority = 0;
  84367. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84368. var optim = _a[_i];
  84369. optim.priority = priority++;
  84370. }
  84371. }
  84372. this._improvementMode = improvementMode;
  84373. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84374. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84375. _this._sceneDisposeObserver = null;
  84376. _this.dispose();
  84377. });
  84378. }
  84379. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84380. /**
  84381. * Gets a boolean indicating if the optimizer is in improvement mode
  84382. */
  84383. get: function () {
  84384. return this._improvementMode;
  84385. },
  84386. enumerable: true,
  84387. configurable: true
  84388. });
  84389. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84390. /**
  84391. * Gets the current priority level (0 at start)
  84392. */
  84393. get: function () {
  84394. return this._currentPriorityLevel;
  84395. },
  84396. enumerable: true,
  84397. configurable: true
  84398. });
  84399. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84400. /**
  84401. * Gets the current frame rate checked by the SceneOptimizer
  84402. */
  84403. get: function () {
  84404. return this._currentFrameRate;
  84405. },
  84406. enumerable: true,
  84407. configurable: true
  84408. });
  84409. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84410. /**
  84411. * Gets or sets the current target frame rate (60 by default)
  84412. */
  84413. get: function () {
  84414. return this._targetFrameRate;
  84415. },
  84416. /**
  84417. * Gets or sets the current target frame rate (60 by default)
  84418. */
  84419. set: function (value) {
  84420. this._targetFrameRate = value;
  84421. },
  84422. enumerable: true,
  84423. configurable: true
  84424. });
  84425. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84426. /**
  84427. * Gets or sets the current interval between two checks (every 2000ms by default)
  84428. */
  84429. get: function () {
  84430. return this._trackerDuration;
  84431. },
  84432. /**
  84433. * Gets or sets the current interval between two checks (every 2000ms by default)
  84434. */
  84435. set: function (value) {
  84436. this._trackerDuration = value;
  84437. },
  84438. enumerable: true,
  84439. configurable: true
  84440. });
  84441. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84442. /**
  84443. * Gets the list of active optimizations
  84444. */
  84445. get: function () {
  84446. return this._options.optimizations;
  84447. },
  84448. enumerable: true,
  84449. configurable: true
  84450. });
  84451. /**
  84452. * Stops the current optimizer
  84453. */
  84454. SceneOptimizer.prototype.stop = function () {
  84455. this._isRunning = false;
  84456. };
  84457. /**
  84458. * Reset the optimizer to initial step (current priority level = 0)
  84459. */
  84460. SceneOptimizer.prototype.reset = function () {
  84461. this._currentPriorityLevel = 0;
  84462. };
  84463. /**
  84464. * Start the optimizer. By default it will try to reach a specific framerate
  84465. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84466. */
  84467. SceneOptimizer.prototype.start = function () {
  84468. var _this = this;
  84469. if (this._isRunning) {
  84470. return;
  84471. }
  84472. this._isRunning = true;
  84473. // Let's wait for the scene to be ready before running our check
  84474. this._scene.executeWhenReady(function () {
  84475. setTimeout(function () {
  84476. _this._checkCurrentState();
  84477. }, _this._trackerDuration);
  84478. });
  84479. };
  84480. SceneOptimizer.prototype._checkCurrentState = function () {
  84481. var _this = this;
  84482. if (!this._isRunning) {
  84483. return;
  84484. }
  84485. var scene = this._scene;
  84486. var options = this._options;
  84487. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84488. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84489. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84490. this._isRunning = false;
  84491. this.onSuccessObservable.notifyObservers(this);
  84492. return;
  84493. }
  84494. // Apply current level of optimizations
  84495. var allDone = true;
  84496. var noOptimizationApplied = true;
  84497. for (var index = 0; index < options.optimizations.length; index++) {
  84498. var optimization = options.optimizations[index];
  84499. if (optimization.priority === this._currentPriorityLevel) {
  84500. noOptimizationApplied = false;
  84501. allDone = allDone && optimization.apply(scene, this);
  84502. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84503. }
  84504. }
  84505. // If no optimization was applied, this is a failure :(
  84506. if (noOptimizationApplied) {
  84507. this._isRunning = false;
  84508. this.onFailureObservable.notifyObservers(this);
  84509. return;
  84510. }
  84511. // If all optimizations were done, move to next level
  84512. if (allDone) {
  84513. this._currentPriorityLevel++;
  84514. }
  84515. // Let's the system running for a specific amount of time before checking FPS
  84516. scene.executeWhenReady(function () {
  84517. setTimeout(function () {
  84518. _this._checkCurrentState();
  84519. }, _this._trackerDuration);
  84520. });
  84521. };
  84522. /**
  84523. * Release all resources
  84524. */
  84525. SceneOptimizer.prototype.dispose = function () {
  84526. this.stop();
  84527. this.onSuccessObservable.clear();
  84528. this.onFailureObservable.clear();
  84529. this.onNewOptimizationAppliedObservable.clear();
  84530. if (this._sceneDisposeObserver) {
  84531. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84532. }
  84533. };
  84534. /**
  84535. * Helper function to create a SceneOptimizer with one single line of code
  84536. * @param scene defines the scene to work on
  84537. * @param options defines the options to use with the SceneOptimizer
  84538. * @param onSuccess defines a callback to call on success
  84539. * @param onFailure defines a callback to call on failure
  84540. * @returns the new SceneOptimizer object
  84541. */
  84542. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84543. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84544. if (onSuccess) {
  84545. optimizer.onSuccessObservable.add(function () {
  84546. onSuccess();
  84547. });
  84548. }
  84549. if (onFailure) {
  84550. optimizer.onFailureObservable.add(function () {
  84551. onFailure();
  84552. });
  84553. }
  84554. optimizer.start();
  84555. return optimizer;
  84556. };
  84557. return SceneOptimizer;
  84558. }());
  84559. BABYLON.SceneOptimizer = SceneOptimizer;
  84560. })(BABYLON || (BABYLON = {}));
  84561. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84562. var BABYLON;
  84563. (function (BABYLON) {
  84564. var OutlineRenderer = /** @class */ (function () {
  84565. function OutlineRenderer(scene) {
  84566. this.zOffset = 1;
  84567. this._scene = scene;
  84568. }
  84569. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84570. var _this = this;
  84571. if (useOverlay === void 0) { useOverlay = false; }
  84572. var scene = this._scene;
  84573. var engine = this._scene.getEngine();
  84574. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84575. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84576. return;
  84577. }
  84578. var mesh = subMesh.getRenderingMesh();
  84579. var material = subMesh.getMaterial();
  84580. if (!material || !scene.activeCamera) {
  84581. return;
  84582. }
  84583. engine.enableEffect(this._effect);
  84584. // Logarithmic depth
  84585. if (material.useLogarithmicDepth) {
  84586. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84587. }
  84588. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84589. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84590. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84591. // Bones
  84592. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84593. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84594. }
  84595. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84596. // Alpha test
  84597. if (material && material.needAlphaTesting()) {
  84598. var alphaTexture = material.getAlphaTestTexture();
  84599. if (alphaTexture) {
  84600. this._effect.setTexture("diffuseSampler", alphaTexture);
  84601. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84602. }
  84603. }
  84604. engine.setZOffset(-this.zOffset);
  84605. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84606. engine.setZOffset(0);
  84607. };
  84608. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84609. var defines = [];
  84610. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84611. var mesh = subMesh.getMesh();
  84612. var material = subMesh.getMaterial();
  84613. if (material) {
  84614. // Alpha test
  84615. if (material.needAlphaTesting()) {
  84616. defines.push("#define ALPHATEST");
  84617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84618. attribs.push(BABYLON.VertexBuffer.UVKind);
  84619. defines.push("#define UV1");
  84620. }
  84621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84623. defines.push("#define UV2");
  84624. }
  84625. }
  84626. //Logarithmic depth
  84627. if (material.useLogarithmicDepth) {
  84628. defines.push("#define LOGARITHMICDEPTH");
  84629. }
  84630. }
  84631. // Bones
  84632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84635. if (mesh.numBoneInfluencers > 4) {
  84636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84638. }
  84639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84640. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84641. }
  84642. else {
  84643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84644. }
  84645. // Instances
  84646. if (useInstances) {
  84647. defines.push("#define INSTANCES");
  84648. attribs.push("world0");
  84649. attribs.push("world1");
  84650. attribs.push("world2");
  84651. attribs.push("world3");
  84652. }
  84653. // Get correct effect
  84654. var join = defines.join("\n");
  84655. if (this._cachedDefines !== join) {
  84656. this._cachedDefines = join;
  84657. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84658. }
  84659. return this._effect.isReady();
  84660. };
  84661. return OutlineRenderer;
  84662. }());
  84663. BABYLON.OutlineRenderer = OutlineRenderer;
  84664. })(BABYLON || (BABYLON = {}));
  84665. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84666. var BABYLON;
  84667. (function (BABYLON) {
  84668. var FaceAdjacencies = /** @class */ (function () {
  84669. function FaceAdjacencies() {
  84670. this.edges = new Array();
  84671. this.edgesConnectedCount = 0;
  84672. }
  84673. return FaceAdjacencies;
  84674. }());
  84675. var EdgesRenderer = /** @class */ (function () {
  84676. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84677. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84678. if (epsilon === void 0) { epsilon = 0.95; }
  84679. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84680. this.edgesWidthScalerForOrthographic = 1000.0;
  84681. this.edgesWidthScalerForPerspective = 50.0;
  84682. this._linesPositions = new Array();
  84683. this._linesNormals = new Array();
  84684. this._linesIndices = new Array();
  84685. this._buffers = {};
  84686. this._checkVerticesInsteadOfIndices = false;
  84687. this._source = source;
  84688. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84689. this._epsilon = epsilon;
  84690. this._prepareRessources();
  84691. this._generateEdgesLines();
  84692. }
  84693. EdgesRenderer.prototype._prepareRessources = function () {
  84694. if (this._lineShader) {
  84695. return;
  84696. }
  84697. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84698. attributes: ["position", "normal"],
  84699. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84700. });
  84701. this._lineShader.disableDepthWrite = true;
  84702. this._lineShader.backFaceCulling = false;
  84703. };
  84704. EdgesRenderer.prototype._rebuild = function () {
  84705. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84706. if (buffer) {
  84707. buffer._rebuild();
  84708. }
  84709. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84710. if (buffer) {
  84711. buffer._rebuild();
  84712. }
  84713. var scene = this._source.getScene();
  84714. var engine = scene.getEngine();
  84715. this._ib = engine.createIndexBuffer(this._linesIndices);
  84716. };
  84717. EdgesRenderer.prototype.dispose = function () {
  84718. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84719. if (buffer) {
  84720. buffer.dispose();
  84721. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84722. }
  84723. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84724. if (buffer) {
  84725. buffer.dispose();
  84726. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84727. }
  84728. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84729. this._lineShader.dispose();
  84730. };
  84731. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84732. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84733. return 0;
  84734. }
  84735. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84736. return 1;
  84737. }
  84738. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84739. return 2;
  84740. }
  84741. return -1;
  84742. };
  84743. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84744. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84745. return 0;
  84746. }
  84747. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84748. return 1;
  84749. }
  84750. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84751. return 2;
  84752. }
  84753. return -1;
  84754. };
  84755. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84756. var needToCreateLine;
  84757. if (edge === undefined) {
  84758. needToCreateLine = true;
  84759. }
  84760. else {
  84761. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84762. needToCreateLine = dotProduct < this._epsilon;
  84763. }
  84764. if (needToCreateLine) {
  84765. var offset = this._linesPositions.length / 3;
  84766. var normal = p0.subtract(p1);
  84767. normal.normalize();
  84768. // Positions
  84769. this._linesPositions.push(p0.x);
  84770. this._linesPositions.push(p0.y);
  84771. this._linesPositions.push(p0.z);
  84772. this._linesPositions.push(p0.x);
  84773. this._linesPositions.push(p0.y);
  84774. this._linesPositions.push(p0.z);
  84775. this._linesPositions.push(p1.x);
  84776. this._linesPositions.push(p1.y);
  84777. this._linesPositions.push(p1.z);
  84778. this._linesPositions.push(p1.x);
  84779. this._linesPositions.push(p1.y);
  84780. this._linesPositions.push(p1.z);
  84781. // Normals
  84782. this._linesNormals.push(p1.x);
  84783. this._linesNormals.push(p1.y);
  84784. this._linesNormals.push(p1.z);
  84785. this._linesNormals.push(-1);
  84786. this._linesNormals.push(p1.x);
  84787. this._linesNormals.push(p1.y);
  84788. this._linesNormals.push(p1.z);
  84789. this._linesNormals.push(1);
  84790. this._linesNormals.push(p0.x);
  84791. this._linesNormals.push(p0.y);
  84792. this._linesNormals.push(p0.z);
  84793. this._linesNormals.push(-1);
  84794. this._linesNormals.push(p0.x);
  84795. this._linesNormals.push(p0.y);
  84796. this._linesNormals.push(p0.z);
  84797. this._linesNormals.push(1);
  84798. // Indices
  84799. this._linesIndices.push(offset);
  84800. this._linesIndices.push(offset + 1);
  84801. this._linesIndices.push(offset + 2);
  84802. this._linesIndices.push(offset);
  84803. this._linesIndices.push(offset + 2);
  84804. this._linesIndices.push(offset + 3);
  84805. }
  84806. };
  84807. EdgesRenderer.prototype._generateEdgesLines = function () {
  84808. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84809. var indices = this._source.getIndices();
  84810. if (!indices || !positions) {
  84811. return;
  84812. }
  84813. // First let's find adjacencies
  84814. var adjacencies = new Array();
  84815. var faceNormals = new Array();
  84816. var index;
  84817. var faceAdjacencies;
  84818. // Prepare faces
  84819. for (index = 0; index < indices.length; index += 3) {
  84820. faceAdjacencies = new FaceAdjacencies();
  84821. var p0Index = indices[index];
  84822. var p1Index = indices[index + 1];
  84823. var p2Index = indices[index + 2];
  84824. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84825. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84826. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84827. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84828. faceNormal.normalize();
  84829. faceNormals.push(faceNormal);
  84830. adjacencies.push(faceAdjacencies);
  84831. }
  84832. // Scan
  84833. for (index = 0; index < adjacencies.length; index++) {
  84834. faceAdjacencies = adjacencies[index];
  84835. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84836. var otherFaceAdjacencies = adjacencies[otherIndex];
  84837. if (faceAdjacencies.edgesConnectedCount === 3) {
  84838. break;
  84839. }
  84840. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84841. continue;
  84842. }
  84843. var otherP0 = indices[otherIndex * 3];
  84844. var otherP1 = indices[otherIndex * 3 + 1];
  84845. var otherP2 = indices[otherIndex * 3 + 2];
  84846. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84847. var otherEdgeIndex = 0;
  84848. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84849. continue;
  84850. }
  84851. switch (edgeIndex) {
  84852. case 0:
  84853. if (this._checkVerticesInsteadOfIndices) {
  84854. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84855. }
  84856. else {
  84857. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84858. }
  84859. break;
  84860. case 1:
  84861. if (this._checkVerticesInsteadOfIndices) {
  84862. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84863. }
  84864. else {
  84865. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84866. }
  84867. break;
  84868. case 2:
  84869. if (this._checkVerticesInsteadOfIndices) {
  84870. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84871. }
  84872. else {
  84873. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84874. }
  84875. break;
  84876. }
  84877. if (otherEdgeIndex === -1) {
  84878. continue;
  84879. }
  84880. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84881. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84882. faceAdjacencies.edgesConnectedCount++;
  84883. otherFaceAdjacencies.edgesConnectedCount++;
  84884. if (faceAdjacencies.edgesConnectedCount === 3) {
  84885. break;
  84886. }
  84887. }
  84888. }
  84889. }
  84890. // Create lines
  84891. for (index = 0; index < adjacencies.length; index++) {
  84892. // 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
  84893. var current = adjacencies[index];
  84894. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84895. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84896. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84897. }
  84898. // Merge into a single mesh
  84899. var engine = this._source.getScene().getEngine();
  84900. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84901. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84902. this._ib = engine.createIndexBuffer(this._linesIndices);
  84903. this._indicesCount = this._linesIndices.length;
  84904. };
  84905. EdgesRenderer.prototype.render = function () {
  84906. var scene = this._source.getScene();
  84907. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84908. return;
  84909. }
  84910. var engine = scene.getEngine();
  84911. this._lineShader._preBind();
  84912. // VBOs
  84913. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84914. scene.resetCachedMaterial();
  84915. this._lineShader.setColor4("color", this._source.edgesColor);
  84916. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84917. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84918. }
  84919. else {
  84920. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84921. }
  84922. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84923. this._lineShader.bind(this._source.getWorldMatrix());
  84924. // Draw order
  84925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84926. this._lineShader.unbind();
  84927. engine.setDepthWrite(true);
  84928. };
  84929. return EdgesRenderer;
  84930. }());
  84931. BABYLON.EdgesRenderer = EdgesRenderer;
  84932. })(BABYLON || (BABYLON = {}));
  84933. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84934. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84935. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84936. s = arguments[i];
  84937. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84938. t[p] = s[p];
  84939. }
  84940. return t;
  84941. };
  84942. var BABYLON;
  84943. (function (BABYLON) {
  84944. /**
  84945. * The effect layer Helps adding post process effect blended with the main pass.
  84946. *
  84947. * This can be for instance use to generate glow or higlight effects on the scene.
  84948. *
  84949. * The effect layer class can not be used directly and is intented to inherited from to be
  84950. * customized per effects.
  84951. */
  84952. var EffectLayer = /** @class */ (function () {
  84953. /**
  84954. * Instantiates a new effect Layer and references it in the scene.
  84955. * @param name The name of the layer
  84956. * @param scene The scene to use the layer in
  84957. */
  84958. function EffectLayer(
  84959. /** The Friendly of the effect in the scene */
  84960. name, scene) {
  84961. this.name = name;
  84962. this._vertexBuffers = {};
  84963. this._maxSize = 0;
  84964. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84965. this._shouldRender = true;
  84966. this._postProcesses = [];
  84967. this._textures = [];
  84968. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84969. /**
  84970. * The clear color of the texture used to generate the glow map.
  84971. */
  84972. this.neutralColor = new BABYLON.Color4();
  84973. /**
  84974. * Specifies wether the highlight layer is enabled or not.
  84975. */
  84976. this.isEnabled = true;
  84977. /**
  84978. * An event triggered when the effect layer has been disposed.
  84979. */
  84980. this.onDisposeObservable = new BABYLON.Observable();
  84981. /**
  84982. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84983. */
  84984. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84985. /**
  84986. * An event triggered when the generated texture is being merged in the scene.
  84987. */
  84988. this.onBeforeComposeObservable = new BABYLON.Observable();
  84989. /**
  84990. * An event triggered when the generated texture has been merged in the scene.
  84991. */
  84992. this.onAfterComposeObservable = new BABYLON.Observable();
  84993. /**
  84994. * An event triggered when the efffect layer changes its size.
  84995. */
  84996. this.onSizeChangedObservable = new BABYLON.Observable();
  84997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84998. this._engine = scene.getEngine();
  84999. this._maxSize = this._engine.getCaps().maxTextureSize;
  85000. this._scene.effectLayers.push(this);
  85001. // Generate Buffers
  85002. this._generateIndexBuffer();
  85003. this._genrateVertexBuffer();
  85004. }
  85005. Object.defineProperty(EffectLayer.prototype, "camera", {
  85006. /**
  85007. * Gets the camera attached to the layer.
  85008. */
  85009. get: function () {
  85010. return this._effectLayerOptions.camera;
  85011. },
  85012. enumerable: true,
  85013. configurable: true
  85014. });
  85015. /**
  85016. * Initializes the effect layer with the required options.
  85017. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85018. */
  85019. EffectLayer.prototype._init = function (options) {
  85020. // Adapt options
  85021. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85022. this._setMainTextureSize();
  85023. this._createMainTexture();
  85024. this._createTextureAndPostProcesses();
  85025. this._mergeEffect = this._createMergeEffect();
  85026. };
  85027. /**
  85028. * Generates the index buffer of the full screen quad blending to the main canvas.
  85029. */
  85030. EffectLayer.prototype._generateIndexBuffer = function () {
  85031. // Indices
  85032. var indices = [];
  85033. indices.push(0);
  85034. indices.push(1);
  85035. indices.push(2);
  85036. indices.push(0);
  85037. indices.push(2);
  85038. indices.push(3);
  85039. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85040. };
  85041. /**
  85042. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85043. */
  85044. EffectLayer.prototype._genrateVertexBuffer = function () {
  85045. // VBO
  85046. var vertices = [];
  85047. vertices.push(1, 1);
  85048. vertices.push(-1, 1);
  85049. vertices.push(-1, -1);
  85050. vertices.push(1, -1);
  85051. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85052. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85053. };
  85054. /**
  85055. * Sets the main texture desired size which is the closest power of two
  85056. * of the engine canvas size.
  85057. */
  85058. EffectLayer.prototype._setMainTextureSize = function () {
  85059. if (this._effectLayerOptions.mainTextureFixedSize) {
  85060. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85061. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85062. }
  85063. else {
  85064. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85065. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85066. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85067. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85068. }
  85069. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85070. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85071. };
  85072. /**
  85073. * Creates the main texture for the effect layer.
  85074. */
  85075. EffectLayer.prototype._createMainTexture = function () {
  85076. var _this = this;
  85077. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85078. width: this._mainTextureDesiredSize.width,
  85079. height: this._mainTextureDesiredSize.height
  85080. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85081. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85082. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85083. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85084. this._mainTexture.anisotropicFilteringLevel = 1;
  85085. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85086. this._mainTexture.renderParticles = false;
  85087. this._mainTexture.renderList = null;
  85088. this._mainTexture.ignoreCameraViewport = true;
  85089. // Custom render function
  85090. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85091. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85092. var index;
  85093. var engine = _this._scene.getEngine();
  85094. if (depthOnlySubMeshes.length) {
  85095. engine.setColorWrite(false);
  85096. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85097. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85098. }
  85099. engine.setColorWrite(true);
  85100. }
  85101. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85102. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85103. }
  85104. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85105. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85106. }
  85107. for (index = 0; index < transparentSubMeshes.length; index++) {
  85108. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85109. }
  85110. };
  85111. this._mainTexture.onClearObservable.add(function (engine) {
  85112. engine.clear(_this.neutralColor, true, true, true);
  85113. });
  85114. };
  85115. /**
  85116. * Checks for the readiness of the element composing the layer.
  85117. * @param subMesh the mesh to check for
  85118. * @param useInstances specify wether or not to use instances to render the mesh
  85119. * @param emissiveTexture the associated emissive texture used to generate the glow
  85120. * @return true if ready otherwise, false
  85121. */
  85122. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85123. var material = subMesh.getMaterial();
  85124. if (!material) {
  85125. return false;
  85126. }
  85127. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85128. return false;
  85129. }
  85130. var defines = [];
  85131. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85132. var mesh = subMesh.getMesh();
  85133. var uv1 = false;
  85134. var uv2 = false;
  85135. // Alpha test
  85136. if (material && material.needAlphaTesting()) {
  85137. var alphaTexture = material.getAlphaTestTexture();
  85138. if (alphaTexture) {
  85139. defines.push("#define ALPHATEST");
  85140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85141. alphaTexture.coordinatesIndex === 1) {
  85142. defines.push("#define DIFFUSEUV2");
  85143. uv2 = true;
  85144. }
  85145. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85146. defines.push("#define DIFFUSEUV1");
  85147. uv1 = true;
  85148. }
  85149. }
  85150. }
  85151. // Emissive
  85152. if (emissiveTexture) {
  85153. defines.push("#define EMISSIVE");
  85154. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85155. emissiveTexture.coordinatesIndex === 1) {
  85156. defines.push("#define EMISSIVEUV2");
  85157. uv2 = true;
  85158. }
  85159. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85160. defines.push("#define EMISSIVEUV1");
  85161. uv1 = true;
  85162. }
  85163. }
  85164. if (uv1) {
  85165. attribs.push(BABYLON.VertexBuffer.UVKind);
  85166. defines.push("#define UV1");
  85167. }
  85168. if (uv2) {
  85169. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85170. defines.push("#define UV2");
  85171. }
  85172. // Bones
  85173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85176. if (mesh.numBoneInfluencers > 4) {
  85177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85179. }
  85180. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85181. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85182. }
  85183. else {
  85184. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85185. }
  85186. // Instances
  85187. if (useInstances) {
  85188. defines.push("#define INSTANCES");
  85189. attribs.push("world0");
  85190. attribs.push("world1");
  85191. attribs.push("world2");
  85192. attribs.push("world3");
  85193. }
  85194. // Get correct effect
  85195. var join = defines.join("\n");
  85196. if (this._cachedDefines !== join) {
  85197. this._cachedDefines = join;
  85198. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85199. }
  85200. return this._effectLayerMapGenerationEffect.isReady();
  85201. };
  85202. /**
  85203. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85204. */
  85205. EffectLayer.prototype.render = function () {
  85206. var currentEffect = this._mergeEffect;
  85207. // Check
  85208. if (!currentEffect.isReady())
  85209. return;
  85210. for (var i = 0; i < this._postProcesses.length; i++) {
  85211. if (!this._postProcesses[i].isReady()) {
  85212. return;
  85213. }
  85214. }
  85215. var engine = this._scene.getEngine();
  85216. this.onBeforeComposeObservable.notifyObservers(this);
  85217. // Render
  85218. engine.enableEffect(currentEffect);
  85219. engine.setState(false);
  85220. // VBOs
  85221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85222. // Cache
  85223. var previousAlphaMode = engine.getAlphaMode();
  85224. // Go Blend.
  85225. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85226. // Blends the map on the main canvas.
  85227. this._internalRender(currentEffect);
  85228. // Restore Alpha
  85229. engine.setAlphaMode(previousAlphaMode);
  85230. this.onAfterComposeObservable.notifyObservers(this);
  85231. // Handle size changes.
  85232. var size = this._mainTexture.getSize();
  85233. this._setMainTextureSize();
  85234. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85235. // Recreate RTT and post processes on size change.
  85236. this.onSizeChangedObservable.notifyObservers(this);
  85237. this._disposeTextureAndPostProcesses();
  85238. this._createMainTexture();
  85239. this._createTextureAndPostProcesses();
  85240. }
  85241. };
  85242. /**
  85243. * Determine if a given mesh will be used in the current effect.
  85244. * @param mesh mesh to test
  85245. * @returns true if the mesh will be used
  85246. */
  85247. EffectLayer.prototype.hasMesh = function (mesh) {
  85248. return true;
  85249. };
  85250. /**
  85251. * Returns true if the layer contains information to display, otherwise false.
  85252. * @returns true if the glow layer should be rendered
  85253. */
  85254. EffectLayer.prototype.shouldRender = function () {
  85255. return this.isEnabled && this._shouldRender;
  85256. };
  85257. /**
  85258. * Returns true if the mesh should render, otherwise false.
  85259. * @param mesh The mesh to render
  85260. * @returns true if it should render otherwise false
  85261. */
  85262. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85263. return true;
  85264. };
  85265. /**
  85266. * Returns true if the mesh should render, otherwise false.
  85267. * @param mesh The mesh to render
  85268. * @returns true if it should render otherwise false
  85269. */
  85270. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85271. return true;
  85272. };
  85273. /**
  85274. * Renders the submesh passed in parameter to the generation map.
  85275. */
  85276. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85277. var _this = this;
  85278. if (!this.shouldRender()) {
  85279. return;
  85280. }
  85281. var material = subMesh.getMaterial();
  85282. var mesh = subMesh.getRenderingMesh();
  85283. var scene = this._scene;
  85284. var engine = scene.getEngine();
  85285. if (!material) {
  85286. return;
  85287. }
  85288. // Do not block in blend mode.
  85289. if (material.needAlphaBlendingForMesh(mesh)) {
  85290. return;
  85291. }
  85292. // Culling
  85293. engine.setState(material.backFaceCulling);
  85294. // Managing instances
  85295. var batch = mesh._getInstancesRenderList(subMesh._id);
  85296. if (batch.mustReturn) {
  85297. return;
  85298. }
  85299. // Early Exit per mesh
  85300. if (!this._shouldRenderMesh(mesh)) {
  85301. return;
  85302. }
  85303. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85304. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85305. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85306. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85307. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85308. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85309. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85310. // Alpha test
  85311. if (material && material.needAlphaTesting()) {
  85312. var alphaTexture = material.getAlphaTestTexture();
  85313. if (alphaTexture) {
  85314. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85315. var textureMatrix = alphaTexture.getTextureMatrix();
  85316. if (textureMatrix) {
  85317. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85318. }
  85319. }
  85320. }
  85321. // Glow emissive only
  85322. if (this._emissiveTextureAndColor.texture) {
  85323. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85324. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85325. }
  85326. // Bones
  85327. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85328. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85329. }
  85330. // Draw
  85331. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85332. }
  85333. else {
  85334. // Need to reset refresh rate of the shadowMap
  85335. this._mainTexture.resetRefreshCounter();
  85336. }
  85337. };
  85338. /**
  85339. * Rebuild the required buffers.
  85340. * @ignore Internal use only.
  85341. */
  85342. EffectLayer.prototype._rebuild = function () {
  85343. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85344. if (vb) {
  85345. vb._rebuild();
  85346. }
  85347. this._generateIndexBuffer();
  85348. };
  85349. /**
  85350. * Dispose only the render target textures and post process.
  85351. */
  85352. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85353. this._mainTexture.dispose();
  85354. for (var i = 0; i < this._postProcesses.length; i++) {
  85355. if (this._postProcesses[i]) {
  85356. this._postProcesses[i].dispose();
  85357. }
  85358. }
  85359. this._postProcesses = [];
  85360. for (var i = 0; i < this._textures.length; i++) {
  85361. if (this._textures[i]) {
  85362. this._textures[i].dispose();
  85363. }
  85364. }
  85365. this._textures = [];
  85366. };
  85367. /**
  85368. * Dispose the highlight layer and free resources.
  85369. */
  85370. EffectLayer.prototype.dispose = function () {
  85371. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85372. if (vertexBuffer) {
  85373. vertexBuffer.dispose();
  85374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85375. }
  85376. if (this._indexBuffer) {
  85377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85378. this._indexBuffer = null;
  85379. }
  85380. // Clean textures and post processes
  85381. this._disposeTextureAndPostProcesses();
  85382. // Remove from scene
  85383. var index = this._scene.effectLayers.indexOf(this, 0);
  85384. if (index > -1) {
  85385. this._scene.effectLayers.splice(index, 1);
  85386. }
  85387. // Callback
  85388. this.onDisposeObservable.notifyObservers(this);
  85389. this.onDisposeObservable.clear();
  85390. this.onBeforeRenderMainTextureObservable.clear();
  85391. this.onBeforeComposeObservable.clear();
  85392. this.onAfterComposeObservable.clear();
  85393. this.onSizeChangedObservable.clear();
  85394. };
  85395. return EffectLayer;
  85396. }());
  85397. BABYLON.EffectLayer = EffectLayer;
  85398. })(BABYLON || (BABYLON = {}));
  85399. //# sourceMappingURL=babylon.effectLayer.js.map
  85400. var BABYLON;
  85401. (function (BABYLON) {
  85402. /**
  85403. * Special Glow Blur post process only blurring the alpha channel
  85404. * It enforces keeping the most luminous color in the color channel.
  85405. */
  85406. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85407. __extends(GlowBlurPostProcess, _super);
  85408. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85410. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85411. _this.direction = direction;
  85412. _this.kernel = kernel;
  85413. _this.onApplyObservable.add(function (effect) {
  85414. effect.setFloat2("screenSize", _this.width, _this.height);
  85415. effect.setVector2("direction", _this.direction);
  85416. effect.setFloat("blurWidth", _this.kernel);
  85417. });
  85418. return _this;
  85419. }
  85420. return GlowBlurPostProcess;
  85421. }(BABYLON.PostProcess));
  85422. /**
  85423. * The highlight layer Helps adding a glow effect around a mesh.
  85424. *
  85425. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85426. * glowy meshes to your scene.
  85427. *
  85428. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85429. */
  85430. var HighlightLayer = /** @class */ (function (_super) {
  85431. __extends(HighlightLayer, _super);
  85432. /**
  85433. * Instantiates a new highlight Layer and references it to the scene..
  85434. * @param name The name of the layer
  85435. * @param scene The scene to use the layer in
  85436. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85437. */
  85438. function HighlightLayer(name, scene, options) {
  85439. var _this = _super.call(this, name, scene) || this;
  85440. _this.name = name;
  85441. /**
  85442. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85443. */
  85444. _this.innerGlow = true;
  85445. /**
  85446. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85447. */
  85448. _this.outerGlow = true;
  85449. /**
  85450. * An event triggered when the highlight layer is being blurred.
  85451. */
  85452. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85453. /**
  85454. * An event triggered when the highlight layer has been blurred.
  85455. */
  85456. _this.onAfterBlurObservable = new BABYLON.Observable();
  85457. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85458. _this._meshes = {};
  85459. _this._excludedMeshes = {};
  85460. _this.neutralColor = HighlightLayer.NeutralColor;
  85461. // Warn on stencil
  85462. if (!_this._engine.isStencilEnable) {
  85463. 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 }");
  85464. }
  85465. // Adapt options
  85466. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85467. // Initialize the layer
  85468. _this._init({
  85469. alphaBlendingMode: _this._options.alphaBlendingMode,
  85470. camera: _this._options.camera,
  85471. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85472. mainTextureRatio: _this._options.mainTextureRatio
  85473. });
  85474. // Do not render as long as no meshes have been added
  85475. _this._shouldRender = false;
  85476. return _this;
  85477. }
  85478. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85479. /**
  85480. * Gets the horizontal size of the blur.
  85481. */
  85482. get: function () {
  85483. return this._horizontalBlurPostprocess.kernel;
  85484. },
  85485. /**
  85486. * Specifies the horizontal size of the blur.
  85487. */
  85488. set: function (value) {
  85489. this._horizontalBlurPostprocess.kernel = value;
  85490. },
  85491. enumerable: true,
  85492. configurable: true
  85493. });
  85494. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85495. /**
  85496. * Gets the vertical size of the blur.
  85497. */
  85498. get: function () {
  85499. return this._verticalBlurPostprocess.kernel;
  85500. },
  85501. /**
  85502. * Specifies the vertical size of the blur.
  85503. */
  85504. set: function (value) {
  85505. this._verticalBlurPostprocess.kernel = value;
  85506. },
  85507. enumerable: true,
  85508. configurable: true
  85509. });
  85510. /**
  85511. * Get the effect name of the layer.
  85512. * @return The effect name
  85513. */
  85514. HighlightLayer.prototype.getEffectName = function () {
  85515. return HighlightLayer.EffectName;
  85516. };
  85517. /**
  85518. * Create the merge effect. This is the shader use to blit the information back
  85519. * to the main canvas at the end of the scene rendering.
  85520. */
  85521. HighlightLayer.prototype._createMergeEffect = function () {
  85522. // Effect
  85523. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85524. };
  85525. /**
  85526. * Creates the render target textures and post processes used in the highlight layer.
  85527. */
  85528. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85529. var _this = this;
  85530. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85531. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85532. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85533. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85534. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85535. width: blurTextureWidth,
  85536. height: blurTextureHeight
  85537. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85538. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85539. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85540. this._blurTexture.anisotropicFilteringLevel = 16;
  85541. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85542. this._blurTexture.renderParticles = false;
  85543. this._blurTexture.ignoreCameraViewport = true;
  85544. this._textures = [this._blurTexture];
  85545. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85546. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85547. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85548. effect.setTexture("textureSampler", _this._mainTexture);
  85549. });
  85550. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85551. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85552. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85553. });
  85554. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85555. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85556. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85557. });
  85558. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85559. }
  85560. else {
  85561. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85562. width: blurTextureWidth,
  85563. height: blurTextureHeight
  85564. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85565. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85566. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85567. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85568. effect.setTexture("textureSampler", _this._mainTexture);
  85569. });
  85570. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85571. width: blurTextureWidth,
  85572. height: blurTextureHeight
  85573. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85574. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85575. }
  85576. this._mainTexture.onAfterUnbindObservable.add(function () {
  85577. _this.onBeforeBlurObservable.notifyObservers(_this);
  85578. var internalTexture = _this._blurTexture.getInternalTexture();
  85579. if (internalTexture) {
  85580. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85581. }
  85582. _this.onAfterBlurObservable.notifyObservers(_this);
  85583. });
  85584. // Prevent autoClear.
  85585. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85586. };
  85587. /**
  85588. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85589. */
  85590. HighlightLayer.prototype.needStencil = function () {
  85591. return true;
  85592. };
  85593. /**
  85594. * Checks for the readiness of the element composing the layer.
  85595. * @param subMesh the mesh to check for
  85596. * @param useInstances specify wether or not to use instances to render the mesh
  85597. * @param emissiveTexture the associated emissive texture used to generate the glow
  85598. * @return true if ready otherwise, false
  85599. */
  85600. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85601. var material = subMesh.getMaterial();
  85602. var mesh = subMesh.getRenderingMesh();
  85603. if (!material || !mesh || !this._meshes) {
  85604. return false;
  85605. }
  85606. var emissiveTexture = null;
  85607. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85608. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85609. emissiveTexture = material.emissiveTexture;
  85610. }
  85611. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85612. };
  85613. /**
  85614. * Implementation specific of rendering the generating effect on the main canvas.
  85615. * @param effect The effect used to render through
  85616. */
  85617. HighlightLayer.prototype._internalRender = function (effect) {
  85618. // Texture
  85619. effect.setTexture("textureSampler", this._blurTexture);
  85620. // Cache
  85621. var engine = this._engine;
  85622. var previousStencilBuffer = engine.getStencilBuffer();
  85623. var previousStencilFunction = engine.getStencilFunction();
  85624. var previousStencilMask = engine.getStencilMask();
  85625. var previousStencilOperationPass = engine.getStencilOperationPass();
  85626. var previousStencilOperationFail = engine.getStencilOperationFail();
  85627. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85628. var previousStencilReference = engine.getStencilFunctionReference();
  85629. // Stencil operations
  85630. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85631. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85632. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85633. // Draw order
  85634. engine.setStencilMask(0x00);
  85635. engine.setStencilBuffer(true);
  85636. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85637. // 2 passes inner outer
  85638. if (this.outerGlow) {
  85639. effect.setFloat("offset", 0);
  85640. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85642. }
  85643. if (this.innerGlow) {
  85644. effect.setFloat("offset", 1);
  85645. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85647. }
  85648. // Restore Cache
  85649. engine.setStencilFunction(previousStencilFunction);
  85650. engine.setStencilMask(previousStencilMask);
  85651. engine.setStencilBuffer(previousStencilBuffer);
  85652. engine.setStencilOperationPass(previousStencilOperationPass);
  85653. engine.setStencilOperationFail(previousStencilOperationFail);
  85654. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85655. engine.setStencilFunctionReference(previousStencilReference);
  85656. };
  85657. /**
  85658. * Returns true if the layer contains information to display, otherwise false.
  85659. */
  85660. HighlightLayer.prototype.shouldRender = function () {
  85661. if (_super.prototype.shouldRender.call(this)) {
  85662. return this._meshes ? true : false;
  85663. }
  85664. return false;
  85665. };
  85666. /**
  85667. * Returns true if the mesh should render, otherwise false.
  85668. * @param mesh The mesh to render
  85669. * @returns true if it should render otherwise false
  85670. */
  85671. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85672. // Excluded Mesh
  85673. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85674. return false;
  85675. }
  85676. ;
  85677. return true;
  85678. };
  85679. /**
  85680. * Sets the required values for both the emissive texture and and the main color.
  85681. */
  85682. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85683. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85684. if (highlightLayerMesh) {
  85685. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85686. }
  85687. else {
  85688. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85689. }
  85690. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85691. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85692. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85693. }
  85694. else {
  85695. this._emissiveTextureAndColor.texture = null;
  85696. }
  85697. };
  85698. /**
  85699. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85700. * @param mesh The mesh to exclude from the highlight layer
  85701. */
  85702. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85703. if (!this._excludedMeshes) {
  85704. return;
  85705. }
  85706. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85707. if (!meshExcluded) {
  85708. this._excludedMeshes[mesh.uniqueId] = {
  85709. mesh: mesh,
  85710. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85711. mesh.getEngine().setStencilBuffer(false);
  85712. }),
  85713. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85714. mesh.getEngine().setStencilBuffer(true);
  85715. }),
  85716. };
  85717. }
  85718. };
  85719. /**
  85720. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85721. * @param mesh The mesh to highlight
  85722. */
  85723. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85724. if (!this._excludedMeshes) {
  85725. return;
  85726. }
  85727. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85728. if (meshExcluded) {
  85729. if (meshExcluded.beforeRender) {
  85730. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85731. }
  85732. if (meshExcluded.afterRender) {
  85733. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85734. }
  85735. }
  85736. this._excludedMeshes[mesh.uniqueId] = null;
  85737. };
  85738. /**
  85739. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85740. * @param mesh mesh to test
  85741. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85742. */
  85743. HighlightLayer.prototype.hasMesh = function (mesh) {
  85744. if (!this._meshes) {
  85745. return false;
  85746. }
  85747. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85748. };
  85749. /**
  85750. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85751. * @param mesh The mesh to highlight
  85752. * @param color The color of the highlight
  85753. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85754. */
  85755. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85756. var _this = this;
  85757. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85758. if (!this._meshes) {
  85759. return;
  85760. }
  85761. var meshHighlight = this._meshes[mesh.uniqueId];
  85762. if (meshHighlight) {
  85763. meshHighlight.color = color;
  85764. }
  85765. else {
  85766. this._meshes[mesh.uniqueId] = {
  85767. mesh: mesh,
  85768. color: color,
  85769. // Lambda required for capture due to Observable this context
  85770. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85771. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85772. _this._defaultStencilReference(mesh);
  85773. }
  85774. else {
  85775. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85776. }
  85777. }),
  85778. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85779. glowEmissiveOnly: glowEmissiveOnly
  85780. };
  85781. }
  85782. this._shouldRender = true;
  85783. };
  85784. /**
  85785. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85786. * @param mesh The mesh to highlight
  85787. */
  85788. HighlightLayer.prototype.removeMesh = function (mesh) {
  85789. if (!this._meshes) {
  85790. return;
  85791. }
  85792. var meshHighlight = this._meshes[mesh.uniqueId];
  85793. if (meshHighlight) {
  85794. if (meshHighlight.observerHighlight) {
  85795. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85796. }
  85797. if (meshHighlight.observerDefault) {
  85798. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85799. }
  85800. delete this._meshes[mesh.uniqueId];
  85801. }
  85802. this._shouldRender = false;
  85803. for (var meshHighlightToCheck in this._meshes) {
  85804. if (this._meshes[meshHighlightToCheck]) {
  85805. this._shouldRender = true;
  85806. break;
  85807. }
  85808. }
  85809. };
  85810. /**
  85811. * Force the stencil to the normal expected value for none glowing parts
  85812. */
  85813. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85814. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85815. };
  85816. /**
  85817. * Free any resources and references associated to a mesh.
  85818. * Internal use
  85819. * @param mesh The mesh to free.
  85820. */
  85821. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85822. this.removeMesh(mesh);
  85823. this.removeExcludedMesh(mesh);
  85824. };
  85825. /**
  85826. * Dispose the highlight layer and free resources.
  85827. */
  85828. HighlightLayer.prototype.dispose = function () {
  85829. if (this._meshes) {
  85830. // Clean mesh references
  85831. for (var id in this._meshes) {
  85832. var meshHighlight = this._meshes[id];
  85833. if (meshHighlight && meshHighlight.mesh) {
  85834. if (meshHighlight.observerHighlight) {
  85835. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85836. }
  85837. if (meshHighlight.observerDefault) {
  85838. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85839. }
  85840. }
  85841. }
  85842. this._meshes = null;
  85843. }
  85844. if (this._excludedMeshes) {
  85845. for (var id in this._excludedMeshes) {
  85846. var meshHighlight = this._excludedMeshes[id];
  85847. if (meshHighlight) {
  85848. if (meshHighlight.beforeRender) {
  85849. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85850. }
  85851. if (meshHighlight.afterRender) {
  85852. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85853. }
  85854. }
  85855. }
  85856. this._excludedMeshes = null;
  85857. }
  85858. _super.prototype.dispose.call(this);
  85859. };
  85860. /**
  85861. * Effect Name of the highlight layer.
  85862. */
  85863. HighlightLayer.EffectName = "HighlightLayer";
  85864. /**
  85865. * The neutral color used during the preparation of the glow effect.
  85866. * This is black by default as the blend operation is a blend operation.
  85867. */
  85868. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85869. /**
  85870. * Stencil value used for glowing meshes.
  85871. */
  85872. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85873. /**
  85874. * Stencil value used for the other meshes in the scene.
  85875. */
  85876. HighlightLayer.NormalMeshStencilReference = 0x01;
  85877. return HighlightLayer;
  85878. }(BABYLON.EffectLayer));
  85879. BABYLON.HighlightLayer = HighlightLayer;
  85880. })(BABYLON || (BABYLON = {}));
  85881. //# sourceMappingURL=babylon.highlightLayer.js.map
  85882. var BABYLON;
  85883. (function (BABYLON) {
  85884. /**
  85885. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85886. *
  85887. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85888. * glowy meshes to your scene.
  85889. *
  85890. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85891. */
  85892. var GlowLayer = /** @class */ (function (_super) {
  85893. __extends(GlowLayer, _super);
  85894. /**
  85895. * Instantiates a new glow Layer and references it to the scene.
  85896. * @param name The name of the layer
  85897. * @param scene The scene to use the layer in
  85898. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85899. */
  85900. function GlowLayer(name, scene, options) {
  85901. var _this = _super.call(this, name, scene) || this;
  85902. _this.name = name;
  85903. _this._intensity = 1.0;
  85904. _this._includedOnlyMeshes = [];
  85905. _this._excludedMeshes = [];
  85906. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85907. // Adapt options
  85908. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85909. // Initialize the layer
  85910. _this._init({
  85911. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85912. camera: _this._options.camera,
  85913. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85914. mainTextureRatio: _this._options.mainTextureRatio
  85915. });
  85916. return _this;
  85917. }
  85918. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85919. /**
  85920. * Gets the kernel size of the blur.
  85921. */
  85922. get: function () {
  85923. return this._horizontalBlurPostprocess1.kernel;
  85924. },
  85925. /**
  85926. * Sets the kernel size of the blur.
  85927. */
  85928. set: function (value) {
  85929. this._horizontalBlurPostprocess1.kernel = value;
  85930. this._verticalBlurPostprocess1.kernel = value;
  85931. this._horizontalBlurPostprocess2.kernel = value;
  85932. this._verticalBlurPostprocess2.kernel = value;
  85933. },
  85934. enumerable: true,
  85935. configurable: true
  85936. });
  85937. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85938. /**
  85939. * Gets the glow intensity.
  85940. */
  85941. get: function () {
  85942. return this._intensity;
  85943. },
  85944. /**
  85945. * Sets the glow intensity.
  85946. */
  85947. set: function (value) {
  85948. this._intensity = value;
  85949. },
  85950. enumerable: true,
  85951. configurable: true
  85952. });
  85953. /**
  85954. * Get the effect name of the layer.
  85955. * @return The effect name
  85956. */
  85957. GlowLayer.prototype.getEffectName = function () {
  85958. return GlowLayer.EffectName;
  85959. };
  85960. /**
  85961. * Create the merge effect. This is the shader use to blit the information back
  85962. * to the main canvas at the end of the scene rendering.
  85963. */
  85964. GlowLayer.prototype._createMergeEffect = function () {
  85965. // Effect
  85966. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85967. };
  85968. /**
  85969. * Creates the render target textures and post processes used in the glow layer.
  85970. */
  85971. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85972. var _this = this;
  85973. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85974. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85975. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85976. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85977. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85978. width: blurTextureWidth,
  85979. height: blurTextureHeight
  85980. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85981. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85982. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85983. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85984. this._blurTexture1.renderParticles = false;
  85985. this._blurTexture1.ignoreCameraViewport = true;
  85986. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85987. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85988. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85989. width: blurTextureWidth2,
  85990. height: blurTextureHeight2
  85991. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85992. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85993. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85994. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85995. this._blurTexture2.renderParticles = false;
  85996. this._blurTexture2.ignoreCameraViewport = true;
  85997. this._textures = [this._blurTexture1, this._blurTexture2];
  85998. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85999. width: blurTextureWidth,
  86000. height: blurTextureHeight
  86001. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86002. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86003. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86004. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86005. effect.setTexture("textureSampler", _this._mainTexture);
  86006. });
  86007. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86008. width: blurTextureWidth,
  86009. height: blurTextureHeight
  86010. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86011. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86012. width: blurTextureWidth2,
  86013. height: blurTextureHeight2
  86014. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86015. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86016. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86017. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86018. effect.setTexture("textureSampler", _this._blurTexture1);
  86019. });
  86020. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86021. width: blurTextureWidth2,
  86022. height: blurTextureHeight2
  86023. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86024. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86025. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86026. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86027. this._mainTexture.samples = this._options.mainTextureSamples;
  86028. this._mainTexture.onAfterUnbindObservable.add(function () {
  86029. var internalTexture = _this._blurTexture1.getInternalTexture();
  86030. if (internalTexture) {
  86031. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86032. internalTexture = _this._blurTexture2.getInternalTexture();
  86033. if (internalTexture) {
  86034. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86035. }
  86036. }
  86037. });
  86038. // Prevent autoClear.
  86039. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86040. };
  86041. /**
  86042. * Checks for the readiness of the element composing the layer.
  86043. * @param subMesh the mesh to check for
  86044. * @param useInstances specify wether or not to use instances to render the mesh
  86045. * @param emissiveTexture the associated emissive texture used to generate the glow
  86046. * @return true if ready otherwise, false
  86047. */
  86048. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86049. var material = subMesh.getMaterial();
  86050. var mesh = subMesh.getRenderingMesh();
  86051. if (!material || !mesh) {
  86052. return false;
  86053. }
  86054. var emissiveTexture = material.emissiveTexture;
  86055. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86056. };
  86057. /**
  86058. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86059. */
  86060. GlowLayer.prototype.needStencil = function () {
  86061. return false;
  86062. };
  86063. /**
  86064. * Implementation specific of rendering the generating effect on the main canvas.
  86065. * @param effect The effect used to render through
  86066. */
  86067. GlowLayer.prototype._internalRender = function (effect) {
  86068. // Texture
  86069. effect.setTexture("textureSampler", this._blurTexture1);
  86070. effect.setTexture("textureSampler2", this._blurTexture2);
  86071. effect.setFloat("offset", this._intensity);
  86072. // Cache
  86073. var engine = this._engine;
  86074. var previousStencilBuffer = engine.getStencilBuffer();
  86075. // Draw order
  86076. engine.setStencilBuffer(false);
  86077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86078. // Draw order
  86079. engine.setStencilBuffer(previousStencilBuffer);
  86080. };
  86081. /**
  86082. * Sets the required values for both the emissive texture and and the main color.
  86083. */
  86084. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86085. var textureLevel = 1.0;
  86086. if (this.customEmissiveTextureSelector) {
  86087. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86088. }
  86089. else {
  86090. if (material) {
  86091. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86092. if (this._emissiveTextureAndColor.texture) {
  86093. textureLevel = this._emissiveTextureAndColor.texture.level;
  86094. }
  86095. }
  86096. else {
  86097. this._emissiveTextureAndColor.texture = null;
  86098. }
  86099. }
  86100. if (this.customEmissiveColorSelector) {
  86101. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86102. }
  86103. else {
  86104. if (material.emissiveColor) {
  86105. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86106. }
  86107. else {
  86108. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86109. }
  86110. }
  86111. };
  86112. /**
  86113. * Returns true if the mesh should render, otherwise false.
  86114. * @param mesh The mesh to render
  86115. * @returns true if it should render otherwise false
  86116. */
  86117. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86118. return this.hasMesh(mesh);
  86119. };
  86120. /**
  86121. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86122. * @param mesh The mesh to exclude from the glow layer
  86123. */
  86124. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86125. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86126. this._excludedMeshes.push(mesh.uniqueId);
  86127. }
  86128. };
  86129. /**
  86130. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86131. * @param mesh The mesh to remove
  86132. */
  86133. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86134. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86135. if (index !== -1) {
  86136. this._excludedMeshes.splice(index, 1);
  86137. }
  86138. };
  86139. /**
  86140. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86141. * @param mesh The mesh to include in the glow layer
  86142. */
  86143. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86144. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86145. this._includedOnlyMeshes.push(mesh.uniqueId);
  86146. }
  86147. };
  86148. /**
  86149. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86150. * @param mesh The mesh to remove
  86151. */
  86152. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86153. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86154. if (index !== -1) {
  86155. this._includedOnlyMeshes.splice(index, 1);
  86156. }
  86157. };
  86158. /**
  86159. * Determine if a given mesh will be used in the glow layer
  86160. * @param mesh The mesh to test
  86161. * @returns true if the mesh will be highlighted by the current glow layer
  86162. */
  86163. GlowLayer.prototype.hasMesh = function (mesh) {
  86164. // Included Mesh
  86165. if (this._includedOnlyMeshes.length) {
  86166. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86167. }
  86168. ;
  86169. // Excluded Mesh
  86170. if (this._excludedMeshes.length) {
  86171. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86172. }
  86173. ;
  86174. return true;
  86175. };
  86176. /**
  86177. * Free any resources and references associated to a mesh.
  86178. * Internal use
  86179. * @param mesh The mesh to free.
  86180. */
  86181. GlowLayer.prototype._disposeMesh = function (mesh) {
  86182. this.removeIncludedOnlyMesh(mesh);
  86183. this.removeExcludedMesh(mesh);
  86184. };
  86185. /**
  86186. * Effect Name of the layer.
  86187. */
  86188. GlowLayer.EffectName = "GlowLayer";
  86189. /**
  86190. * The default blur kernel size used for the glow.
  86191. */
  86192. GlowLayer.DefaultBlurKernelSize = 32;
  86193. /**
  86194. * The default texture size ratio used for the glow.
  86195. */
  86196. GlowLayer.DefaultTextureRatio = 0.5;
  86197. return GlowLayer;
  86198. }(BABYLON.EffectLayer));
  86199. BABYLON.GlowLayer = GlowLayer;
  86200. })(BABYLON || (BABYLON = {}));
  86201. //# sourceMappingURL=babylon.glowLayer.js.map
  86202. var BABYLON;
  86203. (function (BABYLON) {
  86204. /**
  86205. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86206. */
  86207. var AssetTaskState;
  86208. (function (AssetTaskState) {
  86209. /**
  86210. * Initialization
  86211. */
  86212. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86213. /**
  86214. * Running
  86215. */
  86216. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86217. /**
  86218. * Done
  86219. */
  86220. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86221. /**
  86222. * Error
  86223. */
  86224. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86225. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86226. /**
  86227. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86228. */
  86229. var AbstractAssetTask = /** @class */ (function () {
  86230. /**
  86231. * Creates a new {BABYLON.AssetsManager}
  86232. * @param name defines the name of the task
  86233. */
  86234. function AbstractAssetTask(
  86235. /**
  86236. * Task name
  86237. */ name) {
  86238. this.name = name;
  86239. this._isCompleted = false;
  86240. this._taskState = AssetTaskState.INIT;
  86241. }
  86242. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86243. /**
  86244. * Get if the task is completed
  86245. */
  86246. get: function () {
  86247. return this._isCompleted;
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86253. /**
  86254. * Gets the current state of the task
  86255. */
  86256. get: function () {
  86257. return this._taskState;
  86258. },
  86259. enumerable: true,
  86260. configurable: true
  86261. });
  86262. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86263. /**
  86264. * Gets the current error object (if task is in error)
  86265. */
  86266. get: function () {
  86267. return this._errorObject;
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. /**
  86273. * Internal only
  86274. * @ignore
  86275. */
  86276. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86277. if (this._errorObject) {
  86278. return;
  86279. }
  86280. this._errorObject = {
  86281. message: message,
  86282. exception: exception
  86283. };
  86284. };
  86285. /**
  86286. * Execute the current task
  86287. * @param scene defines the scene where you want your assets to be loaded
  86288. * @param onSuccess is a callback called when the task is successfully executed
  86289. * @param onError is a callback called if an error occurs
  86290. */
  86291. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86292. var _this = this;
  86293. this._taskState = AssetTaskState.RUNNING;
  86294. this.runTask(scene, function () {
  86295. _this.onDoneCallback(onSuccess, onError);
  86296. }, function (msg, exception) {
  86297. _this.onErrorCallback(onError, msg, exception);
  86298. });
  86299. };
  86300. /**
  86301. * Execute the current task
  86302. * @param scene defines the scene where you want your assets to be loaded
  86303. * @param onSuccess is a callback called when the task is successfully executed
  86304. * @param onError is a callback called if an error occurs
  86305. */
  86306. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86307. throw new Error("runTask is not implemented");
  86308. };
  86309. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86310. this._taskState = AssetTaskState.ERROR;
  86311. this._errorObject = {
  86312. message: message,
  86313. exception: exception
  86314. };
  86315. if (this.onError) {
  86316. this.onError(this, message, exception);
  86317. }
  86318. onError();
  86319. };
  86320. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86321. try {
  86322. this._taskState = AssetTaskState.DONE;
  86323. this._isCompleted = true;
  86324. if (this.onSuccess) {
  86325. this.onSuccess(this);
  86326. }
  86327. onSuccess();
  86328. }
  86329. catch (e) {
  86330. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86331. }
  86332. };
  86333. return AbstractAssetTask;
  86334. }());
  86335. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86336. /**
  86337. * Class used to share progress information about assets loading
  86338. */
  86339. var AssetsProgressEvent = /** @class */ (function () {
  86340. /**
  86341. * Creates a {BABYLON.AssetsProgressEvent}
  86342. * @param remainingCount defines the number of remaining tasks to process
  86343. * @param totalCount defines the total number of tasks
  86344. * @param task defines the task that was just processed
  86345. */
  86346. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86347. this.remainingCount = remainingCount;
  86348. this.totalCount = totalCount;
  86349. this.task = task;
  86350. }
  86351. return AssetsProgressEvent;
  86352. }());
  86353. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86354. /**
  86355. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86356. */
  86357. var MeshAssetTask = /** @class */ (function (_super) {
  86358. __extends(MeshAssetTask, _super);
  86359. /**
  86360. * Creates a new {BABYLON.MeshAssetTask}
  86361. * @param name defines the name of the task
  86362. * @param meshesNames defines the list of mesh's names you want to load
  86363. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86364. * @param sceneFilename defines the filename of the scene to load from
  86365. */
  86366. function MeshAssetTask(
  86367. /**
  86368. * Defines the name of the task
  86369. */
  86370. name,
  86371. /**
  86372. * Defines the list of mesh's names you want to load
  86373. */
  86374. meshesNames,
  86375. /**
  86376. * Defines the root url to use as a base to load your meshes and associated resources
  86377. */
  86378. rootUrl,
  86379. /**
  86380. * Defines the filename of the scene to load from
  86381. */
  86382. sceneFilename) {
  86383. var _this = _super.call(this, name) || this;
  86384. _this.name = name;
  86385. _this.meshesNames = meshesNames;
  86386. _this.rootUrl = rootUrl;
  86387. _this.sceneFilename = sceneFilename;
  86388. return _this;
  86389. }
  86390. /**
  86391. * Execute the current task
  86392. * @param scene defines the scene where you want your assets to be loaded
  86393. * @param onSuccess is a callback called when the task is successfully executed
  86394. * @param onError is a callback called if an error occurs
  86395. */
  86396. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86397. var _this = this;
  86398. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86399. _this.loadedMeshes = meshes;
  86400. _this.loadedParticleSystems = particleSystems;
  86401. _this.loadedSkeletons = skeletons;
  86402. onSuccess();
  86403. }, null, function (scene, message, exception) {
  86404. onError(message, exception);
  86405. });
  86406. };
  86407. return MeshAssetTask;
  86408. }(AbstractAssetTask));
  86409. BABYLON.MeshAssetTask = MeshAssetTask;
  86410. /**
  86411. * Define a task used by {BABYLON.AssetsManager} to load text content
  86412. */
  86413. var TextFileAssetTask = /** @class */ (function (_super) {
  86414. __extends(TextFileAssetTask, _super);
  86415. /**
  86416. * Creates a new TextFileAssetTask object
  86417. * @param name defines the name of the task
  86418. * @param url defines the location of the file to load
  86419. */
  86420. function TextFileAssetTask(
  86421. /**
  86422. * Defines the name of the task
  86423. */
  86424. name,
  86425. /**
  86426. * Defines the location of the file to load
  86427. */
  86428. url) {
  86429. var _this = _super.call(this, name) || this;
  86430. _this.name = name;
  86431. _this.url = url;
  86432. return _this;
  86433. }
  86434. /**
  86435. * Execute the current task
  86436. * @param scene defines the scene where you want your assets to be loaded
  86437. * @param onSuccess is a callback called when the task is successfully executed
  86438. * @param onError is a callback called if an error occurs
  86439. */
  86440. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86441. var _this = this;
  86442. scene._loadFile(this.url, function (data) {
  86443. _this.text = data;
  86444. onSuccess();
  86445. }, undefined, false, false, function (request, exception) {
  86446. if (request) {
  86447. onError(request.status + " " + request.statusText, exception);
  86448. }
  86449. });
  86450. };
  86451. return TextFileAssetTask;
  86452. }(AbstractAssetTask));
  86453. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86454. /**
  86455. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86456. */
  86457. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86458. __extends(BinaryFileAssetTask, _super);
  86459. /**
  86460. * Creates a new BinaryFileAssetTask object
  86461. * @param name defines the name of the new task
  86462. * @param url defines the location of the file to load
  86463. */
  86464. function BinaryFileAssetTask(
  86465. /**
  86466. * Defines the name of the task
  86467. */
  86468. name,
  86469. /**
  86470. * Defines the location of the file to load
  86471. */
  86472. url) {
  86473. var _this = _super.call(this, name) || this;
  86474. _this.name = name;
  86475. _this.url = url;
  86476. return _this;
  86477. }
  86478. /**
  86479. * Execute the current task
  86480. * @param scene defines the scene where you want your assets to be loaded
  86481. * @param onSuccess is a callback called when the task is successfully executed
  86482. * @param onError is a callback called if an error occurs
  86483. */
  86484. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86485. var _this = this;
  86486. scene._loadFile(this.url, function (data) {
  86487. _this.data = data;
  86488. onSuccess();
  86489. }, undefined, true, true, function (request, exception) {
  86490. if (request) {
  86491. onError(request.status + " " + request.statusText, exception);
  86492. }
  86493. });
  86494. };
  86495. return BinaryFileAssetTask;
  86496. }(AbstractAssetTask));
  86497. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86498. /**
  86499. * Define a task used by {BABYLON.AssetsManager} to load images
  86500. */
  86501. var ImageAssetTask = /** @class */ (function (_super) {
  86502. __extends(ImageAssetTask, _super);
  86503. /**
  86504. * Creates a new ImageAssetTask
  86505. * @param name defines the name of the task
  86506. * @param url defines the location of the image to load
  86507. */
  86508. function ImageAssetTask(
  86509. /**
  86510. * Defines the name of the task
  86511. */
  86512. name,
  86513. /**
  86514. * Defines the location of the image to load
  86515. */
  86516. url) {
  86517. var _this = _super.call(this, name) || this;
  86518. _this.name = name;
  86519. _this.url = url;
  86520. return _this;
  86521. }
  86522. /**
  86523. * Execute the current task
  86524. * @param scene defines the scene where you want your assets to be loaded
  86525. * @param onSuccess is a callback called when the task is successfully executed
  86526. * @param onError is a callback called if an error occurs
  86527. */
  86528. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86529. var _this = this;
  86530. var img = new Image();
  86531. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86532. img.onload = function () {
  86533. _this.image = img;
  86534. onSuccess();
  86535. };
  86536. img.onerror = function (err) {
  86537. onError("Error loading image", err);
  86538. };
  86539. img.src = this.url;
  86540. };
  86541. return ImageAssetTask;
  86542. }(AbstractAssetTask));
  86543. BABYLON.ImageAssetTask = ImageAssetTask;
  86544. /**
  86545. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86546. */
  86547. var TextureAssetTask = /** @class */ (function (_super) {
  86548. __extends(TextureAssetTask, _super);
  86549. /**
  86550. * Creates a new TextureAssetTask object
  86551. * @param name defines the name of the task
  86552. * @param url defines the location of the file to load
  86553. * @param noMipmap defines if mipmap should not be generated (default is false)
  86554. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86555. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86556. */
  86557. function TextureAssetTask(
  86558. /**
  86559. * Defines the name of the task
  86560. */
  86561. name,
  86562. /**
  86563. * Defines the location of the file to load
  86564. */
  86565. url,
  86566. /**
  86567. * Defines if mipmap should not be generated (default is false)
  86568. */
  86569. noMipmap,
  86570. /**
  86571. * Defines if texture must be inverted on Y axis (default is false)
  86572. */
  86573. invertY,
  86574. /**
  86575. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86576. */
  86577. samplingMode) {
  86578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86579. var _this = _super.call(this, name) || this;
  86580. _this.name = name;
  86581. _this.url = url;
  86582. _this.noMipmap = noMipmap;
  86583. _this.invertY = invertY;
  86584. _this.samplingMode = samplingMode;
  86585. return _this;
  86586. }
  86587. /**
  86588. * Execute the current task
  86589. * @param scene defines the scene where you want your assets to be loaded
  86590. * @param onSuccess is a callback called when the task is successfully executed
  86591. * @param onError is a callback called if an error occurs
  86592. */
  86593. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86594. var onload = function () {
  86595. onSuccess();
  86596. };
  86597. var onerror = function (message, exception) {
  86598. onError(message, exception);
  86599. };
  86600. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86601. };
  86602. return TextureAssetTask;
  86603. }(AbstractAssetTask));
  86604. BABYLON.TextureAssetTask = TextureAssetTask;
  86605. /**
  86606. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86607. */
  86608. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86609. __extends(CubeTextureAssetTask, _super);
  86610. /**
  86611. * Creates a new CubeTextureAssetTask
  86612. * @param name defines the name of the task
  86613. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86614. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86615. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86616. * @param files defines the explicit list of files (undefined by default)
  86617. */
  86618. function CubeTextureAssetTask(
  86619. /**
  86620. * Defines the name of the task
  86621. */
  86622. name,
  86623. /**
  86624. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86625. */
  86626. url,
  86627. /**
  86628. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86629. */
  86630. extensions,
  86631. /**
  86632. * Defines if mipmaps should not be generated (default is false)
  86633. */
  86634. noMipmap,
  86635. /**
  86636. * Defines the explicit list of files (undefined by default)
  86637. */
  86638. files) {
  86639. var _this = _super.call(this, name) || this;
  86640. _this.name = name;
  86641. _this.url = url;
  86642. _this.extensions = extensions;
  86643. _this.noMipmap = noMipmap;
  86644. _this.files = files;
  86645. return _this;
  86646. }
  86647. /**
  86648. * Execute the current task
  86649. * @param scene defines the scene where you want your assets to be loaded
  86650. * @param onSuccess is a callback called when the task is successfully executed
  86651. * @param onError is a callback called if an error occurs
  86652. */
  86653. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86654. var onload = function () {
  86655. onSuccess();
  86656. };
  86657. var onerror = function (message, exception) {
  86658. onError(message, exception);
  86659. };
  86660. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86661. };
  86662. return CubeTextureAssetTask;
  86663. }(AbstractAssetTask));
  86664. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86665. /**
  86666. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86667. */
  86668. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86669. __extends(HDRCubeTextureAssetTask, _super);
  86670. /**
  86671. * Creates a new HDRCubeTextureAssetTask object
  86672. * @param name defines the name of the task
  86673. * @param url defines the location of the file to load
  86674. * @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.
  86675. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86676. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86677. * @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)
  86678. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86679. */
  86680. function HDRCubeTextureAssetTask(
  86681. /**
  86682. * Defines the name of the task
  86683. */
  86684. name,
  86685. /**
  86686. * Defines the location of the file to load
  86687. */
  86688. url,
  86689. /**
  86690. * 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.
  86691. */
  86692. size,
  86693. /**
  86694. * Defines if mipmaps should not be generated (default is false)
  86695. */
  86696. noMipmap,
  86697. /**
  86698. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86699. */
  86700. generateHarmonics,
  86701. /**
  86702. * 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)
  86703. */
  86704. useInGammaSpace,
  86705. /**
  86706. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86707. */
  86708. usePMREMGenerator) {
  86709. if (noMipmap === void 0) { noMipmap = false; }
  86710. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86711. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86712. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86713. var _this = _super.call(this, name) || this;
  86714. _this.name = name;
  86715. _this.url = url;
  86716. _this.size = size;
  86717. _this.noMipmap = noMipmap;
  86718. _this.generateHarmonics = generateHarmonics;
  86719. _this.useInGammaSpace = useInGammaSpace;
  86720. _this.usePMREMGenerator = usePMREMGenerator;
  86721. return _this;
  86722. }
  86723. /**
  86724. * Execute the current task
  86725. * @param scene defines the scene where you want your assets to be loaded
  86726. * @param onSuccess is a callback called when the task is successfully executed
  86727. * @param onError is a callback called if an error occurs
  86728. */
  86729. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86730. var onload = function () {
  86731. onSuccess();
  86732. };
  86733. var onerror = function (message, exception) {
  86734. onError(message, exception);
  86735. };
  86736. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86737. };
  86738. return HDRCubeTextureAssetTask;
  86739. }(AbstractAssetTask));
  86740. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86741. /**
  86742. * This class can be used to easily import assets into a scene
  86743. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86744. */
  86745. var AssetsManager = /** @class */ (function () {
  86746. /**
  86747. * Creates a new AssetsManager
  86748. * @param scene defines the scene to work on
  86749. */
  86750. function AssetsManager(scene) {
  86751. this._isLoading = false;
  86752. this._tasks = new Array();
  86753. this._waitingTasksCount = 0;
  86754. this._totalTasksCount = 0;
  86755. /**
  86756. * Observable called when all tasks are processed
  86757. */
  86758. this.onTaskSuccessObservable = new BABYLON.Observable();
  86759. /**
  86760. * Observable called when a task had an error
  86761. */
  86762. this.onTaskErrorObservable = new BABYLON.Observable();
  86763. /**
  86764. * Observable called when a task is successful
  86765. */
  86766. this.onTasksDoneObservable = new BABYLON.Observable();
  86767. /**
  86768. * Observable called when a task is done (whatever the result is)
  86769. */
  86770. this.onProgressObservable = new BABYLON.Observable();
  86771. /**
  86772. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86773. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86774. */
  86775. this.useDefaultLoadingScreen = true;
  86776. this._scene = scene;
  86777. }
  86778. /**
  86779. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86780. * @param taskName defines the name of the new task
  86781. * @param meshesNames defines the name of meshes to load
  86782. * @param rootUrl defines the root url to use to locate files
  86783. * @param sceneFilename defines the filename of the scene file
  86784. * @returns a new {BABYLON.MeshAssetTask} object
  86785. */
  86786. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86787. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86788. this._tasks.push(task);
  86789. return task;
  86790. };
  86791. /**
  86792. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86793. * @param taskName defines the name of the new task
  86794. * @param url defines the url of the file to load
  86795. * @returns a new {BABYLON.TextFileAssetTask} object
  86796. */
  86797. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86798. var task = new TextFileAssetTask(taskName, url);
  86799. this._tasks.push(task);
  86800. return task;
  86801. };
  86802. /**
  86803. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86804. * @param taskName defines the name of the new task
  86805. * @param url defines the url of the file to load
  86806. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86807. */
  86808. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86809. var task = new BinaryFileAssetTask(taskName, url);
  86810. this._tasks.push(task);
  86811. return task;
  86812. };
  86813. /**
  86814. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86815. * @param taskName defines the name of the new task
  86816. * @param url defines the url of the file to load
  86817. * @returns a new {BABYLON.ImageAssetTask} object
  86818. */
  86819. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86820. var task = new ImageAssetTask(taskName, url);
  86821. this._tasks.push(task);
  86822. return task;
  86823. };
  86824. /**
  86825. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86826. * @param taskName defines the name of the new task
  86827. * @param url defines the url of the file to load
  86828. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86829. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86830. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86831. * @returns a new {BABYLON.TextureAssetTask} object
  86832. */
  86833. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86835. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86836. this._tasks.push(task);
  86837. return task;
  86838. };
  86839. /**
  86840. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86841. * @param taskName defines the name of the new task
  86842. * @param url defines the url of the file to load
  86843. * @param extensions defines the extension to use to load the cube map (can be null)
  86844. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86845. * @param files defines the list of files to load (can be null)
  86846. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86847. */
  86848. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86849. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86850. this._tasks.push(task);
  86851. return task;
  86852. };
  86853. /**
  86854. *
  86855. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86856. * @param taskName defines the name of the new task
  86857. * @param url defines the url of the file to load
  86858. * @param size defines the size you want for the cubemap (can be null)
  86859. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86860. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86861. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86862. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86863. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86864. */
  86865. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86866. if (noMipmap === void 0) { noMipmap = false; }
  86867. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86868. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86869. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86870. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86871. this._tasks.push(task);
  86872. return task;
  86873. };
  86874. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86875. var _this = this;
  86876. this._waitingTasksCount--;
  86877. try {
  86878. if (task.taskState === AssetTaskState.DONE) {
  86879. // Let's remove successfull tasks
  86880. BABYLON.Tools.SetImmediate(function () {
  86881. var index = _this._tasks.indexOf(task);
  86882. if (index > -1) {
  86883. _this._tasks.splice(index, 1);
  86884. }
  86885. });
  86886. }
  86887. if (this.onProgress) {
  86888. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86889. }
  86890. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86891. }
  86892. catch (e) {
  86893. BABYLON.Tools.Error("Error running progress callbacks.");
  86894. console.log(e);
  86895. }
  86896. if (this._waitingTasksCount === 0) {
  86897. try {
  86898. if (this.onFinish) {
  86899. this.onFinish(this._tasks);
  86900. }
  86901. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86902. }
  86903. catch (e) {
  86904. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86905. console.log(e);
  86906. }
  86907. this._isLoading = false;
  86908. this._scene.getEngine().hideLoadingUI();
  86909. }
  86910. };
  86911. AssetsManager.prototype._runTask = function (task) {
  86912. var _this = this;
  86913. var done = function () {
  86914. try {
  86915. if (_this.onTaskSuccess) {
  86916. _this.onTaskSuccess(task);
  86917. }
  86918. _this.onTaskSuccessObservable.notifyObservers(task);
  86919. _this._decreaseWaitingTasksCount(task);
  86920. }
  86921. catch (e) {
  86922. error("Error executing task success callbacks", e);
  86923. }
  86924. };
  86925. var error = function (message, exception) {
  86926. task._setErrorObject(message, exception);
  86927. if (_this.onTaskError) {
  86928. _this.onTaskError(task);
  86929. }
  86930. _this.onTaskErrorObservable.notifyObservers(task);
  86931. _this._decreaseWaitingTasksCount(task);
  86932. };
  86933. task.run(this._scene, done, error);
  86934. };
  86935. /**
  86936. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86937. * @return the current instance of the {BABYLON.AssetsManager}
  86938. */
  86939. AssetsManager.prototype.reset = function () {
  86940. this._isLoading = false;
  86941. this._tasks = new Array();
  86942. return this;
  86943. };
  86944. /**
  86945. * Start the loading process
  86946. * @return the current instance of the {BABYLON.AssetsManager}
  86947. */
  86948. AssetsManager.prototype.load = function () {
  86949. if (this._isLoading) {
  86950. return this;
  86951. }
  86952. this._isLoading = true;
  86953. this._waitingTasksCount = this._tasks.length;
  86954. this._totalTasksCount = this._tasks.length;
  86955. if (this._waitingTasksCount === 0) {
  86956. this._isLoading = false;
  86957. if (this.onFinish) {
  86958. this.onFinish(this._tasks);
  86959. }
  86960. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86961. return this;
  86962. }
  86963. if (this.useDefaultLoadingScreen) {
  86964. this._scene.getEngine().displayLoadingUI();
  86965. }
  86966. for (var index = 0; index < this._tasks.length; index++) {
  86967. var task = this._tasks[index];
  86968. this._runTask(task);
  86969. }
  86970. return this;
  86971. };
  86972. return AssetsManager;
  86973. }());
  86974. BABYLON.AssetsManager = AssetsManager;
  86975. })(BABYLON || (BABYLON = {}));
  86976. //# sourceMappingURL=babylon.assetsManager.js.map
  86977. var BABYLON;
  86978. (function (BABYLON) {
  86979. var serializedGeometries = [];
  86980. var serializeGeometry = function (geometry, serializationGeometries) {
  86981. if (serializedGeometries[geometry.id]) {
  86982. return;
  86983. }
  86984. if (geometry.doNotSerialize) {
  86985. return;
  86986. }
  86987. if (geometry instanceof BABYLON.BoxGeometry) {
  86988. serializationGeometries.boxes.push(geometry.serialize());
  86989. }
  86990. else if (geometry instanceof BABYLON.SphereGeometry) {
  86991. serializationGeometries.spheres.push(geometry.serialize());
  86992. }
  86993. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86994. serializationGeometries.cylinders.push(geometry.serialize());
  86995. }
  86996. else if (geometry instanceof BABYLON.TorusGeometry) {
  86997. serializationGeometries.toruses.push(geometry.serialize());
  86998. }
  86999. else if (geometry instanceof BABYLON.GroundGeometry) {
  87000. serializationGeometries.grounds.push(geometry.serialize());
  87001. }
  87002. else if (geometry instanceof BABYLON.Plane) {
  87003. serializationGeometries.planes.push(geometry.serialize());
  87004. }
  87005. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87006. serializationGeometries.torusKnots.push(geometry.serialize());
  87007. }
  87008. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87009. throw new Error("Unknown primitive type");
  87010. }
  87011. else {
  87012. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87013. }
  87014. serializedGeometries[geometry.id] = true;
  87015. };
  87016. var serializeMesh = function (mesh, serializationScene) {
  87017. var serializationObject = {};
  87018. // Geometry
  87019. var geometry = mesh._geometry;
  87020. if (geometry) {
  87021. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87022. // 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
  87023. serializeGeometry(geometry, serializationScene.geometries);
  87024. }
  87025. }
  87026. // Custom
  87027. if (mesh.serialize) {
  87028. mesh.serialize(serializationObject);
  87029. }
  87030. return serializationObject;
  87031. };
  87032. var finalizeSingleMesh = function (mesh, serializationObject) {
  87033. //only works if the mesh is already loaded
  87034. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87035. //serialize material
  87036. if (mesh.material) {
  87037. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87038. serializationObject.materials = serializationObject.materials || [];
  87039. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87040. serializationObject.materials.push(mesh.material.serialize());
  87041. }
  87042. }
  87043. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87044. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87045. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87046. serializationObject.multiMaterials.push(mesh.material.serialize());
  87047. }
  87048. }
  87049. }
  87050. //serialize geometry
  87051. var geometry = mesh._geometry;
  87052. if (geometry) {
  87053. if (!serializationObject.geometries) {
  87054. serializationObject.geometries = {};
  87055. serializationObject.geometries.boxes = [];
  87056. serializationObject.geometries.spheres = [];
  87057. serializationObject.geometries.cylinders = [];
  87058. serializationObject.geometries.toruses = [];
  87059. serializationObject.geometries.grounds = [];
  87060. serializationObject.geometries.planes = [];
  87061. serializationObject.geometries.torusKnots = [];
  87062. serializationObject.geometries.vertexData = [];
  87063. }
  87064. serializeGeometry(geometry, serializationObject.geometries);
  87065. }
  87066. // Skeletons
  87067. if (mesh.skeleton) {
  87068. serializationObject.skeletons = serializationObject.skeletons || [];
  87069. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87070. }
  87071. //serialize the actual mesh
  87072. serializationObject.meshes = serializationObject.meshes || [];
  87073. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87074. }
  87075. };
  87076. var SceneSerializer = /** @class */ (function () {
  87077. function SceneSerializer() {
  87078. }
  87079. SceneSerializer.ClearCache = function () {
  87080. serializedGeometries = [];
  87081. };
  87082. SceneSerializer.Serialize = function (scene) {
  87083. var serializationObject = {};
  87084. SceneSerializer.ClearCache();
  87085. // Scene
  87086. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87087. serializationObject.autoClear = scene.autoClear;
  87088. serializationObject.clearColor = scene.clearColor.asArray();
  87089. serializationObject.ambientColor = scene.ambientColor.asArray();
  87090. serializationObject.gravity = scene.gravity.asArray();
  87091. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87092. serializationObject.workerCollisions = scene.workerCollisions;
  87093. // Fog
  87094. if (scene.fogMode && scene.fogMode !== 0) {
  87095. serializationObject.fogMode = scene.fogMode;
  87096. serializationObject.fogColor = scene.fogColor.asArray();
  87097. serializationObject.fogStart = scene.fogStart;
  87098. serializationObject.fogEnd = scene.fogEnd;
  87099. serializationObject.fogDensity = scene.fogDensity;
  87100. }
  87101. //Physics
  87102. if (scene.isPhysicsEnabled()) {
  87103. var physicEngine = scene.getPhysicsEngine();
  87104. if (physicEngine) {
  87105. serializationObject.physicsEnabled = true;
  87106. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87107. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87108. }
  87109. }
  87110. // Metadata
  87111. if (scene.metadata) {
  87112. serializationObject.metadata = scene.metadata;
  87113. }
  87114. // Morph targets
  87115. serializationObject.morphTargetManagers = [];
  87116. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87117. var abstractMesh = _a[_i];
  87118. var manager = abstractMesh.morphTargetManager;
  87119. if (manager) {
  87120. serializationObject.morphTargetManagers.push(manager.serialize());
  87121. }
  87122. }
  87123. // Lights
  87124. serializationObject.lights = [];
  87125. var index;
  87126. var light;
  87127. for (index = 0; index < scene.lights.length; index++) {
  87128. light = scene.lights[index];
  87129. if (!light.doNotSerialize) {
  87130. serializationObject.lights.push(light.serialize());
  87131. }
  87132. }
  87133. // Cameras
  87134. serializationObject.cameras = [];
  87135. for (index = 0; index < scene.cameras.length; index++) {
  87136. var camera = scene.cameras[index];
  87137. if (!camera.doNotSerialize) {
  87138. serializationObject.cameras.push(camera.serialize());
  87139. }
  87140. }
  87141. if (scene.activeCamera) {
  87142. serializationObject.activeCameraID = scene.activeCamera.id;
  87143. }
  87144. // Animations
  87145. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87146. // Materials
  87147. serializationObject.materials = [];
  87148. serializationObject.multiMaterials = [];
  87149. var material;
  87150. for (index = 0; index < scene.materials.length; index++) {
  87151. material = scene.materials[index];
  87152. if (!material.doNotSerialize) {
  87153. serializationObject.materials.push(material.serialize());
  87154. }
  87155. }
  87156. // MultiMaterials
  87157. serializationObject.multiMaterials = [];
  87158. for (index = 0; index < scene.multiMaterials.length; index++) {
  87159. var multiMaterial = scene.multiMaterials[index];
  87160. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87161. }
  87162. // Environment texture
  87163. if (scene.environmentTexture) {
  87164. serializationObject.environmentTexture = scene.environmentTexture.name;
  87165. }
  87166. // Skeletons
  87167. serializationObject.skeletons = [];
  87168. for (index = 0; index < scene.skeletons.length; index++) {
  87169. var skeleton = scene.skeletons[index];
  87170. if (!skeleton.doNotSerialize) {
  87171. serializationObject.skeletons.push(skeleton.serialize());
  87172. }
  87173. }
  87174. // Transform nodes
  87175. serializationObject.transformNodes = [];
  87176. for (index = 0; index < scene.transformNodes.length; index++) {
  87177. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87178. }
  87179. // Geometries
  87180. serializationObject.geometries = {};
  87181. serializationObject.geometries.boxes = [];
  87182. serializationObject.geometries.spheres = [];
  87183. serializationObject.geometries.cylinders = [];
  87184. serializationObject.geometries.toruses = [];
  87185. serializationObject.geometries.grounds = [];
  87186. serializationObject.geometries.planes = [];
  87187. serializationObject.geometries.torusKnots = [];
  87188. serializationObject.geometries.vertexData = [];
  87189. serializedGeometries = [];
  87190. var geometries = scene.getGeometries();
  87191. for (index = 0; index < geometries.length; index++) {
  87192. var geometry = geometries[index];
  87193. if (geometry.isReady()) {
  87194. serializeGeometry(geometry, serializationObject.geometries);
  87195. }
  87196. }
  87197. // Meshes
  87198. serializationObject.meshes = [];
  87199. for (index = 0; index < scene.meshes.length; index++) {
  87200. var abstractMesh = scene.meshes[index];
  87201. if (abstractMesh instanceof BABYLON.Mesh) {
  87202. var mesh = abstractMesh;
  87203. if (!mesh.doNotSerialize) {
  87204. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87205. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87206. }
  87207. }
  87208. }
  87209. }
  87210. // Particles Systems
  87211. serializationObject.particleSystems = [];
  87212. for (index = 0; index < scene.particleSystems.length; index++) {
  87213. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87214. }
  87215. // Lens flares
  87216. serializationObject.lensFlareSystems = [];
  87217. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87218. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87219. }
  87220. // Shadows
  87221. serializationObject.shadowGenerators = [];
  87222. for (index = 0; index < scene.lights.length; index++) {
  87223. light = scene.lights[index];
  87224. var shadowGenerator = light.getShadowGenerator();
  87225. if (shadowGenerator) {
  87226. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87227. }
  87228. }
  87229. // Action Manager
  87230. if (scene.actionManager) {
  87231. serializationObject.actions = scene.actionManager.serialize("scene");
  87232. }
  87233. // Audio
  87234. serializationObject.sounds = [];
  87235. for (index = 0; index < scene.soundTracks.length; index++) {
  87236. var soundtrack = scene.soundTracks[index];
  87237. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87238. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87239. }
  87240. }
  87241. return serializationObject;
  87242. };
  87243. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87244. if (withParents === void 0) { withParents = false; }
  87245. if (withChildren === void 0) { withChildren = false; }
  87246. var serializationObject = {};
  87247. SceneSerializer.ClearCache();
  87248. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87249. if (withParents || withChildren) {
  87250. //deliberate for loop! not for each, appended should be processed as well.
  87251. for (var i = 0; i < toSerialize.length; ++i) {
  87252. if (withChildren) {
  87253. toSerialize[i].getDescendants().forEach(function (node) {
  87254. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87255. toSerialize.push(node);
  87256. }
  87257. });
  87258. }
  87259. //make sure the array doesn't contain the object already
  87260. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87261. toSerialize.push(toSerialize[i].parent);
  87262. }
  87263. }
  87264. }
  87265. toSerialize.forEach(function (mesh) {
  87266. finalizeSingleMesh(mesh, serializationObject);
  87267. });
  87268. return serializationObject;
  87269. };
  87270. return SceneSerializer;
  87271. }());
  87272. BABYLON.SceneSerializer = SceneSerializer;
  87273. })(BABYLON || (BABYLON = {}));
  87274. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87275. var BABYLON;
  87276. (function (BABYLON) {
  87277. var ReflectionProbe = /** @class */ (function () {
  87278. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87279. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87280. var _this = this;
  87281. this.name = name;
  87282. this._viewMatrix = BABYLON.Matrix.Identity();
  87283. this._target = BABYLON.Vector3.Zero();
  87284. this._add = BABYLON.Vector3.Zero();
  87285. this._invertYAxis = false;
  87286. this.position = BABYLON.Vector3.Zero();
  87287. this._scene = scene;
  87288. this._scene.reflectionProbes.push(this);
  87289. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87290. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87291. switch (faceIndex) {
  87292. case 0:
  87293. _this._add.copyFromFloats(1, 0, 0);
  87294. break;
  87295. case 1:
  87296. _this._add.copyFromFloats(-1, 0, 0);
  87297. break;
  87298. case 2:
  87299. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87300. break;
  87301. case 3:
  87302. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87303. break;
  87304. case 4:
  87305. _this._add.copyFromFloats(0, 0, 1);
  87306. break;
  87307. case 5:
  87308. _this._add.copyFromFloats(0, 0, -1);
  87309. break;
  87310. }
  87311. if (_this._attachedMesh) {
  87312. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87313. }
  87314. _this.position.addToRef(_this._add, _this._target);
  87315. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87316. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87317. scene._forcedViewPosition = _this.position;
  87318. });
  87319. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87320. scene._forcedViewPosition = null;
  87321. scene.updateTransformMatrix(true);
  87322. });
  87323. if (scene.activeCamera) {
  87324. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87325. }
  87326. }
  87327. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87328. get: function () {
  87329. return this._renderTargetTexture.samples;
  87330. },
  87331. set: function (value) {
  87332. this._renderTargetTexture.samples = value;
  87333. },
  87334. enumerable: true,
  87335. configurable: true
  87336. });
  87337. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87338. get: function () {
  87339. return this._renderTargetTexture.refreshRate;
  87340. },
  87341. set: function (value) {
  87342. this._renderTargetTexture.refreshRate = value;
  87343. },
  87344. enumerable: true,
  87345. configurable: true
  87346. });
  87347. ReflectionProbe.prototype.getScene = function () {
  87348. return this._scene;
  87349. };
  87350. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87351. get: function () {
  87352. return this._renderTargetTexture;
  87353. },
  87354. enumerable: true,
  87355. configurable: true
  87356. });
  87357. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87358. get: function () {
  87359. return this._renderTargetTexture.renderList;
  87360. },
  87361. enumerable: true,
  87362. configurable: true
  87363. });
  87364. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87365. this._attachedMesh = mesh;
  87366. };
  87367. /**
  87368. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87369. *
  87370. * @param renderingGroupId The rendering group id corresponding to its index
  87371. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87372. */
  87373. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87374. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87375. };
  87376. ReflectionProbe.prototype.dispose = function () {
  87377. var index = this._scene.reflectionProbes.indexOf(this);
  87378. if (index !== -1) {
  87379. // Remove from the scene if found
  87380. this._scene.reflectionProbes.splice(index, 1);
  87381. }
  87382. if (this._renderTargetTexture) {
  87383. this._renderTargetTexture.dispose();
  87384. this._renderTargetTexture = null;
  87385. }
  87386. };
  87387. return ReflectionProbe;
  87388. }());
  87389. BABYLON.ReflectionProbe = ReflectionProbe;
  87390. })(BABYLON || (BABYLON = {}));
  87391. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87392. var BABYLON;
  87393. (function (BABYLON) {
  87394. var Layer = /** @class */ (function () {
  87395. function Layer(name, imgUrl, scene, isBackground, color) {
  87396. this.name = name;
  87397. this.scale = new BABYLON.Vector2(1, 1);
  87398. this.offset = new BABYLON.Vector2(0, 0);
  87399. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87400. this.layerMask = 0x0FFFFFFF;
  87401. this._vertexBuffers = {};
  87402. // Events
  87403. /**
  87404. * An event triggered when the layer is disposed.
  87405. * @type {BABYLON.Observable}
  87406. */
  87407. this.onDisposeObservable = new BABYLON.Observable();
  87408. /**
  87409. * An event triggered before rendering the scene
  87410. * @type {BABYLON.Observable}
  87411. */
  87412. this.onBeforeRenderObservable = new BABYLON.Observable();
  87413. /**
  87414. * An event triggered after rendering the scene
  87415. * @type {BABYLON.Observable}
  87416. */
  87417. this.onAfterRenderObservable = new BABYLON.Observable();
  87418. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87419. this.isBackground = isBackground === undefined ? true : isBackground;
  87420. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87421. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87422. this._scene.layers.push(this);
  87423. var engine = this._scene.getEngine();
  87424. // VBO
  87425. var vertices = [];
  87426. vertices.push(1, 1);
  87427. vertices.push(-1, 1);
  87428. vertices.push(-1, -1);
  87429. vertices.push(1, -1);
  87430. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87431. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87432. this._createIndexBuffer();
  87433. // Effects
  87434. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87435. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87436. }
  87437. Object.defineProperty(Layer.prototype, "onDispose", {
  87438. set: function (callback) {
  87439. if (this._onDisposeObserver) {
  87440. this.onDisposeObservable.remove(this._onDisposeObserver);
  87441. }
  87442. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87443. },
  87444. enumerable: true,
  87445. configurable: true
  87446. });
  87447. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87448. set: function (callback) {
  87449. if (this._onBeforeRenderObserver) {
  87450. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87451. }
  87452. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87453. },
  87454. enumerable: true,
  87455. configurable: true
  87456. });
  87457. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87458. set: function (callback) {
  87459. if (this._onAfterRenderObserver) {
  87460. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87461. }
  87462. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87463. },
  87464. enumerable: true,
  87465. configurable: true
  87466. });
  87467. Layer.prototype._createIndexBuffer = function () {
  87468. var engine = this._scene.getEngine();
  87469. // Indices
  87470. var indices = [];
  87471. indices.push(0);
  87472. indices.push(1);
  87473. indices.push(2);
  87474. indices.push(0);
  87475. indices.push(2);
  87476. indices.push(3);
  87477. this._indexBuffer = engine.createIndexBuffer(indices);
  87478. };
  87479. Layer.prototype._rebuild = function () {
  87480. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87481. if (vb) {
  87482. vb._rebuild();
  87483. }
  87484. this._createIndexBuffer();
  87485. };
  87486. Layer.prototype.render = function () {
  87487. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87488. // Check
  87489. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87490. return;
  87491. var engine = this._scene.getEngine();
  87492. this.onBeforeRenderObservable.notifyObservers(this);
  87493. // Render
  87494. engine.enableEffect(currentEffect);
  87495. engine.setState(false);
  87496. // Texture
  87497. currentEffect.setTexture("textureSampler", this.texture);
  87498. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87499. // Color
  87500. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87501. // Scale / offset
  87502. currentEffect.setVector2("offset", this.offset);
  87503. currentEffect.setVector2("scale", this.scale);
  87504. // VBOs
  87505. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87506. // Draw order
  87507. if (!this.alphaTest) {
  87508. engine.setAlphaMode(this.alphaBlendingMode);
  87509. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87510. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87511. }
  87512. else {
  87513. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87514. }
  87515. this.onAfterRenderObservable.notifyObservers(this);
  87516. };
  87517. Layer.prototype.dispose = function () {
  87518. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87519. if (vertexBuffer) {
  87520. vertexBuffer.dispose();
  87521. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87522. }
  87523. if (this._indexBuffer) {
  87524. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87525. this._indexBuffer = null;
  87526. }
  87527. if (this.texture) {
  87528. this.texture.dispose();
  87529. this.texture = null;
  87530. }
  87531. // Remove from scene
  87532. var index = this._scene.layers.indexOf(this);
  87533. this._scene.layers.splice(index, 1);
  87534. // Callback
  87535. this.onDisposeObservable.notifyObservers(this);
  87536. this.onDisposeObservable.clear();
  87537. this.onAfterRenderObservable.clear();
  87538. this.onBeforeRenderObservable.clear();
  87539. };
  87540. return Layer;
  87541. }());
  87542. BABYLON.Layer = Layer;
  87543. })(BABYLON || (BABYLON = {}));
  87544. //# sourceMappingURL=babylon.layer.js.map
  87545. var BABYLON;
  87546. (function (BABYLON) {
  87547. var TextureTools = /** @class */ (function () {
  87548. function TextureTools() {
  87549. }
  87550. /**
  87551. * Uses the GPU to create a copy texture rescaled at a given size
  87552. * @param texture Texture to copy from
  87553. * @param width Desired width
  87554. * @param height Desired height
  87555. * @return Generated texture
  87556. */
  87557. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87558. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87559. var scene = texture.getScene();
  87560. var engine = scene.getEngine();
  87561. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87562. rtt.wrapU = texture.wrapU;
  87563. rtt.wrapV = texture.wrapV;
  87564. rtt.uOffset = texture.uOffset;
  87565. rtt.vOffset = texture.vOffset;
  87566. rtt.uScale = texture.uScale;
  87567. rtt.vScale = texture.vScale;
  87568. rtt.uAng = texture.uAng;
  87569. rtt.vAng = texture.vAng;
  87570. rtt.wAng = texture.wAng;
  87571. rtt.coordinatesIndex = texture.coordinatesIndex;
  87572. rtt.level = texture.level;
  87573. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87574. rtt._texture.isReady = false;
  87575. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87576. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87577. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87578. passPostProcess.getEffect().executeWhenCompiled(function () {
  87579. passPostProcess.onApply = function (effect) {
  87580. effect.setTexture("textureSampler", texture);
  87581. };
  87582. var internalTexture = rtt.getInternalTexture();
  87583. if (internalTexture) {
  87584. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87585. engine.unBindFramebuffer(internalTexture);
  87586. rtt.disposeFramebufferObjects();
  87587. passPostProcess.dispose();
  87588. internalTexture.isReady = true;
  87589. }
  87590. });
  87591. return rtt;
  87592. };
  87593. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87594. if (!scene._environmentBRDFTexture) {
  87595. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87596. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87597. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87598. scene._environmentBRDFTexture = texture;
  87599. }
  87600. return scene._environmentBRDFTexture;
  87601. };
  87602. 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=";
  87603. return TextureTools;
  87604. }());
  87605. BABYLON.TextureTools = TextureTools;
  87606. })(BABYLON || (BABYLON = {}));
  87607. //# sourceMappingURL=babylon.textureTools.js.map
  87608. var BABYLON;
  87609. (function (BABYLON) {
  87610. var FramingBehavior = /** @class */ (function () {
  87611. function FramingBehavior() {
  87612. this._mode = FramingBehavior.FitFrustumSidesMode;
  87613. this._radiusScale = 1.0;
  87614. this._positionScale = 0.5;
  87615. this._defaultElevation = 0.3;
  87616. this._elevationReturnTime = 1500;
  87617. this._elevationReturnWaitTime = 1000;
  87618. this._zoomStopsAnimation = false;
  87619. this._framingTime = 1500;
  87620. this._isPointerDown = false;
  87621. this._lastInteractionTime = -Infinity;
  87622. // Framing control
  87623. this._animatables = new Array();
  87624. this._betaIsAnimating = false;
  87625. }
  87626. Object.defineProperty(FramingBehavior.prototype, "name", {
  87627. get: function () {
  87628. return "Framing";
  87629. },
  87630. enumerable: true,
  87631. configurable: true
  87632. });
  87633. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87634. /**
  87635. * Gets current mode used by the behavior.
  87636. */
  87637. get: function () {
  87638. return this._mode;
  87639. },
  87640. /**
  87641. * Sets the current mode used by the behavior
  87642. */
  87643. set: function (mode) {
  87644. this._mode = mode;
  87645. },
  87646. enumerable: true,
  87647. configurable: true
  87648. });
  87649. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87650. /**
  87651. * Gets the scale applied to the radius
  87652. */
  87653. get: function () {
  87654. return this._radiusScale;
  87655. },
  87656. /**
  87657. * Sets the scale applied to the radius (1 by default)
  87658. */
  87659. set: function (radius) {
  87660. this._radiusScale = radius;
  87661. },
  87662. enumerable: true,
  87663. configurable: true
  87664. });
  87665. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87666. /**
  87667. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87668. */
  87669. get: function () {
  87670. return this._positionScale;
  87671. },
  87672. /**
  87673. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87674. */
  87675. set: function (scale) {
  87676. this._positionScale = scale;
  87677. },
  87678. enumerable: true,
  87679. configurable: true
  87680. });
  87681. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87682. /**
  87683. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87684. * behaviour is triggered, in radians.
  87685. */
  87686. get: function () {
  87687. return this._defaultElevation;
  87688. },
  87689. /**
  87690. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87691. * behaviour is triggered, in radians.
  87692. */
  87693. set: function (elevation) {
  87694. this._defaultElevation = elevation;
  87695. },
  87696. enumerable: true,
  87697. configurable: true
  87698. });
  87699. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87700. /**
  87701. * Gets the time (in milliseconds) taken to return to the default beta position.
  87702. * Negative value indicates camera should not return to default.
  87703. */
  87704. get: function () {
  87705. return this._elevationReturnTime;
  87706. },
  87707. /**
  87708. * Sets the time (in milliseconds) taken to return to the default beta position.
  87709. * Negative value indicates camera should not return to default.
  87710. */
  87711. set: function (speed) {
  87712. this._elevationReturnTime = speed;
  87713. },
  87714. enumerable: true,
  87715. configurable: true
  87716. });
  87717. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87718. /**
  87719. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87720. */
  87721. get: function () {
  87722. return this._elevationReturnWaitTime;
  87723. },
  87724. /**
  87725. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87726. */
  87727. set: function (time) {
  87728. this._elevationReturnWaitTime = time;
  87729. },
  87730. enumerable: true,
  87731. configurable: true
  87732. });
  87733. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87734. /**
  87735. * Gets the flag that indicates if user zooming should stop animation.
  87736. */
  87737. get: function () {
  87738. return this._zoomStopsAnimation;
  87739. },
  87740. /**
  87741. * Sets the flag that indicates if user zooming should stop animation.
  87742. */
  87743. set: function (flag) {
  87744. this._zoomStopsAnimation = flag;
  87745. },
  87746. enumerable: true,
  87747. configurable: true
  87748. });
  87749. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87750. /**
  87751. * Gets the transition time when framing the mesh, in milliseconds
  87752. */
  87753. get: function () {
  87754. return this._framingTime;
  87755. },
  87756. /**
  87757. * Sets the transition time when framing the mesh, in milliseconds
  87758. */
  87759. set: function (time) {
  87760. this._framingTime = time;
  87761. },
  87762. enumerable: true,
  87763. configurable: true
  87764. });
  87765. FramingBehavior.prototype.init = function () {
  87766. // Do notihng
  87767. };
  87768. FramingBehavior.prototype.attach = function (camera) {
  87769. var _this = this;
  87770. this._attachedCamera = camera;
  87771. var scene = this._attachedCamera.getScene();
  87772. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87773. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87774. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87775. _this._isPointerDown = true;
  87776. return;
  87777. }
  87778. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87779. _this._isPointerDown = false;
  87780. }
  87781. });
  87782. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87783. if (mesh) {
  87784. _this.zoomOnMesh(mesh);
  87785. }
  87786. });
  87787. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87788. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87789. _this._applyUserInteraction();
  87790. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87791. // back to the default position after a given timeout
  87792. _this._maintainCameraAboveGround();
  87793. });
  87794. };
  87795. FramingBehavior.prototype.detach = function () {
  87796. if (!this._attachedCamera) {
  87797. return;
  87798. }
  87799. var scene = this._attachedCamera.getScene();
  87800. if (this._onPrePointerObservableObserver) {
  87801. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87802. }
  87803. if (this._onAfterCheckInputsObserver) {
  87804. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87805. }
  87806. if (this._onMeshTargetChangedObserver) {
  87807. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87808. }
  87809. this._attachedCamera = null;
  87810. };
  87811. /**
  87812. * Targets the given mesh and updates zoom level accordingly.
  87813. * @param mesh The mesh to target.
  87814. * @param radius Optional. If a cached radius position already exists, overrides default.
  87815. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87816. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87817. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87818. */
  87819. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87820. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87821. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87822. mesh.computeWorldMatrix(true);
  87823. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87824. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87825. };
  87826. /**
  87827. * Targets the given mesh with its children and updates zoom level accordingly.
  87828. * @param mesh The mesh to target.
  87829. * @param radius Optional. If a cached radius position already exists, overrides default.
  87830. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87831. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87832. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87833. */
  87834. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87835. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87836. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87837. mesh.computeWorldMatrix(true);
  87838. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87839. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87840. };
  87841. /**
  87842. * Targets the given meshes with their children and updates zoom level accordingly.
  87843. * @param meshes The mesh to target.
  87844. * @param radius Optional. If a cached radius position already exists, overrides default.
  87845. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87846. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87847. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87848. */
  87849. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87850. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87851. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87852. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87853. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87854. for (var i = 0; i < meshes.length; i++) {
  87855. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87856. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87857. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87858. }
  87859. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87860. };
  87861. /**
  87862. * Targets the given mesh and updates zoom level accordingly.
  87863. * @param mesh The mesh to target.
  87864. * @param radius Optional. If a cached radius position already exists, overrides default.
  87865. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87866. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87867. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87868. */
  87869. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87870. var _this = this;
  87871. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87872. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87873. var zoomTarget;
  87874. if (!this._attachedCamera) {
  87875. return;
  87876. }
  87877. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87878. var bottom = minimumWorld.y;
  87879. var top = maximumWorld.y;
  87880. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87881. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87882. if (focusOnOriginXZ) {
  87883. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87884. }
  87885. else {
  87886. var centerWorld = minimumWorld.add(radiusWorld);
  87887. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87888. }
  87889. if (!this._vectorTransition) {
  87890. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87891. }
  87892. this._betaIsAnimating = true;
  87893. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87894. if (animatable) {
  87895. this._animatables.push(animatable);
  87896. }
  87897. // sets the radius and lower radius bounds
  87898. // Small delta ensures camera is not always at lower zoom limit.
  87899. var radius = 0;
  87900. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87901. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87902. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87903. radius = position;
  87904. }
  87905. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87906. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87907. if (this._attachedCamera.lowerRadiusLimit === null) {
  87908. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87909. }
  87910. }
  87911. // Set sensibilities
  87912. var extend = maximumWorld.subtract(minimumWorld).length();
  87913. this._attachedCamera.panningSensibility = 5000 / extend;
  87914. this._attachedCamera.wheelPrecision = 100 / radius;
  87915. // transition to new radius
  87916. if (!this._radiusTransition) {
  87917. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87918. }
  87919. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87920. _this.stopAllAnimations();
  87921. if (onAnimationEnd) {
  87922. onAnimationEnd();
  87923. }
  87924. if (_this._attachedCamera) {
  87925. _this._attachedCamera.storeState();
  87926. }
  87927. });
  87928. if (animatable) {
  87929. this._animatables.push(animatable);
  87930. }
  87931. };
  87932. /**
  87933. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87934. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87935. * frustum width.
  87936. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87937. * to fully enclose the mesh in the viewing frustum.
  87938. */
  87939. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87940. var size = maximumWorld.subtract(minimumWorld);
  87941. var boxVectorGlobalDiagonal = size.length();
  87942. var frustumSlope = this._getFrustumSlope();
  87943. // Formula for setting distance
  87944. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87945. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87946. // Horizon distance
  87947. var radius = radiusWithoutFraming * this._radiusScale;
  87948. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87949. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87950. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87951. var camera = this._attachedCamera;
  87952. if (!camera) {
  87953. return 0;
  87954. }
  87955. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87956. // Don't exceed the requested limit
  87957. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87958. }
  87959. // Don't exceed the upper radius limit
  87960. if (camera.upperRadiusLimit) {
  87961. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87962. }
  87963. return distance;
  87964. };
  87965. /**
  87966. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87967. * is automatically returned to its default position (expected to be above ground plane).
  87968. */
  87969. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87970. var _this = this;
  87971. if (this._elevationReturnTime < 0) {
  87972. return;
  87973. }
  87974. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87975. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87976. var limitBeta = Math.PI * 0.5;
  87977. // Bring the camera back up if below the ground plane
  87978. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87979. this._betaIsAnimating = true;
  87980. //Transition to new position
  87981. this.stopAllAnimations();
  87982. if (!this._betaTransition) {
  87983. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87984. }
  87985. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87986. _this._clearAnimationLocks();
  87987. _this.stopAllAnimations();
  87988. });
  87989. if (animatabe) {
  87990. this._animatables.push(animatabe);
  87991. }
  87992. }
  87993. };
  87994. /**
  87995. * Returns the frustum slope based on the canvas ratio and camera FOV
  87996. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87997. */
  87998. FramingBehavior.prototype._getFrustumSlope = function () {
  87999. // Calculate the viewport ratio
  88000. // Aspect Ratio is Height/Width.
  88001. var camera = this._attachedCamera;
  88002. if (!camera) {
  88003. return BABYLON.Vector2.Zero();
  88004. }
  88005. var engine = camera.getScene().getEngine();
  88006. var aspectRatio = engine.getAspectRatio(camera);
  88007. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88008. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88009. var frustumSlopeY = Math.tan(camera.fov / 2);
  88010. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88011. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88012. // along the forward vector.
  88013. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88014. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88015. };
  88016. /**
  88017. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88018. */
  88019. FramingBehavior.prototype._clearAnimationLocks = function () {
  88020. this._betaIsAnimating = false;
  88021. };
  88022. /**
  88023. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88024. */
  88025. FramingBehavior.prototype._applyUserInteraction = function () {
  88026. if (this.isUserIsMoving) {
  88027. this._lastInteractionTime = BABYLON.Tools.Now;
  88028. this.stopAllAnimations();
  88029. this._clearAnimationLocks();
  88030. }
  88031. };
  88032. /**
  88033. * Stops and removes all animations that have been applied to the camera
  88034. */
  88035. FramingBehavior.prototype.stopAllAnimations = function () {
  88036. if (this._attachedCamera) {
  88037. this._attachedCamera.animations = [];
  88038. }
  88039. while (this._animatables.length) {
  88040. if (this._animatables[0]) {
  88041. this._animatables[0].onAnimationEnd = null;
  88042. this._animatables[0].stop();
  88043. }
  88044. this._animatables.shift();
  88045. }
  88046. };
  88047. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88048. /**
  88049. * Gets a value indicating if the user is moving the camera
  88050. */
  88051. get: function () {
  88052. if (!this._attachedCamera) {
  88053. return false;
  88054. }
  88055. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88056. this._attachedCamera.inertialBetaOffset !== 0 ||
  88057. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88058. this._attachedCamera.inertialPanningX !== 0 ||
  88059. this._attachedCamera.inertialPanningY !== 0 ||
  88060. this._isPointerDown;
  88061. },
  88062. enumerable: true,
  88063. configurable: true
  88064. });
  88065. /**
  88066. * The easing function used by animations
  88067. */
  88068. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88069. /**
  88070. * The easing mode used by animations
  88071. */
  88072. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88073. // Statics
  88074. /**
  88075. * The camera can move all the way towards the mesh.
  88076. */
  88077. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88078. /**
  88079. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88080. */
  88081. FramingBehavior.FitFrustumSidesMode = 1;
  88082. return FramingBehavior;
  88083. }());
  88084. BABYLON.FramingBehavior = FramingBehavior;
  88085. })(BABYLON || (BABYLON = {}));
  88086. //# sourceMappingURL=babylon.framingBehavior.js.map
  88087. var BABYLON;
  88088. (function (BABYLON) {
  88089. /**
  88090. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88091. */
  88092. var BouncingBehavior = /** @class */ (function () {
  88093. function BouncingBehavior() {
  88094. /**
  88095. * The duration of the animation, in milliseconds
  88096. */
  88097. this.transitionDuration = 450;
  88098. /**
  88099. * Length of the distance animated by the transition when lower radius is reached
  88100. */
  88101. this.lowerRadiusTransitionRange = 2;
  88102. /**
  88103. * Length of the distance animated by the transition when upper radius is reached
  88104. */
  88105. this.upperRadiusTransitionRange = -2;
  88106. this._autoTransitionRange = false;
  88107. // Animations
  88108. this._radiusIsAnimating = false;
  88109. this._radiusBounceTransition = null;
  88110. this._animatables = new Array();
  88111. }
  88112. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88113. get: function () {
  88114. return "Bouncing";
  88115. },
  88116. enumerable: true,
  88117. configurable: true
  88118. });
  88119. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88120. /**
  88121. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88122. */
  88123. get: function () {
  88124. return this._autoTransitionRange;
  88125. },
  88126. /**
  88127. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88128. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88129. */
  88130. set: function (value) {
  88131. var _this = this;
  88132. if (this._autoTransitionRange === value) {
  88133. return;
  88134. }
  88135. this._autoTransitionRange = value;
  88136. var camera = this._attachedCamera;
  88137. if (!camera) {
  88138. return;
  88139. }
  88140. if (value) {
  88141. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88142. if (!mesh) {
  88143. return;
  88144. }
  88145. mesh.computeWorldMatrix(true);
  88146. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88147. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88148. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88149. });
  88150. }
  88151. else if (this._onMeshTargetChangedObserver) {
  88152. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88153. }
  88154. },
  88155. enumerable: true,
  88156. configurable: true
  88157. });
  88158. BouncingBehavior.prototype.init = function () {
  88159. // Do notihng
  88160. };
  88161. BouncingBehavior.prototype.attach = function (camera) {
  88162. var _this = this;
  88163. this._attachedCamera = camera;
  88164. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88165. if (!_this._attachedCamera) {
  88166. return;
  88167. }
  88168. // Add the bounce animation to the lower radius limit
  88169. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88170. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88171. }
  88172. // Add the bounce animation to the upper radius limit
  88173. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88174. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88175. }
  88176. });
  88177. };
  88178. BouncingBehavior.prototype.detach = function () {
  88179. if (!this._attachedCamera) {
  88180. return;
  88181. }
  88182. if (this._onAfterCheckInputsObserver) {
  88183. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88184. }
  88185. if (this._onMeshTargetChangedObserver) {
  88186. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88187. }
  88188. this._attachedCamera = null;
  88189. };
  88190. /**
  88191. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88192. * @param radiusLimit The limit to check against.
  88193. * @return Bool to indicate if at limit.
  88194. */
  88195. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88196. if (!this._attachedCamera) {
  88197. return false;
  88198. }
  88199. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88200. return true;
  88201. }
  88202. return false;
  88203. };
  88204. /**
  88205. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88206. * @param radiusDelta The delta by which to animate to. Can be negative.
  88207. */
  88208. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88209. var _this = this;
  88210. if (!this._attachedCamera) {
  88211. return;
  88212. }
  88213. if (!this._radiusBounceTransition) {
  88214. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88215. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88216. }
  88217. // Prevent zoom until bounce has completed
  88218. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88219. this._attachedCamera.wheelPrecision = Infinity;
  88220. this._attachedCamera.inertialRadiusOffset = 0;
  88221. // Animate to the radius limit
  88222. this.stopAllAnimations();
  88223. this._radiusIsAnimating = true;
  88224. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88225. if (animatable) {
  88226. this._animatables.push(animatable);
  88227. }
  88228. };
  88229. /**
  88230. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88231. */
  88232. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88233. this._radiusIsAnimating = false;
  88234. if (this._attachedCamera) {
  88235. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88236. }
  88237. };
  88238. /**
  88239. * Stops and removes all animations that have been applied to the camera
  88240. */
  88241. BouncingBehavior.prototype.stopAllAnimations = function () {
  88242. if (this._attachedCamera) {
  88243. this._attachedCamera.animations = [];
  88244. }
  88245. while (this._animatables.length) {
  88246. this._animatables[0].onAnimationEnd = null;
  88247. this._animatables[0].stop();
  88248. this._animatables.shift();
  88249. }
  88250. };
  88251. /**
  88252. * The easing function used by animations
  88253. */
  88254. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88255. /**
  88256. * The easing mode used by animations
  88257. */
  88258. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88259. return BouncingBehavior;
  88260. }());
  88261. BABYLON.BouncingBehavior = BouncingBehavior;
  88262. })(BABYLON || (BABYLON = {}));
  88263. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88264. var BABYLON;
  88265. (function (BABYLON) {
  88266. var AutoRotationBehavior = /** @class */ (function () {
  88267. function AutoRotationBehavior() {
  88268. this._zoomStopsAnimation = false;
  88269. this._idleRotationSpeed = 0.05;
  88270. this._idleRotationWaitTime = 2000;
  88271. this._idleRotationSpinupTime = 2000;
  88272. this._isPointerDown = false;
  88273. this._lastFrameTime = null;
  88274. this._lastInteractionTime = -Infinity;
  88275. this._cameraRotationSpeed = 0;
  88276. this._lastFrameRadius = 0;
  88277. }
  88278. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88279. get: function () {
  88280. return "AutoRotation";
  88281. },
  88282. enumerable: true,
  88283. configurable: true
  88284. });
  88285. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88286. /**
  88287. * Gets the flag that indicates if user zooming should stop animation.
  88288. */
  88289. get: function () {
  88290. return this._zoomStopsAnimation;
  88291. },
  88292. /**
  88293. * Sets the flag that indicates if user zooming should stop animation.
  88294. */
  88295. set: function (flag) {
  88296. this._zoomStopsAnimation = flag;
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88302. /**
  88303. * Gets the default speed at which the camera rotates around the model.
  88304. */
  88305. get: function () {
  88306. return this._idleRotationSpeed;
  88307. },
  88308. /**
  88309. * Sets the default speed at which the camera rotates around the model.
  88310. */
  88311. set: function (speed) {
  88312. this._idleRotationSpeed = speed;
  88313. },
  88314. enumerable: true,
  88315. configurable: true
  88316. });
  88317. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88318. /**
  88319. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88320. */
  88321. get: function () {
  88322. return this._idleRotationWaitTime;
  88323. },
  88324. /**
  88325. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88326. */
  88327. set: function (time) {
  88328. this._idleRotationWaitTime = time;
  88329. },
  88330. enumerable: true,
  88331. configurable: true
  88332. });
  88333. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88334. /**
  88335. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88336. */
  88337. get: function () {
  88338. return this._idleRotationSpinupTime;
  88339. },
  88340. /**
  88341. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88342. */
  88343. set: function (time) {
  88344. this._idleRotationSpinupTime = time;
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88350. /**
  88351. * Gets a value indicating if the camera is currently rotating because of this behavior
  88352. */
  88353. get: function () {
  88354. return Math.abs(this._cameraRotationSpeed) > 0;
  88355. },
  88356. enumerable: true,
  88357. configurable: true
  88358. });
  88359. AutoRotationBehavior.prototype.init = function () {
  88360. // Do notihng
  88361. };
  88362. AutoRotationBehavior.prototype.attach = function (camera) {
  88363. var _this = this;
  88364. this._attachedCamera = camera;
  88365. var scene = this._attachedCamera.getScene();
  88366. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88367. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88368. _this._isPointerDown = true;
  88369. return;
  88370. }
  88371. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88372. _this._isPointerDown = false;
  88373. }
  88374. });
  88375. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88376. var now = BABYLON.Tools.Now;
  88377. var dt = 0;
  88378. if (_this._lastFrameTime != null) {
  88379. dt = now - _this._lastFrameTime;
  88380. }
  88381. _this._lastFrameTime = now;
  88382. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88383. _this._applyUserInteraction();
  88384. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88385. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88386. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88387. // Step camera rotation by rotation speed
  88388. if (_this._attachedCamera) {
  88389. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88390. }
  88391. });
  88392. };
  88393. AutoRotationBehavior.prototype.detach = function () {
  88394. if (!this._attachedCamera) {
  88395. return;
  88396. }
  88397. var scene = this._attachedCamera.getScene();
  88398. if (this._onPrePointerObservableObserver) {
  88399. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88400. }
  88401. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88402. this._attachedCamera = null;
  88403. };
  88404. /**
  88405. * Returns true if user is scrolling.
  88406. * @return true if user is scrolling.
  88407. */
  88408. AutoRotationBehavior.prototype._userIsZooming = function () {
  88409. if (!this._attachedCamera) {
  88410. return false;
  88411. }
  88412. return this._attachedCamera.inertialRadiusOffset !== 0;
  88413. };
  88414. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88415. if (!this._attachedCamera) {
  88416. return false;
  88417. }
  88418. var zoomHasHitLimit = false;
  88419. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88420. zoomHasHitLimit = true;
  88421. }
  88422. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88423. this._lastFrameRadius = this._attachedCamera.radius;
  88424. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88425. };
  88426. /**
  88427. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88428. */
  88429. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88430. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88431. this._lastInteractionTime = BABYLON.Tools.Now;
  88432. }
  88433. };
  88434. // Tools
  88435. AutoRotationBehavior.prototype._userIsMoving = function () {
  88436. if (!this._attachedCamera) {
  88437. return false;
  88438. }
  88439. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88440. this._attachedCamera.inertialBetaOffset !== 0 ||
  88441. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88442. this._attachedCamera.inertialPanningX !== 0 ||
  88443. this._attachedCamera.inertialPanningY !== 0 ||
  88444. this._isPointerDown;
  88445. };
  88446. return AutoRotationBehavior;
  88447. }());
  88448. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88449. })(BABYLON || (BABYLON = {}));
  88450. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88451. var BABYLON;
  88452. (function (BABYLON) {
  88453. var NullEngineOptions = /** @class */ (function () {
  88454. function NullEngineOptions() {
  88455. this.renderWidth = 512;
  88456. this.renderHeight = 256;
  88457. this.textureSize = 512;
  88458. this.deterministicLockstep = false;
  88459. this.lockstepMaxSteps = 4;
  88460. }
  88461. return NullEngineOptions;
  88462. }());
  88463. BABYLON.NullEngineOptions = NullEngineOptions;
  88464. /**
  88465. * The null engine class provides support for headless version of babylon.js.
  88466. * This can be used in server side scenario or for testing purposes
  88467. */
  88468. var NullEngine = /** @class */ (function (_super) {
  88469. __extends(NullEngine, _super);
  88470. function NullEngine(options) {
  88471. if (options === void 0) { options = new NullEngineOptions(); }
  88472. var _this = _super.call(this, null) || this;
  88473. if (options.deterministicLockstep === undefined) {
  88474. options.deterministicLockstep = false;
  88475. }
  88476. if (options.lockstepMaxSteps === undefined) {
  88477. options.lockstepMaxSteps = 4;
  88478. }
  88479. _this._options = options;
  88480. // Init caps
  88481. // We consider we are on a webgl1 capable device
  88482. _this._caps = new BABYLON.EngineCapabilities();
  88483. _this._caps.maxTexturesImageUnits = 16;
  88484. _this._caps.maxVertexTextureImageUnits = 16;
  88485. _this._caps.maxTextureSize = 512;
  88486. _this._caps.maxCubemapTextureSize = 512;
  88487. _this._caps.maxRenderTextureSize = 512;
  88488. _this._caps.maxVertexAttribs = 16;
  88489. _this._caps.maxVaryingVectors = 16;
  88490. _this._caps.maxFragmentUniformVectors = 16;
  88491. _this._caps.maxVertexUniformVectors = 16;
  88492. // Extensions
  88493. _this._caps.standardDerivatives = false;
  88494. _this._caps.astc = null;
  88495. _this._caps.s3tc = null;
  88496. _this._caps.pvrtc = null;
  88497. _this._caps.etc1 = null;
  88498. _this._caps.etc2 = null;
  88499. _this._caps.textureAnisotropicFilterExtension = null;
  88500. _this._caps.maxAnisotropy = 0;
  88501. _this._caps.uintIndices = false;
  88502. _this._caps.fragmentDepthSupported = false;
  88503. _this._caps.highPrecisionShaderSupported = true;
  88504. _this._caps.colorBufferFloat = false;
  88505. _this._caps.textureFloat = false;
  88506. _this._caps.textureFloatLinearFiltering = false;
  88507. _this._caps.textureFloatRender = false;
  88508. _this._caps.textureHalfFloat = false;
  88509. _this._caps.textureHalfFloatLinearFiltering = false;
  88510. _this._caps.textureHalfFloatRender = false;
  88511. _this._caps.textureLOD = false;
  88512. _this._caps.drawBuffersExtension = false;
  88513. _this._caps.depthTextureExtension = false;
  88514. _this._caps.vertexArrayObject = false;
  88515. _this._caps.instancedArrays = false;
  88516. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88517. // Wrappers
  88518. if (typeof URL === "undefined") {
  88519. URL = {
  88520. createObjectURL: function () { },
  88521. revokeObjectURL: function () { }
  88522. };
  88523. }
  88524. if (typeof Blob === "undefined") {
  88525. Blob = function () { };
  88526. }
  88527. return _this;
  88528. }
  88529. NullEngine.prototype.isDeterministicLockStep = function () {
  88530. return this._options.deterministicLockstep;
  88531. };
  88532. NullEngine.prototype.getLockstepMaxSteps = function () {
  88533. return this._options.lockstepMaxSteps;
  88534. };
  88535. NullEngine.prototype.getHardwareScalingLevel = function () {
  88536. return 1.0;
  88537. };
  88538. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88539. return {
  88540. capacity: 0,
  88541. references: 1,
  88542. is32Bits: false
  88543. };
  88544. };
  88545. NullEngine.prototype.createIndexBuffer = function (indices) {
  88546. return {
  88547. capacity: 0,
  88548. references: 1,
  88549. is32Bits: false
  88550. };
  88551. };
  88552. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88553. if (stencil === void 0) { stencil = false; }
  88554. };
  88555. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88556. if (useScreen === void 0) { useScreen = false; }
  88557. if (!useScreen && this._currentRenderTarget) {
  88558. return this._currentRenderTarget.width;
  88559. }
  88560. return this._options.renderWidth;
  88561. };
  88562. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88563. if (useScreen === void 0) { useScreen = false; }
  88564. if (!useScreen && this._currentRenderTarget) {
  88565. return this._currentRenderTarget.height;
  88566. }
  88567. return this._options.renderHeight;
  88568. };
  88569. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88570. this._cachedViewport = viewport;
  88571. };
  88572. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88573. return {
  88574. transformFeedback: null,
  88575. __SPECTOR_rebuildProgram: null
  88576. };
  88577. };
  88578. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88579. return [];
  88580. };
  88581. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88582. return [];
  88583. };
  88584. NullEngine.prototype.bindSamplers = function (effect) {
  88585. this._currentEffect = null;
  88586. };
  88587. NullEngine.prototype.enableEffect = function (effect) {
  88588. this._currentEffect = effect;
  88589. if (effect.onBind) {
  88590. effect.onBind(effect);
  88591. }
  88592. effect.onBindObservable.notifyObservers(effect);
  88593. };
  88594. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88595. if (zOffset === void 0) { zOffset = 0; }
  88596. if (reverseSide === void 0) { reverseSide = false; }
  88597. };
  88598. NullEngine.prototype.setIntArray = function (uniform, array) {
  88599. };
  88600. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88601. };
  88602. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88603. };
  88604. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88605. };
  88606. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88607. };
  88608. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88609. };
  88610. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88611. };
  88612. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88613. };
  88614. NullEngine.prototype.setArray = function (uniform, array) {
  88615. };
  88616. NullEngine.prototype.setArray2 = function (uniform, array) {
  88617. };
  88618. NullEngine.prototype.setArray3 = function (uniform, array) {
  88619. };
  88620. NullEngine.prototype.setArray4 = function (uniform, array) {
  88621. };
  88622. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88623. };
  88624. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88625. };
  88626. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88627. };
  88628. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88629. };
  88630. NullEngine.prototype.setFloat = function (uniform, value) {
  88631. };
  88632. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88633. };
  88634. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88635. };
  88636. NullEngine.prototype.setBool = function (uniform, bool) {
  88637. };
  88638. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88639. };
  88640. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88641. };
  88642. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88643. };
  88644. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88645. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88646. if (this._alphaMode === mode) {
  88647. return;
  88648. }
  88649. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88650. if (!noDepthWriteChange) {
  88651. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88652. }
  88653. this._alphaMode = mode;
  88654. };
  88655. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88656. };
  88657. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88658. if (this.preventCacheWipeBetweenFrames) {
  88659. return;
  88660. }
  88661. this.resetTextureCache();
  88662. this._currentEffect = null;
  88663. if (bruteForce) {
  88664. this._currentProgram = null;
  88665. this._stencilState.reset();
  88666. this._depthCullingState.reset();
  88667. this._alphaState.reset();
  88668. }
  88669. this._cachedVertexBuffers = null;
  88670. this._cachedIndexBuffer = null;
  88671. this._cachedEffectForVertexBuffers = null;
  88672. };
  88673. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88674. };
  88675. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88676. };
  88677. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88678. };
  88679. NullEngine.prototype._createTexture = function () {
  88680. return {};
  88681. };
  88682. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88684. if (onLoad === void 0) { onLoad = null; }
  88685. if (onError === void 0) { onError = null; }
  88686. if (buffer === void 0) { buffer = null; }
  88687. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88688. var url = String(urlArg);
  88689. texture.url = url;
  88690. texture.generateMipMaps = !noMipmap;
  88691. texture.samplingMode = samplingMode;
  88692. texture.invertY = invertY;
  88693. texture.baseWidth = this._options.textureSize;
  88694. texture.baseHeight = this._options.textureSize;
  88695. texture.width = this._options.textureSize;
  88696. texture.height = this._options.textureSize;
  88697. if (format) {
  88698. texture.format = format;
  88699. }
  88700. texture.isReady = true;
  88701. if (onLoad) {
  88702. onLoad();
  88703. }
  88704. return texture;
  88705. };
  88706. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88707. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88708. if (options !== undefined && typeof options === "object") {
  88709. fullOptions.generateMipMaps = options.generateMipMaps;
  88710. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88711. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88712. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88713. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88714. }
  88715. else {
  88716. fullOptions.generateMipMaps = options;
  88717. fullOptions.generateDepthBuffer = true;
  88718. fullOptions.generateStencilBuffer = false;
  88719. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88720. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88721. }
  88722. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88723. var width = size.width || size;
  88724. var height = size.height || size;
  88725. texture._depthStencilBuffer = {};
  88726. texture._framebuffer = {};
  88727. texture.baseWidth = width;
  88728. texture.baseHeight = height;
  88729. texture.width = width;
  88730. texture.height = height;
  88731. texture.isReady = true;
  88732. texture.samples = 1;
  88733. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88734. texture.samplingMode = fullOptions.samplingMode;
  88735. texture.type = fullOptions.type;
  88736. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88737. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88738. return texture;
  88739. };
  88740. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88741. texture.samplingMode = samplingMode;
  88742. };
  88743. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88744. if (this._currentRenderTarget) {
  88745. this.unBindFramebuffer(this._currentRenderTarget);
  88746. }
  88747. this._currentRenderTarget = texture;
  88748. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88749. if (this._cachedViewport && !forceFullscreenViewport) {
  88750. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88751. }
  88752. };
  88753. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88754. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88755. this._currentRenderTarget = null;
  88756. if (onBeforeUnbind) {
  88757. if (texture._MSAAFramebuffer) {
  88758. this._currentFramebuffer = texture._framebuffer;
  88759. }
  88760. onBeforeUnbind();
  88761. }
  88762. this._currentFramebuffer = null;
  88763. };
  88764. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88765. var vbo = {
  88766. capacity: 1,
  88767. references: 1,
  88768. is32Bits: false
  88769. };
  88770. return vbo;
  88771. };
  88772. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88773. if (offset === void 0) { offset = 0; }
  88774. };
  88775. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88776. };
  88777. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88778. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88779. this._boundTexturesCache[this._activeChannel] = texture;
  88780. }
  88781. };
  88782. NullEngine.prototype._bindTexture = function (channel, texture) {
  88783. if (channel < 0) {
  88784. return;
  88785. }
  88786. this._bindTextureDirectly(0, texture);
  88787. };
  88788. NullEngine.prototype._releaseBuffer = function (buffer) {
  88789. buffer.references--;
  88790. if (buffer.references === 0) {
  88791. return true;
  88792. }
  88793. return false;
  88794. };
  88795. return NullEngine;
  88796. }(BABYLON.Engine));
  88797. BABYLON.NullEngine = NullEngine;
  88798. })(BABYLON || (BABYLON = {}));
  88799. //# sourceMappingURL=babylon.nullEngine.js.map
  88800. var BABYLON;
  88801. (function (BABYLON) {
  88802. /**
  88803. * This class can be used to get instrumentation data from a Babylon engine
  88804. */
  88805. var EngineInstrumentation = /** @class */ (function () {
  88806. function EngineInstrumentation(engine) {
  88807. this.engine = engine;
  88808. this._captureGPUFrameTime = false;
  88809. this._gpuFrameTime = new BABYLON.PerfCounter();
  88810. this._captureShaderCompilationTime = false;
  88811. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88812. // Observers
  88813. this._onBeginFrameObserver = null;
  88814. this._onEndFrameObserver = null;
  88815. this._onBeforeShaderCompilationObserver = null;
  88816. this._onAfterShaderCompilationObserver = null;
  88817. }
  88818. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88819. // Properties
  88820. /**
  88821. * Gets the perf counter used for GPU frame time
  88822. */
  88823. get: function () {
  88824. return this._gpuFrameTime;
  88825. },
  88826. enumerable: true,
  88827. configurable: true
  88828. });
  88829. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88830. /**
  88831. * Gets the GPU frame time capture status
  88832. */
  88833. get: function () {
  88834. return this._captureGPUFrameTime;
  88835. },
  88836. /**
  88837. * Enable or disable the GPU frame time capture
  88838. */
  88839. set: function (value) {
  88840. var _this = this;
  88841. if (value === this._captureGPUFrameTime) {
  88842. return;
  88843. }
  88844. this._captureGPUFrameTime = value;
  88845. if (value) {
  88846. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88847. if (!_this._gpuFrameTimeToken) {
  88848. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88849. }
  88850. });
  88851. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88852. if (!_this._gpuFrameTimeToken) {
  88853. return;
  88854. }
  88855. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88856. if (time > -1) {
  88857. _this._gpuFrameTimeToken = null;
  88858. _this._gpuFrameTime.fetchNewFrame();
  88859. _this._gpuFrameTime.addCount(time, true);
  88860. }
  88861. });
  88862. }
  88863. else {
  88864. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88865. this._onBeginFrameObserver = null;
  88866. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88867. this._onEndFrameObserver = null;
  88868. }
  88869. },
  88870. enumerable: true,
  88871. configurable: true
  88872. });
  88873. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88874. /**
  88875. * Gets the perf counter used for shader compilation time
  88876. */
  88877. get: function () {
  88878. return this._shaderCompilationTime;
  88879. },
  88880. enumerable: true,
  88881. configurable: true
  88882. });
  88883. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88884. /**
  88885. * Gets the shader compilation time capture status
  88886. */
  88887. get: function () {
  88888. return this._captureShaderCompilationTime;
  88889. },
  88890. /**
  88891. * Enable or disable the shader compilation time capture
  88892. */
  88893. set: function (value) {
  88894. var _this = this;
  88895. if (value === this._captureShaderCompilationTime) {
  88896. return;
  88897. }
  88898. this._captureShaderCompilationTime = value;
  88899. if (value) {
  88900. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88901. _this._shaderCompilationTime.fetchNewFrame();
  88902. _this._shaderCompilationTime.beginMonitoring();
  88903. });
  88904. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88905. _this._shaderCompilationTime.endMonitoring();
  88906. });
  88907. }
  88908. else {
  88909. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88910. this._onBeforeShaderCompilationObserver = null;
  88911. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88912. this._onAfterShaderCompilationObserver = null;
  88913. }
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. EngineInstrumentation.prototype.dispose = function () {
  88919. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88920. this._onBeginFrameObserver = null;
  88921. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88922. this._onEndFrameObserver = null;
  88923. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88924. this._onBeforeShaderCompilationObserver = null;
  88925. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88926. this._onAfterShaderCompilationObserver = null;
  88927. this.engine = null;
  88928. };
  88929. return EngineInstrumentation;
  88930. }());
  88931. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88932. })(BABYLON || (BABYLON = {}));
  88933. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88934. var BABYLON;
  88935. (function (BABYLON) {
  88936. /**
  88937. * This class can be used to get instrumentation data from a Babylon engine
  88938. */
  88939. var SceneInstrumentation = /** @class */ (function () {
  88940. function SceneInstrumentation(scene) {
  88941. var _this = this;
  88942. this.scene = scene;
  88943. this._captureActiveMeshesEvaluationTime = false;
  88944. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88945. this._captureRenderTargetsRenderTime = false;
  88946. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88947. this._captureFrameTime = false;
  88948. this._frameTime = new BABYLON.PerfCounter();
  88949. this._captureRenderTime = false;
  88950. this._renderTime = new BABYLON.PerfCounter();
  88951. this._captureInterFrameTime = false;
  88952. this._interFrameTime = new BABYLON.PerfCounter();
  88953. this._captureParticlesRenderTime = false;
  88954. this._particlesRenderTime = new BABYLON.PerfCounter();
  88955. this._captureSpritesRenderTime = false;
  88956. this._spritesRenderTime = new BABYLON.PerfCounter();
  88957. this._capturePhysicsTime = false;
  88958. this._physicsTime = new BABYLON.PerfCounter();
  88959. this._captureAnimationsTime = false;
  88960. this._animationsTime = new BABYLON.PerfCounter();
  88961. // Observers
  88962. this._onBeforeActiveMeshesEvaluationObserver = null;
  88963. this._onAfterActiveMeshesEvaluationObserver = null;
  88964. this._onBeforeRenderTargetsRenderObserver = null;
  88965. this._onAfterRenderTargetsRenderObserver = null;
  88966. this._onAfterRenderObserver = null;
  88967. this._onBeforeDrawPhaseObserver = null;
  88968. this._onAfterDrawPhaseObserver = null;
  88969. this._onBeforeAnimationsObserver = null;
  88970. this._onBeforeParticlesRenderingObserver = null;
  88971. this._onAfterParticlesRenderingObserver = null;
  88972. this._onBeforeSpritesRenderingObserver = null;
  88973. this._onAfterSpritesRenderingObserver = null;
  88974. this._onBeforePhysicsObserver = null;
  88975. this._onAfterPhysicsObserver = null;
  88976. this._onAfterAnimationsObserver = null;
  88977. // Before render
  88978. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88979. if (_this._captureActiveMeshesEvaluationTime) {
  88980. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88981. }
  88982. if (_this._captureRenderTargetsRenderTime) {
  88983. _this._renderTargetsRenderTime.fetchNewFrame();
  88984. }
  88985. if (_this._captureFrameTime) {
  88986. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88987. _this._frameTime.beginMonitoring();
  88988. }
  88989. if (_this._captureInterFrameTime) {
  88990. _this._interFrameTime.endMonitoring();
  88991. }
  88992. if (_this._captureParticlesRenderTime) {
  88993. _this._particlesRenderTime.fetchNewFrame();
  88994. }
  88995. if (_this._captureSpritesRenderTime) {
  88996. _this._spritesRenderTime.fetchNewFrame();
  88997. }
  88998. if (_this._captureAnimationsTime) {
  88999. _this._animationsTime.beginMonitoring();
  89000. }
  89001. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89002. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89003. });
  89004. // After render
  89005. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89006. if (_this._captureFrameTime) {
  89007. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89008. _this._frameTime.endMonitoring();
  89009. }
  89010. if (_this._captureRenderTime) {
  89011. _this._renderTime.endMonitoring(false);
  89012. }
  89013. if (_this._captureInterFrameTime) {
  89014. _this._interFrameTime.beginMonitoring();
  89015. }
  89016. });
  89017. }
  89018. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89019. // Properties
  89020. /**
  89021. * Gets the perf counter used for active meshes evaluation time
  89022. */
  89023. get: function () {
  89024. return this._activeMeshesEvaluationTime;
  89025. },
  89026. enumerable: true,
  89027. configurable: true
  89028. });
  89029. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89030. /**
  89031. * Gets the active meshes evaluation time capture status
  89032. */
  89033. get: function () {
  89034. return this._captureActiveMeshesEvaluationTime;
  89035. },
  89036. /**
  89037. * Enable or disable the active meshes evaluation time capture
  89038. */
  89039. set: function (value) {
  89040. var _this = this;
  89041. if (value === this._captureActiveMeshesEvaluationTime) {
  89042. return;
  89043. }
  89044. this._captureActiveMeshesEvaluationTime = value;
  89045. if (value) {
  89046. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89047. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89048. _this._activeMeshesEvaluationTime.beginMonitoring();
  89049. });
  89050. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89051. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89052. _this._activeMeshesEvaluationTime.endMonitoring();
  89053. });
  89054. }
  89055. else {
  89056. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89057. this._onBeforeActiveMeshesEvaluationObserver = null;
  89058. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89059. this._onAfterActiveMeshesEvaluationObserver = null;
  89060. }
  89061. },
  89062. enumerable: true,
  89063. configurable: true
  89064. });
  89065. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89066. /**
  89067. * Gets the perf counter used for render targets render time
  89068. */
  89069. get: function () {
  89070. return this._renderTargetsRenderTime;
  89071. },
  89072. enumerable: true,
  89073. configurable: true
  89074. });
  89075. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89076. /**
  89077. * Gets the render targets render time capture status
  89078. */
  89079. get: function () {
  89080. return this._captureRenderTargetsRenderTime;
  89081. },
  89082. /**
  89083. * Enable or disable the render targets render time capture
  89084. */
  89085. set: function (value) {
  89086. var _this = this;
  89087. if (value === this._captureRenderTargetsRenderTime) {
  89088. return;
  89089. }
  89090. this._captureRenderTargetsRenderTime = value;
  89091. if (value) {
  89092. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89093. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89094. _this._renderTargetsRenderTime.beginMonitoring();
  89095. });
  89096. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89097. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89098. _this._renderTargetsRenderTime.endMonitoring(false);
  89099. });
  89100. }
  89101. else {
  89102. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89103. this._onBeforeRenderTargetsRenderObserver = null;
  89104. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89105. this._onAfterRenderTargetsRenderObserver = null;
  89106. }
  89107. },
  89108. enumerable: true,
  89109. configurable: true
  89110. });
  89111. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89112. /**
  89113. * Gets the perf counter used for particles render time
  89114. */
  89115. get: function () {
  89116. return this._particlesRenderTime;
  89117. },
  89118. enumerable: true,
  89119. configurable: true
  89120. });
  89121. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89122. /**
  89123. * Gets the particles render time capture status
  89124. */
  89125. get: function () {
  89126. return this._captureParticlesRenderTime;
  89127. },
  89128. /**
  89129. * Enable or disable the particles render time capture
  89130. */
  89131. set: function (value) {
  89132. var _this = this;
  89133. if (value === this._captureParticlesRenderTime) {
  89134. return;
  89135. }
  89136. this._captureParticlesRenderTime = value;
  89137. if (value) {
  89138. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89139. BABYLON.Tools.StartPerformanceCounter("Particles");
  89140. _this._particlesRenderTime.beginMonitoring();
  89141. });
  89142. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89143. BABYLON.Tools.EndPerformanceCounter("Particles");
  89144. _this._particlesRenderTime.endMonitoring(false);
  89145. });
  89146. }
  89147. else {
  89148. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89149. this._onBeforeParticlesRenderingObserver = null;
  89150. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89151. this._onAfterParticlesRenderingObserver = null;
  89152. }
  89153. },
  89154. enumerable: true,
  89155. configurable: true
  89156. });
  89157. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89158. /**
  89159. * Gets the perf counter used for sprites render time
  89160. */
  89161. get: function () {
  89162. return this._spritesRenderTime;
  89163. },
  89164. enumerable: true,
  89165. configurable: true
  89166. });
  89167. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89168. /**
  89169. * Gets the sprites render time capture status
  89170. */
  89171. get: function () {
  89172. return this._captureSpritesRenderTime;
  89173. },
  89174. /**
  89175. * Enable or disable the sprites render time capture
  89176. */
  89177. set: function (value) {
  89178. var _this = this;
  89179. if (value === this._captureSpritesRenderTime) {
  89180. return;
  89181. }
  89182. this._captureSpritesRenderTime = value;
  89183. if (value) {
  89184. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89185. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89186. _this._spritesRenderTime.beginMonitoring();
  89187. });
  89188. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89189. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89190. _this._spritesRenderTime.endMonitoring(false);
  89191. });
  89192. }
  89193. else {
  89194. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89195. this._onBeforeSpritesRenderingObserver = null;
  89196. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89197. this._onAfterSpritesRenderingObserver = null;
  89198. }
  89199. },
  89200. enumerable: true,
  89201. configurable: true
  89202. });
  89203. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89204. /**
  89205. * Gets the perf counter used for physics time
  89206. */
  89207. get: function () {
  89208. return this._physicsTime;
  89209. },
  89210. enumerable: true,
  89211. configurable: true
  89212. });
  89213. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89214. /**
  89215. * Gets the physics time capture status
  89216. */
  89217. get: function () {
  89218. return this._capturePhysicsTime;
  89219. },
  89220. /**
  89221. * Enable or disable the physics time capture
  89222. */
  89223. set: function (value) {
  89224. var _this = this;
  89225. if (value === this._capturePhysicsTime) {
  89226. return;
  89227. }
  89228. this._capturePhysicsTime = value;
  89229. if (value) {
  89230. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89231. BABYLON.Tools.StartPerformanceCounter("Physics");
  89232. _this._physicsTime.beginMonitoring();
  89233. });
  89234. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89235. BABYLON.Tools.EndPerformanceCounter("Physics");
  89236. _this._physicsTime.endMonitoring();
  89237. });
  89238. }
  89239. else {
  89240. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89241. this._onBeforePhysicsObserver = null;
  89242. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89243. this._onAfterPhysicsObserver = null;
  89244. }
  89245. },
  89246. enumerable: true,
  89247. configurable: true
  89248. });
  89249. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89250. /**
  89251. * Gets the perf counter used for animations time
  89252. */
  89253. get: function () {
  89254. return this._animationsTime;
  89255. },
  89256. enumerable: true,
  89257. configurable: true
  89258. });
  89259. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89260. /**
  89261. * Gets the animations time capture status
  89262. */
  89263. get: function () {
  89264. return this._captureAnimationsTime;
  89265. },
  89266. /**
  89267. * Enable or disable the animations time capture
  89268. */
  89269. set: function (value) {
  89270. var _this = this;
  89271. if (value === this._captureAnimationsTime) {
  89272. return;
  89273. }
  89274. this._captureAnimationsTime = value;
  89275. if (value) {
  89276. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89277. _this._animationsTime.endMonitoring();
  89278. });
  89279. }
  89280. else {
  89281. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89282. this._onAfterAnimationsObserver = null;
  89283. }
  89284. },
  89285. enumerable: true,
  89286. configurable: true
  89287. });
  89288. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89289. /**
  89290. * Gets the perf counter used for frame time capture
  89291. */
  89292. get: function () {
  89293. return this._frameTime;
  89294. },
  89295. enumerable: true,
  89296. configurable: true
  89297. });
  89298. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89299. /**
  89300. * Gets the frame time capture status
  89301. */
  89302. get: function () {
  89303. return this._captureFrameTime;
  89304. },
  89305. /**
  89306. * Enable or disable the frame time capture
  89307. */
  89308. set: function (value) {
  89309. this._captureFrameTime = value;
  89310. },
  89311. enumerable: true,
  89312. configurable: true
  89313. });
  89314. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89315. /**
  89316. * Gets the perf counter used for inter-frames time capture
  89317. */
  89318. get: function () {
  89319. return this._interFrameTime;
  89320. },
  89321. enumerable: true,
  89322. configurable: true
  89323. });
  89324. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89325. /**
  89326. * Gets the inter-frames time capture status
  89327. */
  89328. get: function () {
  89329. return this._captureInterFrameTime;
  89330. },
  89331. /**
  89332. * Enable or disable the inter-frames time capture
  89333. */
  89334. set: function (value) {
  89335. this._captureInterFrameTime = value;
  89336. },
  89337. enumerable: true,
  89338. configurable: true
  89339. });
  89340. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89341. /**
  89342. * Gets the perf counter used for render time capture
  89343. */
  89344. get: function () {
  89345. return this._renderTime;
  89346. },
  89347. enumerable: true,
  89348. configurable: true
  89349. });
  89350. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89351. /**
  89352. * Gets the render time capture status
  89353. */
  89354. get: function () {
  89355. return this._captureRenderTime;
  89356. },
  89357. /**
  89358. * Enable or disable the render time capture
  89359. */
  89360. set: function (value) {
  89361. var _this = this;
  89362. if (value === this._captureRenderTime) {
  89363. return;
  89364. }
  89365. this._captureRenderTime = value;
  89366. if (value) {
  89367. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89368. _this._renderTime.beginMonitoring();
  89369. BABYLON.Tools.StartPerformanceCounter("Main render");
  89370. });
  89371. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89372. _this._renderTime.endMonitoring(false);
  89373. BABYLON.Tools.EndPerformanceCounter("Main render");
  89374. });
  89375. }
  89376. else {
  89377. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89378. this._onBeforeDrawPhaseObserver = null;
  89379. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89380. this._onAfterDrawPhaseObserver = null;
  89381. }
  89382. },
  89383. enumerable: true,
  89384. configurable: true
  89385. });
  89386. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89387. /**
  89388. * Gets the perf counter used for draw calls
  89389. */
  89390. get: function () {
  89391. return this.scene.getEngine()._drawCalls;
  89392. },
  89393. enumerable: true,
  89394. configurable: true
  89395. });
  89396. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89397. /**
  89398. * Gets the perf counter used for texture collisions
  89399. */
  89400. get: function () {
  89401. return this.scene.getEngine()._textureCollisions;
  89402. },
  89403. enumerable: true,
  89404. configurable: true
  89405. });
  89406. SceneInstrumentation.prototype.dispose = function () {
  89407. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89408. this._onAfterRenderObserver = null;
  89409. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89410. this._onBeforeActiveMeshesEvaluationObserver = null;
  89411. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89412. this._onAfterActiveMeshesEvaluationObserver = null;
  89413. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89414. this._onBeforeRenderTargetsRenderObserver = null;
  89415. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89416. this._onAfterRenderTargetsRenderObserver = null;
  89417. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89418. this._onBeforeAnimationsObserver = null;
  89419. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89420. this._onBeforeParticlesRenderingObserver = null;
  89421. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89422. this._onAfterParticlesRenderingObserver = null;
  89423. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89424. this._onBeforeSpritesRenderingObserver = null;
  89425. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89426. this._onAfterSpritesRenderingObserver = null;
  89427. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89428. this._onBeforeDrawPhaseObserver = null;
  89429. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89430. this._onAfterDrawPhaseObserver = null;
  89431. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89432. this._onBeforePhysicsObserver = null;
  89433. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89434. this._onAfterPhysicsObserver = null;
  89435. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89436. this._onAfterAnimationsObserver = null;
  89437. this.scene = null;
  89438. };
  89439. return SceneInstrumentation;
  89440. }());
  89441. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89442. })(BABYLON || (BABYLON = {}));
  89443. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89444. var BABYLON;
  89445. (function (BABYLON) {
  89446. var _TimeToken = /** @class */ (function () {
  89447. function _TimeToken() {
  89448. this._timeElapsedQueryEnded = false;
  89449. }
  89450. return _TimeToken;
  89451. }());
  89452. BABYLON._TimeToken = _TimeToken;
  89453. })(BABYLON || (BABYLON = {}));
  89454. //# sourceMappingURL=babylon.timeToken.js.map
  89455. var BABYLON;
  89456. (function (BABYLON) {
  89457. /**
  89458. * Background material defines definition.
  89459. * @ignore Mainly internal Use
  89460. */
  89461. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89462. __extends(BackgroundMaterialDefines, _super);
  89463. /**
  89464. * Constructor of the defines.
  89465. */
  89466. function BackgroundMaterialDefines() {
  89467. var _this = _super.call(this) || this;
  89468. /**
  89469. * True if the diffuse texture is in use.
  89470. */
  89471. _this.DIFFUSE = false;
  89472. /**
  89473. * The direct UV channel to use.
  89474. */
  89475. _this.DIFFUSEDIRECTUV = 0;
  89476. /**
  89477. * True if the diffuse texture is in gamma space.
  89478. */
  89479. _this.GAMMADIFFUSE = false;
  89480. /**
  89481. * True if the diffuse texture has opacity in the alpha channel.
  89482. */
  89483. _this.DIFFUSEHASALPHA = false;
  89484. /**
  89485. * True if you want the material to fade to transparent at grazing angle.
  89486. */
  89487. _this.OPACITYFRESNEL = false;
  89488. /**
  89489. * True if an extra blur needs to be added in the reflection.
  89490. */
  89491. _this.REFLECTIONBLUR = false;
  89492. /**
  89493. * True if you want the material to fade to reflection at grazing angle.
  89494. */
  89495. _this.REFLECTIONFRESNEL = false;
  89496. /**
  89497. * True if you want the material to falloff as far as you move away from the scene center.
  89498. */
  89499. _this.REFLECTIONFALLOFF = false;
  89500. /**
  89501. * False if the current Webgl implementation does not support the texture lod extension.
  89502. */
  89503. _this.TEXTURELODSUPPORT = false;
  89504. /**
  89505. * True to ensure the data are premultiplied.
  89506. */
  89507. _this.PREMULTIPLYALPHA = false;
  89508. /**
  89509. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89510. */
  89511. _this.USERGBCOLOR = false;
  89512. /**
  89513. * True to add noise in order to reduce the banding effect.
  89514. */
  89515. _this.NOISE = false;
  89516. /**
  89517. * is the reflection texture in BGR color scheme?
  89518. * Mainly used to solve a bug in ios10 video tag
  89519. */
  89520. _this.REFLECTIONBGR = false;
  89521. _this.IMAGEPROCESSING = false;
  89522. _this.VIGNETTE = false;
  89523. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89524. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89525. _this.TONEMAPPING = false;
  89526. _this.CONTRAST = false;
  89527. _this.COLORCURVES = false;
  89528. _this.COLORGRADING = false;
  89529. _this.COLORGRADING3D = false;
  89530. _this.SAMPLER3DGREENDEPTH = false;
  89531. _this.SAMPLER3DBGRMAP = false;
  89532. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89533. _this.EXPOSURE = false;
  89534. _this.GRAIN = false;
  89535. // Reflection.
  89536. _this.REFLECTION = false;
  89537. _this.REFLECTIONMAP_3D = false;
  89538. _this.REFLECTIONMAP_SPHERICAL = false;
  89539. _this.REFLECTIONMAP_PLANAR = false;
  89540. _this.REFLECTIONMAP_CUBIC = false;
  89541. _this.REFLECTIONMAP_PROJECTION = false;
  89542. _this.REFLECTIONMAP_SKYBOX = false;
  89543. _this.REFLECTIONMAP_EXPLICIT = false;
  89544. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89545. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89546. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89547. _this.INVERTCUBICMAP = false;
  89548. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89549. _this.LODINREFLECTIONALPHA = false;
  89550. _this.GAMMAREFLECTION = false;
  89551. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89552. // Default BJS.
  89553. _this.MAINUV1 = false;
  89554. _this.MAINUV2 = false;
  89555. _this.UV1 = false;
  89556. _this.UV2 = false;
  89557. _this.CLIPPLANE = false;
  89558. _this.POINTSIZE = false;
  89559. _this.FOG = false;
  89560. _this.NORMAL = false;
  89561. _this.NUM_BONE_INFLUENCERS = 0;
  89562. _this.BonesPerMesh = 0;
  89563. _this.INSTANCES = false;
  89564. _this.SHADOWFLOAT = false;
  89565. _this.rebuild();
  89566. return _this;
  89567. }
  89568. return BackgroundMaterialDefines;
  89569. }(BABYLON.MaterialDefines));
  89570. /**
  89571. * Background material used to create an efficient environement around your scene.
  89572. */
  89573. var BackgroundMaterial = /** @class */ (function (_super) {
  89574. __extends(BackgroundMaterial, _super);
  89575. /**
  89576. * Instantiates a Background Material in the given scene
  89577. * @param name The friendly name of the material
  89578. * @param scene The scene to add the material to
  89579. */
  89580. function BackgroundMaterial(name, scene) {
  89581. var _this = _super.call(this, name, scene) || this;
  89582. /**
  89583. * Key light Color (multiply against the R channel of the environement texture)
  89584. */
  89585. _this.primaryColor = BABYLON.Color3.White();
  89586. /**
  89587. * Key light Level (allowing HDR output of the background)
  89588. */
  89589. _this.primaryLevel = 1;
  89590. /**
  89591. * Secondary light Color (multiply against the G channel of the environement texture)
  89592. */
  89593. _this.secondaryColor = BABYLON.Color3.Gray();
  89594. /**
  89595. * Secondary light Level (allowing HDR output of the background)
  89596. */
  89597. _this.secondaryLevel = 1;
  89598. /**
  89599. * Tertiary light Color (multiply against the B channel of the environement texture)
  89600. */
  89601. _this.tertiaryColor = BABYLON.Color3.Black();
  89602. /**
  89603. * Tertiary light Level (allowing HDR output of the background)
  89604. */
  89605. _this.tertiaryLevel = 1;
  89606. /**
  89607. * Reflection Texture used in the material.
  89608. * Should be author in a specific way for the best result (refer to the documentation).
  89609. */
  89610. _this.reflectionTexture = null;
  89611. /**
  89612. * Reflection Texture level of blur.
  89613. *
  89614. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89615. * texture twice.
  89616. */
  89617. _this.reflectionBlur = 0;
  89618. /**
  89619. * Diffuse Texture used in the material.
  89620. * Should be author in a specific way for the best result (refer to the documentation).
  89621. */
  89622. _this.diffuseTexture = null;
  89623. _this._shadowLights = null;
  89624. /**
  89625. * Specify the list of lights casting shadow on the material.
  89626. * All scene shadow lights will be included if null.
  89627. */
  89628. _this.shadowLights = null;
  89629. /**
  89630. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89631. * soft lighting on the background.
  89632. */
  89633. _this.shadowBlurScale = 1;
  89634. /**
  89635. * Helps adjusting the shadow to a softer level if required.
  89636. * 0 means black shadows and 1 means no shadows.
  89637. */
  89638. _this.shadowLevel = 0;
  89639. /**
  89640. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89641. * It is usually zero but might be interesting to modify according to your setup.
  89642. */
  89643. _this.sceneCenter = BABYLON.Vector3.Zero();
  89644. /**
  89645. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89646. * This helps ensuring a nice transition when the camera goes under the ground.
  89647. */
  89648. _this.opacityFresnel = true;
  89649. /**
  89650. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89651. * This helps adding a mirror texture on the ground.
  89652. */
  89653. _this.reflectionFresnel = false;
  89654. /**
  89655. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89656. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89657. */
  89658. _this.reflectionFalloffDistance = 0.0;
  89659. /**
  89660. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89661. */
  89662. _this.reflectionAmount = 1.0;
  89663. /**
  89664. * This specifies the weight of the reflection at grazing angle.
  89665. */
  89666. _this.reflectionReflectance0 = 0.05;
  89667. /**
  89668. * This specifies the weight of the reflection at a perpendicular point of view.
  89669. */
  89670. _this.reflectionReflectance90 = 0.5;
  89671. /**
  89672. * Helps to directly use the maps channels instead of their level.
  89673. */
  89674. _this.useRGBColor = true;
  89675. /**
  89676. * This helps reducing the banding effect that could occur on the background.
  89677. */
  89678. _this.enableNoise = false;
  89679. _this._fovMultiplier = 1.0;
  89680. /**
  89681. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89682. * @type {boolean}
  89683. */
  89684. _this.useEquirectangularFOV = false;
  89685. _this._maxSimultaneousLights = 4;
  89686. /**
  89687. * Number of Simultaneous lights allowed on the material.
  89688. */
  89689. _this.maxSimultaneousLights = 4;
  89690. /**
  89691. * Keep track of the image processing observer to allow dispose and replace.
  89692. */
  89693. _this._imageProcessingObserver = null;
  89694. /**
  89695. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89696. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89697. */
  89698. _this.switchToBGR = false;
  89699. // Temp values kept as cache in the material.
  89700. _this._renderTargets = new BABYLON.SmartArray(16);
  89701. _this._reflectionControls = BABYLON.Vector4.Zero();
  89702. // Setup the default processing configuration to the scene.
  89703. _this._attachImageProcessingConfiguration(null);
  89704. _this.getRenderTargetTextures = function () {
  89705. _this._renderTargets.reset();
  89706. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89707. _this._renderTargets.push(_this._diffuseTexture);
  89708. }
  89709. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89710. _this._renderTargets.push(_this._reflectionTexture);
  89711. }
  89712. return _this._renderTargets;
  89713. };
  89714. return _this;
  89715. }
  89716. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89717. /**
  89718. * Sets the reflection reflectance fresnel values according to the default standard
  89719. * empirically know to work well :-)
  89720. */
  89721. set: function (value) {
  89722. var reflectionWeight = value;
  89723. if (reflectionWeight < 0.5) {
  89724. reflectionWeight = reflectionWeight * 2.0;
  89725. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89726. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89727. }
  89728. else {
  89729. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89730. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89731. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89732. }
  89733. },
  89734. enumerable: true,
  89735. configurable: true
  89736. });
  89737. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89738. /**
  89739. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89740. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89741. * Recommended to be keep at 1.0 except for special cases.
  89742. */
  89743. get: function () {
  89744. return this._fovMultiplier;
  89745. },
  89746. set: function (value) {
  89747. if (isNaN(value)) {
  89748. value = 1.0;
  89749. }
  89750. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89751. },
  89752. enumerable: true,
  89753. configurable: true
  89754. });
  89755. /**
  89756. * Attaches a new image processing configuration to the PBR Material.
  89757. * @param configuration (if null the scene configuration will be use)
  89758. */
  89759. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89760. var _this = this;
  89761. if (configuration === this._imageProcessingConfiguration) {
  89762. return;
  89763. }
  89764. // Detaches observer.
  89765. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89766. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89767. }
  89768. // Pick the scene configuration if needed.
  89769. if (!configuration) {
  89770. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89771. }
  89772. else {
  89773. this._imageProcessingConfiguration = configuration;
  89774. }
  89775. // Attaches observer.
  89776. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89777. _this._markAllSubMeshesAsImageProcessingDirty();
  89778. });
  89779. };
  89780. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89781. /**
  89782. * Gets the image processing configuration used either in this material.
  89783. */
  89784. get: function () {
  89785. return this._imageProcessingConfiguration;
  89786. },
  89787. /**
  89788. * Sets the Default image processing configuration used either in the this material.
  89789. *
  89790. * If sets to null, the scene one is in use.
  89791. */
  89792. set: function (value) {
  89793. this._attachImageProcessingConfiguration(value);
  89794. // Ensure the effect will be rebuilt.
  89795. this._markAllSubMeshesAsTexturesDirty();
  89796. },
  89797. enumerable: true,
  89798. configurable: true
  89799. });
  89800. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89801. /**
  89802. * Gets wether the color curves effect is enabled.
  89803. */
  89804. get: function () {
  89805. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89806. },
  89807. /**
  89808. * Sets wether the color curves effect is enabled.
  89809. */
  89810. set: function (value) {
  89811. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89812. },
  89813. enumerable: true,
  89814. configurable: true
  89815. });
  89816. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89817. /**
  89818. * Gets wether the color grading effect is enabled.
  89819. */
  89820. get: function () {
  89821. return this.imageProcessingConfiguration.colorGradingEnabled;
  89822. },
  89823. /**
  89824. * Gets wether the color grading effect is enabled.
  89825. */
  89826. set: function (value) {
  89827. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89828. },
  89829. enumerable: true,
  89830. configurable: true
  89831. });
  89832. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89833. /**
  89834. * Gets wether tonemapping is enabled or not.
  89835. */
  89836. get: function () {
  89837. return this._imageProcessingConfiguration.toneMappingEnabled;
  89838. },
  89839. /**
  89840. * Sets wether tonemapping is enabled or not
  89841. */
  89842. set: function (value) {
  89843. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89844. },
  89845. enumerable: true,
  89846. configurable: true
  89847. });
  89848. ;
  89849. ;
  89850. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89851. /**
  89852. * The camera exposure used on this material.
  89853. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89854. * This corresponds to a photographic exposure.
  89855. */
  89856. get: function () {
  89857. return this._imageProcessingConfiguration.exposure;
  89858. },
  89859. /**
  89860. * The camera exposure used on this material.
  89861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89862. * This corresponds to a photographic exposure.
  89863. */
  89864. set: function (value) {
  89865. this._imageProcessingConfiguration.exposure = value;
  89866. },
  89867. enumerable: true,
  89868. configurable: true
  89869. });
  89870. ;
  89871. ;
  89872. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89873. /**
  89874. * Gets The camera contrast used on this material.
  89875. */
  89876. get: function () {
  89877. return this._imageProcessingConfiguration.contrast;
  89878. },
  89879. /**
  89880. * Sets The camera contrast used on this material.
  89881. */
  89882. set: function (value) {
  89883. this._imageProcessingConfiguration.contrast = value;
  89884. },
  89885. enumerable: true,
  89886. configurable: true
  89887. });
  89888. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89889. /**
  89890. * Gets the Color Grading 2D Lookup Texture.
  89891. */
  89892. get: function () {
  89893. return this._imageProcessingConfiguration.colorGradingTexture;
  89894. },
  89895. /**
  89896. * Sets the Color Grading 2D Lookup Texture.
  89897. */
  89898. set: function (value) {
  89899. this.imageProcessingConfiguration.colorGradingTexture = value;
  89900. },
  89901. enumerable: true,
  89902. configurable: true
  89903. });
  89904. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89905. /**
  89906. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89907. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89908. * 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;
  89909. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89910. */
  89911. get: function () {
  89912. return this.imageProcessingConfiguration.colorCurves;
  89913. },
  89914. /**
  89915. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89916. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89917. * 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;
  89918. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89919. */
  89920. set: function (value) {
  89921. this.imageProcessingConfiguration.colorCurves = value;
  89922. },
  89923. enumerable: true,
  89924. configurable: true
  89925. });
  89926. /**
  89927. * The entire material has been created in order to prevent overdraw.
  89928. * @returns false
  89929. */
  89930. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89931. return true;
  89932. };
  89933. /**
  89934. * The entire material has been created in order to prevent overdraw.
  89935. * @returns true if blending is enable
  89936. */
  89937. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89938. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89939. };
  89940. /**
  89941. * Checks wether the material is ready to be rendered for a given mesh.
  89942. * @param mesh The mesh to render
  89943. * @param subMesh The submesh to check against
  89944. * @param useInstances Specify wether or not the material is used with instances
  89945. * @returns true if all the dependencies are ready (Textures, Effects...)
  89946. */
  89947. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89948. var _this = this;
  89949. if (useInstances === void 0) { useInstances = false; }
  89950. if (subMesh.effect && this.isFrozen) {
  89951. if (this._wasPreviouslyReady) {
  89952. return true;
  89953. }
  89954. }
  89955. if (!subMesh._materialDefines) {
  89956. subMesh._materialDefines = new BackgroundMaterialDefines();
  89957. }
  89958. var scene = this.getScene();
  89959. var defines = subMesh._materialDefines;
  89960. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89961. if (defines._renderId === scene.getRenderId()) {
  89962. return true;
  89963. }
  89964. }
  89965. var engine = scene.getEngine();
  89966. // Lights
  89967. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89968. defines._needNormals = true;
  89969. // Textures
  89970. if (defines._areTexturesDirty) {
  89971. defines._needUVs = false;
  89972. if (scene.texturesEnabled) {
  89973. if (scene.getEngine().getCaps().textureLOD) {
  89974. defines.TEXTURELODSUPPORT = true;
  89975. }
  89976. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89977. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89978. return false;
  89979. }
  89980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89981. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89982. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89983. defines.OPACITYFRESNEL = this._opacityFresnel;
  89984. }
  89985. else {
  89986. defines.DIFFUSE = false;
  89987. defines.DIFFUSEHASALPHA = false;
  89988. defines.GAMMADIFFUSE = false;
  89989. defines.OPACITYFRESNEL = false;
  89990. }
  89991. var reflectionTexture = this._reflectionTexture;
  89992. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89993. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89994. return false;
  89995. }
  89996. defines.REFLECTION = true;
  89997. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89998. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89999. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90000. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90001. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90002. defines.REFLECTIONBGR = this.switchToBGR;
  90003. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90004. defines.INVERTCUBICMAP = true;
  90005. }
  90006. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90007. switch (reflectionTexture.coordinatesMode) {
  90008. case BABYLON.Texture.CUBIC_MODE:
  90009. case BABYLON.Texture.INVCUBIC_MODE:
  90010. defines.REFLECTIONMAP_CUBIC = true;
  90011. break;
  90012. case BABYLON.Texture.EXPLICIT_MODE:
  90013. defines.REFLECTIONMAP_EXPLICIT = true;
  90014. break;
  90015. case BABYLON.Texture.PLANAR_MODE:
  90016. defines.REFLECTIONMAP_PLANAR = true;
  90017. break;
  90018. case BABYLON.Texture.PROJECTION_MODE:
  90019. defines.REFLECTIONMAP_PROJECTION = true;
  90020. break;
  90021. case BABYLON.Texture.SKYBOX_MODE:
  90022. defines.REFLECTIONMAP_SKYBOX = true;
  90023. break;
  90024. case BABYLON.Texture.SPHERICAL_MODE:
  90025. defines.REFLECTIONMAP_SPHERICAL = true;
  90026. break;
  90027. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90028. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90029. break;
  90030. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90031. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90032. break;
  90033. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90034. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90035. break;
  90036. }
  90037. if (this.reflectionFresnel) {
  90038. defines.REFLECTIONFRESNEL = true;
  90039. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90040. this._reflectionControls.x = this.reflectionAmount;
  90041. this._reflectionControls.y = this.reflectionReflectance0;
  90042. this._reflectionControls.z = this.reflectionReflectance90;
  90043. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90044. }
  90045. else {
  90046. defines.REFLECTIONFRESNEL = false;
  90047. defines.REFLECTIONFALLOFF = false;
  90048. }
  90049. }
  90050. else {
  90051. defines.REFLECTION = false;
  90052. defines.REFLECTIONFALLOFF = false;
  90053. defines.REFLECTIONBLUR = false;
  90054. defines.REFLECTIONMAP_3D = false;
  90055. defines.REFLECTIONMAP_SPHERICAL = false;
  90056. defines.REFLECTIONMAP_PLANAR = false;
  90057. defines.REFLECTIONMAP_CUBIC = false;
  90058. defines.REFLECTIONMAP_PROJECTION = false;
  90059. defines.REFLECTIONMAP_SKYBOX = false;
  90060. defines.REFLECTIONMAP_EXPLICIT = false;
  90061. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90062. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90063. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90064. defines.INVERTCUBICMAP = false;
  90065. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90066. defines.LODINREFLECTIONALPHA = false;
  90067. defines.GAMMAREFLECTION = false;
  90068. }
  90069. }
  90070. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90071. defines.USERGBCOLOR = this._useRGBColor;
  90072. defines.NOISE = this._enableNoise;
  90073. }
  90074. if (defines._areImageProcessingDirty) {
  90075. if (!this._imageProcessingConfiguration.isReady()) {
  90076. return false;
  90077. }
  90078. this._imageProcessingConfiguration.prepareDefines(defines);
  90079. }
  90080. // Misc.
  90081. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90082. // Values that need to be evaluated on every frame
  90083. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90084. // Attribs
  90085. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90086. if (mesh) {
  90087. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90088. mesh.createNormals(true);
  90089. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90090. }
  90091. }
  90092. }
  90093. // Get correct effect
  90094. if (defines.isDirty) {
  90095. defines.markAsProcessed();
  90096. scene.resetCachedMaterial();
  90097. // Fallbacks
  90098. var fallbacks = new BABYLON.EffectFallbacks();
  90099. if (defines.FOG) {
  90100. fallbacks.addFallback(0, "FOG");
  90101. }
  90102. if (defines.POINTSIZE) {
  90103. fallbacks.addFallback(1, "POINTSIZE");
  90104. }
  90105. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90106. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90107. fallbacks.addCPUSkinningFallback(0, mesh);
  90108. }
  90109. //Attributes
  90110. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90111. if (defines.NORMAL) {
  90112. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90113. }
  90114. if (defines.UV1) {
  90115. attribs.push(BABYLON.VertexBuffer.UVKind);
  90116. }
  90117. if (defines.UV2) {
  90118. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90119. }
  90120. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90121. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90122. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90123. "vFogInfos", "vFogColor", "pointSize",
  90124. "vClipPlane", "mBones",
  90125. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90126. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90127. "shadowLevel", "alpha",
  90128. "vBackgroundCenter", "vReflectionControl",
  90129. "vDiffuseInfos", "diffuseMatrix",
  90130. ];
  90131. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90132. var uniformBuffers = ["Material", "Scene"];
  90133. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90134. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90135. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90136. uniformsNames: uniforms,
  90137. uniformBuffersNames: uniformBuffers,
  90138. samplers: samplers,
  90139. defines: defines,
  90140. maxSimultaneousLights: this._maxSimultaneousLights
  90141. });
  90142. var onCompiled = function (effect) {
  90143. if (_this.onCompiled) {
  90144. _this.onCompiled(effect);
  90145. }
  90146. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90147. };
  90148. var join = defines.toString();
  90149. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90150. attributes: attribs,
  90151. uniformsNames: uniforms,
  90152. uniformBuffersNames: uniformBuffers,
  90153. samplers: samplers,
  90154. defines: join,
  90155. fallbacks: fallbacks,
  90156. onCompiled: onCompiled,
  90157. onError: this.onError,
  90158. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90159. }, engine), defines);
  90160. this.buildUniformLayout();
  90161. }
  90162. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90163. return false;
  90164. }
  90165. defines._renderId = scene.getRenderId();
  90166. this._wasPreviouslyReady = true;
  90167. return true;
  90168. };
  90169. /**
  90170. * Build the uniform buffer used in the material.
  90171. */
  90172. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90173. // Order is important !
  90174. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90175. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90176. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90177. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90178. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90179. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90180. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90181. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90182. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90183. this._uniformBuffer.addUniform("pointSize", 1);
  90184. this._uniformBuffer.addUniform("shadowLevel", 1);
  90185. this._uniformBuffer.addUniform("alpha", 1);
  90186. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90187. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90188. this._uniformBuffer.create();
  90189. };
  90190. /**
  90191. * Unbind the material.
  90192. */
  90193. BackgroundMaterial.prototype.unbind = function () {
  90194. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90195. this._uniformBuffer.setTexture("diffuseSampler", null);
  90196. }
  90197. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90198. this._uniformBuffer.setTexture("reflectionSampler", null);
  90199. }
  90200. _super.prototype.unbind.call(this);
  90201. };
  90202. /**
  90203. * Bind only the world matrix to the material.
  90204. * @param world The world matrix to bind.
  90205. */
  90206. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90207. this._activeEffect.setMatrix("world", world);
  90208. };
  90209. /**
  90210. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90211. * @param world The world matrix to bind.
  90212. * @param subMesh The submesh to bind for.
  90213. */
  90214. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90215. var scene = this.getScene();
  90216. var defines = subMesh._materialDefines;
  90217. if (!defines) {
  90218. return;
  90219. }
  90220. var effect = subMesh.effect;
  90221. if (!effect) {
  90222. return;
  90223. }
  90224. this._activeEffect = effect;
  90225. // Matrices
  90226. this.bindOnlyWorldMatrix(world);
  90227. // Bones
  90228. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90229. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90230. if (mustRebind) {
  90231. this._uniformBuffer.bindToEffect(effect, "Material");
  90232. this.bindViewProjection(effect);
  90233. var reflectionTexture = this._reflectionTexture;
  90234. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90235. // Texture uniforms
  90236. if (scene.texturesEnabled) {
  90237. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90238. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90239. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90240. }
  90241. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90242. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90243. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90244. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90245. }
  90246. }
  90247. if (this.shadowLevel > 0) {
  90248. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90249. }
  90250. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90251. // Point size
  90252. if (this.pointsCloud) {
  90253. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90254. }
  90255. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90256. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90257. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90258. }
  90259. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90260. // Textures
  90261. if (scene.texturesEnabled) {
  90262. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90263. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90264. }
  90265. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90266. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90267. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90268. }
  90269. else if (!defines.REFLECTIONBLUR) {
  90270. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90271. }
  90272. else {
  90273. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90274. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90275. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90276. }
  90277. if (defines.REFLECTIONFRESNEL) {
  90278. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90279. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90280. }
  90281. }
  90282. }
  90283. // Clip plane
  90284. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90285. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90286. }
  90287. if (mustRebind || !this.isFrozen) {
  90288. if (scene.lightsEnabled) {
  90289. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90290. }
  90291. // View
  90292. this.bindView(effect);
  90293. // Fog
  90294. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90295. // image processing
  90296. this._imageProcessingConfiguration.bind(this._activeEffect);
  90297. }
  90298. this._uniformBuffer.update();
  90299. this._afterBind(mesh);
  90300. };
  90301. /**
  90302. * Dispose the material.
  90303. * @param forceDisposeEffect Force disposal of the associated effect.
  90304. * @param forceDisposeTextures Force disposal of the associated textures.
  90305. */
  90306. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90307. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90308. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90309. if (forceDisposeTextures) {
  90310. if (this.diffuseTexture) {
  90311. this.diffuseTexture.dispose();
  90312. }
  90313. if (this.reflectionTexture) {
  90314. this.reflectionTexture.dispose();
  90315. }
  90316. }
  90317. this._renderTargets.dispose();
  90318. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90319. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90320. }
  90321. _super.prototype.dispose.call(this, forceDisposeEffect);
  90322. };
  90323. /**
  90324. * Clones the material.
  90325. * @param name The cloned name.
  90326. * @returns The cloned material.
  90327. */
  90328. BackgroundMaterial.prototype.clone = function (name) {
  90329. var _this = this;
  90330. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90331. };
  90332. /**
  90333. * Serializes the current material to its JSON representation.
  90334. * @returns The JSON representation.
  90335. */
  90336. BackgroundMaterial.prototype.serialize = function () {
  90337. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90338. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90339. return serializationObject;
  90340. };
  90341. /**
  90342. * Gets the class name of the material
  90343. * @returns "BackgroundMaterial"
  90344. */
  90345. BackgroundMaterial.prototype.getClassName = function () {
  90346. return "BackgroundMaterial";
  90347. };
  90348. /**
  90349. * Parse a JSON input to create back a background material.
  90350. * @param source The JSON data to parse
  90351. * @param scene The scene to create the parsed material in
  90352. * @param rootUrl The root url of the assets the material depends upon
  90353. * @returns the instantiated BackgroundMaterial.
  90354. */
  90355. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90356. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90357. };
  90358. /**
  90359. * Standard reflectance value at parallel view angle.
  90360. */
  90361. BackgroundMaterial.StandardReflectance0 = 0.05;
  90362. /**
  90363. * Standard reflectance value at grazing angle.
  90364. */
  90365. BackgroundMaterial.StandardReflectance90 = 0.5;
  90366. __decorate([
  90367. BABYLON.serializeAsColor3()
  90368. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90369. __decorate([
  90370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90371. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90372. __decorate([
  90373. BABYLON.serialize()
  90374. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90375. __decorate([
  90376. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90377. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90378. __decorate([
  90379. BABYLON.serializeAsColor3()
  90380. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90381. __decorate([
  90382. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90383. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90384. __decorate([
  90385. BABYLON.serialize()
  90386. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90387. __decorate([
  90388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90389. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90390. __decorate([
  90391. BABYLON.serializeAsColor3()
  90392. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90393. __decorate([
  90394. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90395. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90396. __decorate([
  90397. BABYLON.serialize()
  90398. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90399. __decorate([
  90400. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90401. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90402. __decorate([
  90403. BABYLON.serializeAsTexture()
  90404. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90405. __decorate([
  90406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90407. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90408. __decorate([
  90409. BABYLON.serialize()
  90410. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90411. __decorate([
  90412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90413. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90414. __decorate([
  90415. BABYLON.serializeAsTexture()
  90416. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90417. __decorate([
  90418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90419. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90420. __decorate([
  90421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90422. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90423. __decorate([
  90424. BABYLON.serialize()
  90425. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90426. __decorate([
  90427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90428. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90429. __decorate([
  90430. BABYLON.serialize()
  90431. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90432. __decorate([
  90433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90434. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90435. __decorate([
  90436. BABYLON.serializeAsVector3()
  90437. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90438. __decorate([
  90439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90440. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90441. __decorate([
  90442. BABYLON.serialize()
  90443. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90444. __decorate([
  90445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90446. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90447. __decorate([
  90448. BABYLON.serialize()
  90449. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90450. __decorate([
  90451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90452. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90453. __decorate([
  90454. BABYLON.serialize()
  90455. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90456. __decorate([
  90457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90458. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90459. __decorate([
  90460. BABYLON.serialize()
  90461. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90462. __decorate([
  90463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90464. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90465. __decorate([
  90466. BABYLON.serialize()
  90467. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90468. __decorate([
  90469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90470. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90471. __decorate([
  90472. BABYLON.serialize()
  90473. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90474. __decorate([
  90475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90476. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90477. __decorate([
  90478. BABYLON.serialize()
  90479. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90480. __decorate([
  90481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90482. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90483. __decorate([
  90484. BABYLON.serialize()
  90485. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90486. __decorate([
  90487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90488. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90489. __decorate([
  90490. BABYLON.serialize()
  90491. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90492. __decorate([
  90493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90494. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90495. __decorate([
  90496. BABYLON.serializeAsImageProcessingConfiguration()
  90497. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90498. return BackgroundMaterial;
  90499. }(BABYLON.PushMaterial));
  90500. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90501. })(BABYLON || (BABYLON = {}));
  90502. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90503. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90504. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90505. s = arguments[i];
  90506. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90507. t[p] = s[p];
  90508. }
  90509. return t;
  90510. };
  90511. var BABYLON;
  90512. (function (BABYLON) {
  90513. /**
  90514. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90515. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90516. * It also helps with the default setup of your imageProcessing configuration.
  90517. */
  90518. var EnvironmentHelper = /** @class */ (function () {
  90519. /**
  90520. * constructor
  90521. * @param options
  90522. * @param scene The scene to add the material to
  90523. */
  90524. function EnvironmentHelper(options, scene) {
  90525. var _this = this;
  90526. this._errorHandler = function (message, exception) {
  90527. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90528. };
  90529. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90530. this._scene = scene;
  90531. this.onErrorObservable = new BABYLON.Observable();
  90532. this._setupBackground();
  90533. this._setupImageProcessing();
  90534. }
  90535. /**
  90536. * Creates the default options for the helper.
  90537. */
  90538. EnvironmentHelper._getDefaultOptions = function () {
  90539. return {
  90540. createGround: true,
  90541. groundSize: 15,
  90542. groundTexture: this._groundTextureCDNUrl,
  90543. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90544. groundOpacity: 0.9,
  90545. enableGroundShadow: true,
  90546. groundShadowLevel: 0.5,
  90547. enableGroundMirror: false,
  90548. groundMirrorSizeRatio: 0.3,
  90549. groundMirrorBlurKernel: 64,
  90550. groundMirrorAmount: 1,
  90551. groundMirrorFresnelWeight: 1,
  90552. groundMirrorFallOffDistance: 0,
  90553. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90554. groundYBias: 0.00001,
  90555. createSkybox: true,
  90556. skyboxSize: 20,
  90557. skyboxTexture: this._skyboxTextureCDNUrl,
  90558. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90559. backgroundYRotation: 0,
  90560. sizeAuto: true,
  90561. rootPosition: BABYLON.Vector3.Zero(),
  90562. setupImageProcessing: true,
  90563. environmentTexture: this._environmentTextureCDNUrl,
  90564. cameraExposure: 0.8,
  90565. cameraContrast: 1.2,
  90566. toneMappingEnabled: true,
  90567. };
  90568. };
  90569. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90570. /**
  90571. * Gets the root mesh created by the helper.
  90572. */
  90573. get: function () {
  90574. return this._rootMesh;
  90575. },
  90576. enumerable: true,
  90577. configurable: true
  90578. });
  90579. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90580. /**
  90581. * Gets the skybox created by the helper.
  90582. */
  90583. get: function () {
  90584. return this._skybox;
  90585. },
  90586. enumerable: true,
  90587. configurable: true
  90588. });
  90589. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90590. /**
  90591. * Gets the skybox texture created by the helper.
  90592. */
  90593. get: function () {
  90594. return this._skyboxTexture;
  90595. },
  90596. enumerable: true,
  90597. configurable: true
  90598. });
  90599. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90600. /**
  90601. * Gets the skybox material created by the helper.
  90602. */
  90603. get: function () {
  90604. return this._skyboxMaterial;
  90605. },
  90606. enumerable: true,
  90607. configurable: true
  90608. });
  90609. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90610. /**
  90611. * Gets the ground mesh created by the helper.
  90612. */
  90613. get: function () {
  90614. return this._ground;
  90615. },
  90616. enumerable: true,
  90617. configurable: true
  90618. });
  90619. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90620. /**
  90621. * Gets the ground texture created by the helper.
  90622. */
  90623. get: function () {
  90624. return this._groundTexture;
  90625. },
  90626. enumerable: true,
  90627. configurable: true
  90628. });
  90629. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90630. /**
  90631. * Gets the ground mirror created by the helper.
  90632. */
  90633. get: function () {
  90634. return this._groundMirror;
  90635. },
  90636. enumerable: true,
  90637. configurable: true
  90638. });
  90639. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90640. /**
  90641. * Gets the ground mirror render list to helps pushing the meshes
  90642. * you wish in the ground reflection.
  90643. */
  90644. get: function () {
  90645. if (this._groundMirror) {
  90646. return this._groundMirror.renderList;
  90647. }
  90648. return null;
  90649. },
  90650. enumerable: true,
  90651. configurable: true
  90652. });
  90653. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90654. /**
  90655. * Gets the ground material created by the helper.
  90656. */
  90657. get: function () {
  90658. return this._groundMaterial;
  90659. },
  90660. enumerable: true,
  90661. configurable: true
  90662. });
  90663. /**
  90664. * Updates the background according to the new options
  90665. * @param options
  90666. */
  90667. EnvironmentHelper.prototype.updateOptions = function (options) {
  90668. var newOptions = __assign({}, this._options, options);
  90669. if (this._ground && !newOptions.createGround) {
  90670. this._ground.dispose();
  90671. this._ground = null;
  90672. }
  90673. if (this._groundMaterial && !newOptions.createGround) {
  90674. this._groundMaterial.dispose();
  90675. this._groundMaterial = null;
  90676. }
  90677. if (this._groundTexture) {
  90678. if (this._options.groundTexture != newOptions.groundTexture) {
  90679. this._groundTexture.dispose();
  90680. this._groundTexture = null;
  90681. }
  90682. }
  90683. if (this._skybox && !newOptions.createSkybox) {
  90684. this._skybox.dispose();
  90685. this._skybox = null;
  90686. }
  90687. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90688. this._skyboxMaterial.dispose();
  90689. this._skyboxMaterial = null;
  90690. }
  90691. if (this._skyboxTexture) {
  90692. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90693. this._skyboxTexture.dispose();
  90694. this._skyboxTexture = null;
  90695. }
  90696. }
  90697. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90698. this._groundMirror.dispose();
  90699. this._groundMirror = null;
  90700. }
  90701. if (this._scene.environmentTexture) {
  90702. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90703. this._scene.environmentTexture.dispose();
  90704. }
  90705. }
  90706. this._options = newOptions;
  90707. this._setupBackground();
  90708. this._setupImageProcessing();
  90709. };
  90710. /**
  90711. * Sets the primary color of all the available elements.
  90712. * @param color
  90713. */
  90714. EnvironmentHelper.prototype.setMainColor = function (color) {
  90715. if (this.groundMaterial) {
  90716. this.groundMaterial.primaryColor = color;
  90717. }
  90718. if (this.skyboxMaterial) {
  90719. this.skyboxMaterial.primaryColor = color;
  90720. }
  90721. if (this.groundMirror) {
  90722. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90723. }
  90724. };
  90725. /**
  90726. * Setup the image processing according to the specified options.
  90727. */
  90728. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90729. if (this._options.setupImageProcessing) {
  90730. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90731. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90732. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90733. this._setupEnvironmentTexture();
  90734. }
  90735. };
  90736. /**
  90737. * Setup the environment texture according to the specified options.
  90738. */
  90739. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90740. if (this._scene.environmentTexture) {
  90741. return;
  90742. }
  90743. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90744. this._scene.environmentTexture = this._options.environmentTexture;
  90745. return;
  90746. }
  90747. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90748. this._scene.environmentTexture = environmentTexture;
  90749. };
  90750. /**
  90751. * Setup the background according to the specified options.
  90752. */
  90753. EnvironmentHelper.prototype._setupBackground = function () {
  90754. if (!this._rootMesh) {
  90755. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90756. }
  90757. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90758. var sceneSize = this._getSceneSize();
  90759. if (this._options.createGround) {
  90760. this._setupGround(sceneSize);
  90761. this._setupGroundMaterial();
  90762. this._setupGroundDiffuseTexture();
  90763. if (this._options.enableGroundMirror) {
  90764. this._setupGroundMirrorTexture(sceneSize);
  90765. }
  90766. this._setupMirrorInGroundMaterial();
  90767. }
  90768. if (this._options.createSkybox) {
  90769. this._setupSkybox(sceneSize);
  90770. this._setupSkyboxMaterial();
  90771. this._setupSkyboxReflectionTexture();
  90772. }
  90773. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90774. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90775. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90776. };
  90777. /**
  90778. * Get the scene sizes according to the setup.
  90779. */
  90780. EnvironmentHelper.prototype._getSceneSize = function () {
  90781. var _this = this;
  90782. var groundSize = this._options.groundSize;
  90783. var skyboxSize = this._options.skyboxSize;
  90784. var rootPosition = this._options.rootPosition;
  90785. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90786. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90787. }
  90788. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90789. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90790. });
  90791. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90792. if (this._options.sizeAuto) {
  90793. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90794. this._scene.activeCamera.upperRadiusLimit) {
  90795. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90796. skyboxSize = groundSize;
  90797. }
  90798. var sceneDiagonalLenght = sceneDiagonal.length();
  90799. if (sceneDiagonalLenght > groundSize) {
  90800. groundSize = sceneDiagonalLenght * 2;
  90801. skyboxSize = groundSize;
  90802. }
  90803. // 10 % bigger.
  90804. groundSize *= 1.1;
  90805. skyboxSize *= 1.5;
  90806. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90807. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90808. }
  90809. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90810. };
  90811. /**
  90812. * Setup the ground according to the specified options.
  90813. */
  90814. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90815. var _this = this;
  90816. if (!this._ground) {
  90817. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90818. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90819. this._ground.parent = this._rootMesh;
  90820. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90821. }
  90822. this._ground.receiveShadows = this._options.enableGroundShadow;
  90823. };
  90824. /**
  90825. * Setup the ground material according to the specified options.
  90826. */
  90827. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90828. if (!this._groundMaterial) {
  90829. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90830. }
  90831. this._groundMaterial.alpha = this._options.groundOpacity;
  90832. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90833. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90834. this._groundMaterial.primaryLevel = 1;
  90835. this._groundMaterial.primaryColor = this._options.groundColor;
  90836. this._groundMaterial.secondaryLevel = 0;
  90837. this._groundMaterial.tertiaryLevel = 0;
  90838. this._groundMaterial.useRGBColor = false;
  90839. this._groundMaterial.enableNoise = true;
  90840. if (this._ground) {
  90841. this._ground.material = this._groundMaterial;
  90842. }
  90843. };
  90844. /**
  90845. * Setup the ground diffuse texture according to the specified options.
  90846. */
  90847. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90848. if (!this._groundMaterial) {
  90849. return;
  90850. }
  90851. if (this._groundTexture) {
  90852. return;
  90853. }
  90854. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90855. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90856. return;
  90857. }
  90858. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90859. diffuseTexture.gammaSpace = false;
  90860. diffuseTexture.hasAlpha = true;
  90861. this._groundMaterial.diffuseTexture = diffuseTexture;
  90862. };
  90863. /**
  90864. * Setup the ground mirror texture according to the specified options.
  90865. */
  90866. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90867. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90868. if (!this._groundMirror) {
  90869. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90870. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90871. this._groundMirror.anisotropicFilteringLevel = 1;
  90872. this._groundMirror.wrapU = wrapping;
  90873. this._groundMirror.wrapV = wrapping;
  90874. this._groundMirror.gammaSpace = false;
  90875. if (this._groundMirror.renderList) {
  90876. for (var i = 0; i < this._scene.meshes.length; i++) {
  90877. var mesh = this._scene.meshes[i];
  90878. if (mesh !== this._ground &&
  90879. mesh !== this._skybox &&
  90880. mesh !== this._rootMesh) {
  90881. this._groundMirror.renderList.push(mesh);
  90882. }
  90883. }
  90884. }
  90885. }
  90886. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90887. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90888. };
  90889. /**
  90890. * Setup the ground to receive the mirror texture.
  90891. */
  90892. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90893. if (this._groundMaterial) {
  90894. this._groundMaterial.reflectionTexture = this._groundMirror;
  90895. this._groundMaterial.reflectionFresnel = true;
  90896. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90897. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90898. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90899. }
  90900. };
  90901. /**
  90902. * Setup the skybox according to the specified options.
  90903. */
  90904. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90905. var _this = this;
  90906. if (!this._skybox) {
  90907. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90908. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90909. }
  90910. this._skybox.parent = this._rootMesh;
  90911. };
  90912. /**
  90913. * Setup the skybox material according to the specified options.
  90914. */
  90915. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90916. if (!this._skybox) {
  90917. return;
  90918. }
  90919. if (!this._skyboxMaterial) {
  90920. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90921. }
  90922. this._skyboxMaterial.useRGBColor = false;
  90923. this._skyboxMaterial.primaryLevel = 1;
  90924. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90925. this._skyboxMaterial.secondaryLevel = 0;
  90926. this._skyboxMaterial.tertiaryLevel = 0;
  90927. this._skyboxMaterial.enableNoise = true;
  90928. this._skybox.material = this._skyboxMaterial;
  90929. };
  90930. /**
  90931. * Setup the skybox reflection texture according to the specified options.
  90932. */
  90933. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90934. if (!this._skyboxMaterial) {
  90935. return;
  90936. }
  90937. if (this._skyboxTexture) {
  90938. return;
  90939. }
  90940. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90941. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90942. return;
  90943. }
  90944. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90945. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90946. this._skyboxTexture.gammaSpace = false;
  90947. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90948. };
  90949. /**
  90950. * Dispose all the elements created by the Helper.
  90951. */
  90952. EnvironmentHelper.prototype.dispose = function () {
  90953. if (this._groundMaterial) {
  90954. this._groundMaterial.dispose(true, true);
  90955. }
  90956. if (this._skyboxMaterial) {
  90957. this._skyboxMaterial.dispose(true, true);
  90958. }
  90959. this._rootMesh.dispose(false);
  90960. };
  90961. /**
  90962. * Default ground texture URL.
  90963. */
  90964. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90965. /**
  90966. * Default skybox texture URL.
  90967. */
  90968. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90969. /**
  90970. * Default environment texture URL.
  90971. */
  90972. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90973. return EnvironmentHelper;
  90974. }());
  90975. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90976. })(BABYLON || (BABYLON = {}));
  90977. //# sourceMappingURL=babylon.environmentHelper.js.map
  90978. var BABYLON;
  90979. (function (BABYLON) {
  90980. /**
  90981. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90982. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90983. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90984. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90985. */
  90986. var VideoDome = /** @class */ (function (_super) {
  90987. __extends(VideoDome, _super);
  90988. /**
  90989. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90990. * @param name Element's name, child elements will append suffixes for their own names.
  90991. * @param urlsOrVideo
  90992. * @param options An object containing optional or exposed sub element properties:
  90993. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90994. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90995. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90996. * @param options **loop=true** Automatically loop video on end.
  90997. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90998. */
  90999. function VideoDome(name, urlsOrVideo, options, scene) {
  91000. var _this = _super.call(this, name, scene) || this;
  91001. // set defaults and manage values
  91002. name = name || "videoDome";
  91003. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91004. options.clickToPlay = Boolean(options.clickToPlay);
  91005. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91006. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91007. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91008. // create
  91009. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91010. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91011. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91012. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91013. flat: false,
  91014. radius: options.size,
  91015. subdivisions: options.resolution,
  91016. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91017. }, scene);
  91018. // configure material
  91019. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91020. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91021. material.reflectionTexture = _this._videoTexture;
  91022. material.useEquirectangularFOV = true;
  91023. material.fovMultiplier = 1.0;
  91024. // configure mesh
  91025. _this._mesh.material = material;
  91026. _this._mesh.parent = _this;
  91027. // optional configuration
  91028. if (options.clickToPlay) {
  91029. scene.onPointerUp = function () {
  91030. _this._videoTexture.video.play();
  91031. };
  91032. }
  91033. return _this;
  91034. }
  91035. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91036. /**
  91037. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91038. * Also see the options.resolution property.
  91039. */
  91040. get: function () {
  91041. return this._material.fovMultiplier;
  91042. },
  91043. set: function (value) {
  91044. this._material.fovMultiplier = value;
  91045. },
  91046. enumerable: true,
  91047. configurable: true
  91048. });
  91049. /**
  91050. * Releases resources associated with this node.
  91051. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91052. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91053. */
  91054. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91055. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91056. this._videoTexture.dispose();
  91057. this._mesh.dispose();
  91058. this._material.dispose();
  91059. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91060. };
  91061. return VideoDome;
  91062. }(BABYLON.Node));
  91063. BABYLON.VideoDome = VideoDome;
  91064. })(BABYLON || (BABYLON = {}));
  91065. //# sourceMappingURL=babylon.videoDome.js.map
  91066. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+(direction+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91067. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91068. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91069. globalObject["BABYLON"] = BABYLON
  91070. return BABYLON;
  91071. });
  91072. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91073. /***/ }),
  91074. /* 1 */
  91075. /***/ (function(module, exports, __webpack_require__) {
  91076. "use strict";
  91077. Object.defineProperty(exports, "__esModule", { value: true });
  91078. var babylonjs_1 = __webpack_require__(0);
  91079. var helper_1 = __webpack_require__(2);
  91080. var HTMLMapper = (function () {
  91081. function HTMLMapper() {
  91082. }
  91083. HTMLMapper.prototype.map = function (element) {
  91084. var config = {};
  91085. var _loop_1 = function (attrIdx) {
  91086. var attr = element.attributes.item(attrIdx);
  91087. var split = attr.nodeName.split('.');
  91088. split.reduce(function (currentConfig, key, idx) {
  91089. var camelKey = helper_1.kebabToCamel(key);
  91090. if (idx === split.length - 1) {
  91091. var val = attr.nodeValue;
  91092. if (val === "true") {
  91093. val = true;
  91094. }
  91095. else if (val === "false") {
  91096. val = false;
  91097. }
  91098. else {
  91099. var isnum = /^\d+$/.test(val);
  91100. if (isnum) {
  91101. var number = parseFloat(val);
  91102. if (!isNaN(number)) {
  91103. val = number;
  91104. }
  91105. }
  91106. }
  91107. currentConfig[camelKey] = val;
  91108. }
  91109. else {
  91110. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91111. }
  91112. return currentConfig[camelKey];
  91113. }, config);
  91114. };
  91115. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91116. _loop_1(attrIdx);
  91117. }
  91118. return config;
  91119. };
  91120. return HTMLMapper;
  91121. }());
  91122. var JSONMapper = (function () {
  91123. function JSONMapper() {
  91124. }
  91125. JSONMapper.prototype.map = function (rawSource) {
  91126. return JSON.parse(rawSource);
  91127. };
  91128. return JSONMapper;
  91129. }());
  91130. var DOMMapper = (function () {
  91131. function DOMMapper() {
  91132. }
  91133. DOMMapper.prototype.map = function (baseElement) {
  91134. var htmlMapper = new HTMLMapper();
  91135. var config = htmlMapper.map(baseElement);
  91136. var traverseChildren = function (element, partConfig) {
  91137. var children = element.children;
  91138. if (children.length) {
  91139. for (var i = 0; i < children.length; ++i) {
  91140. var item = children.item(i);
  91141. var configMapped = htmlMapper.map(item);
  91142. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91143. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91144. partConfig[key] = [];
  91145. }
  91146. else {
  91147. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91148. partConfig.push(configMapped);
  91149. }
  91150. else if (partConfig[key]) {
  91151. element.setAttribute('array', 'true');
  91152. var oldItem = partConfig[key];
  91153. partConfig = [oldItem, configMapped];
  91154. }
  91155. else {
  91156. partConfig[key] = configMapped;
  91157. }
  91158. }
  91159. traverseChildren(item, partConfig[key] || configMapped);
  91160. }
  91161. }
  91162. return partConfig;
  91163. };
  91164. traverseChildren(baseElement, config);
  91165. return config;
  91166. };
  91167. return DOMMapper;
  91168. }());
  91169. var MapperManager = (function () {
  91170. function MapperManager() {
  91171. this.mappers = {
  91172. "html": new HTMLMapper(),
  91173. "json": new JSONMapper(),
  91174. "dom": new DOMMapper()
  91175. };
  91176. }
  91177. MapperManager.prototype.getMapper = function (type) {
  91178. if (!this.mappers[type]) {
  91179. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91180. }
  91181. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91182. };
  91183. MapperManager.prototype.registerMapper = function (type, mapper) {
  91184. this.mappers[type] = mapper;
  91185. };
  91186. MapperManager.DefaultMapper = 'json';
  91187. return MapperManager;
  91188. }());
  91189. exports.MapperManager = MapperManager;
  91190. exports.mapperManager = new MapperManager();
  91191. /***/ }),
  91192. /* 2 */
  91193. /***/ (function(module, exports, __webpack_require__) {
  91194. "use strict";
  91195. Object.defineProperty(exports, "__esModule", { value: true });
  91196. function isUrl(urlToCheck) {
  91197. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91198. return true;
  91199. }
  91200. return false;
  91201. }
  91202. exports.isUrl = isUrl;
  91203. function kebabToCamel(s) {
  91204. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91205. }
  91206. exports.kebabToCamel = kebabToCamel;
  91207. function camelToKebab(str) {
  91208. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91209. }
  91210. exports.camelToKebab = camelToKebab;
  91211. /***/ }),
  91212. /* 3 */
  91213. /***/ (function(module, exports, __webpack_require__) {
  91214. "use strict";
  91215. Object.defineProperty(exports, "__esModule", { value: true });
  91216. var babylonjs_1 = __webpack_require__(0);
  91217. var ViewerManager = (function () {
  91218. function ViewerManager() {
  91219. this.viewers = {};
  91220. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91221. }
  91222. ViewerManager.prototype.addViewer = function (viewer) {
  91223. this.viewers[viewer.getBaseId()] = viewer;
  91224. this._onViewerAdded(viewer);
  91225. };
  91226. ViewerManager.prototype.getViewerById = function (id) {
  91227. return this.viewers[id];
  91228. };
  91229. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91230. for (var id in this.viewers) {
  91231. if (this.viewers[id].containerElement === element) {
  91232. return this.getViewerById(id);
  91233. }
  91234. }
  91235. };
  91236. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91237. var _this = this;
  91238. return new Promise(function (resolve, reject) {
  91239. var localViewer = _this.getViewerById(id);
  91240. if (localViewer) {
  91241. return resolve(localViewer);
  91242. }
  91243. var viewerFunction = function (viewer) {
  91244. if (viewer.getBaseId() === id) {
  91245. resolve(viewer);
  91246. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91247. }
  91248. };
  91249. _this.onViewerAddedObservable.add(viewerFunction);
  91250. });
  91251. };
  91252. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91253. this.onViewerAdded && this.onViewerAdded(viewer);
  91254. this.onViewerAddedObservable.notifyObservers(viewer);
  91255. };
  91256. return ViewerManager;
  91257. }());
  91258. exports.ViewerManager = ViewerManager;
  91259. exports.viewerManager = new ViewerManager();
  91260. /***/ }),
  91261. /* 4 */
  91262. /***/ (function(module, exports, __webpack_require__) {
  91263. "use strict";
  91264. var __extends = (this && this.__extends) || (function () {
  91265. var extendStatics = Object.setPrototypeOf ||
  91266. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91267. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91268. return function (d, b) {
  91269. extendStatics(d, b);
  91270. function __() { this.constructor = d; }
  91271. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91272. };
  91273. })();
  91274. Object.defineProperty(exports, "__esModule", { value: true });
  91275. var viewer_1 = __webpack_require__(5);
  91276. var babylonjs_1 = __webpack_require__(0);
  91277. var DefaultViewer = (function (_super) {
  91278. __extends(DefaultViewer, _super);
  91279. function DefaultViewer(containerElement, initialConfiguration) {
  91280. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91281. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91282. _this.containerElement = containerElement;
  91283. _this.onModelLoaded = function (model) {
  91284. var hideLoadingDelay = 500;
  91285. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91286. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91287. }
  91288. setTimeout(function () {
  91289. _this.hideLoadingScreen();
  91290. }, hideLoadingDelay);
  91291. return;
  91292. };
  91293. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91294. return _this;
  91295. }
  91296. DefaultViewer.prototype.initScene = function () {
  91297. var _this = this;
  91298. return _super.prototype.initScene.call(this).then(function () {
  91299. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91300. return _this.scene;
  91301. });
  91302. };
  91303. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91304. var _this = this;
  91305. this.showLoadingScreen();
  91306. this.initNavbar();
  91307. var closeButton = document.getElementById('close-button');
  91308. if (closeButton) {
  91309. closeButton.addEventListener('pointerdown', function () {
  91310. _this.hideOverlayScreen();
  91311. });
  91312. }
  91313. return _super.prototype.onTemplatesLoaded.call(this);
  91314. };
  91315. DefaultViewer.prototype.initNavbar = function () {
  91316. var navbar = this.templateManager.getTemplate('navBar');
  91317. if (navbar) {
  91318. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91319. var navbarShown_1 = true;
  91320. var timeoutCancel_1;
  91321. var triggerNavbar = function (show, evt) {
  91322. if (show === void 0) { show = false; }
  91323. if (!navbar || evt.button > 0)
  91324. return;
  91325. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91326. if (show === navbarShown_1)
  91327. return;
  91328. if (show) {
  91329. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91330. navbarShown_1 = show;
  91331. }
  91332. else {
  91333. var visibilityTimeout = 2000;
  91334. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91335. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91336. }
  91337. timeoutCancel_1 = setTimeout(function () {
  91338. if (navbar) {
  91339. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91340. }
  91341. navbarShown_1 = show;
  91342. }, visibilityTimeout);
  91343. }
  91344. };
  91345. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91346. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91347. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91348. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91349. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91350. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91351. var triggerFullscren = function (eventData) {
  91352. if (viewerElement_1) {
  91353. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91354. if (!fullscreenElement) {
  91355. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91356. requestFullScreen.call(viewerElement_1);
  91357. }
  91358. else {
  91359. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91360. exitFullscreen.call(document);
  91361. }
  91362. }
  91363. };
  91364. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91365. }
  91366. };
  91367. DefaultViewer.prototype.prepareContainerElement = function () {
  91368. this.containerElement.style.position = 'relative';
  91369. this.containerElement.style.display = 'flex';
  91370. };
  91371. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91372. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91373. var navbar = this.templateManager.getTemplate('navBar');
  91374. if (!navbar)
  91375. return;
  91376. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91377. if (metadataContainer) {
  91378. if (modelConfiguration.title !== undefined) {
  91379. var element = metadataContainer.querySelector('span.model-title');
  91380. if (element) {
  91381. element.innerHTML = modelConfiguration.title;
  91382. }
  91383. }
  91384. if (modelConfiguration.subtitle !== undefined) {
  91385. var element = metadataContainer.querySelector('span.model-subtitle');
  91386. if (element) {
  91387. element.innerHTML = modelConfiguration.subtitle;
  91388. }
  91389. }
  91390. if (modelConfiguration.thumbnail !== undefined) {
  91391. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91392. }
  91393. }
  91394. };
  91395. DefaultViewer.prototype.loadModel = function (model) {
  91396. var _this = this;
  91397. if (model === void 0) { model = this.configuration.model; }
  91398. this.showLoadingScreen();
  91399. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91400. console.log(error);
  91401. _this.hideLoadingScreen();
  91402. _this.showOverlayScreen('error');
  91403. return Promise.reject(error);
  91404. });
  91405. };
  91406. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91407. var _this = this;
  91408. var template = this.templateManager.getTemplate('overlay');
  91409. if (!template)
  91410. return Promise.resolve('Overlay template not found');
  91411. return template.show((function (template) {
  91412. var canvasRect = _this.containerElement.getBoundingClientRect();
  91413. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91414. template.parent.style.display = 'flex';
  91415. template.parent.style.width = canvasRect.width + "px";
  91416. template.parent.style.height = canvasRect.height + "px";
  91417. template.parent.style.opacity = "1";
  91418. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91419. if (!subTemplate) {
  91420. return Promise.reject(subScreen + ' template not found');
  91421. }
  91422. return subTemplate.show((function (template) {
  91423. template.parent.style.display = 'flex';
  91424. return Promise.resolve(template);
  91425. }));
  91426. }));
  91427. };
  91428. DefaultViewer.prototype.hideOverlayScreen = function () {
  91429. var template = this.templateManager.getTemplate('overlay');
  91430. if (!template)
  91431. return Promise.resolve('Overlay template not found');
  91432. return template.hide((function (template) {
  91433. template.parent.style.opacity = "0";
  91434. var onTransitionEnd = function () {
  91435. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91436. template.parent.style.display = 'none';
  91437. };
  91438. template.parent.addEventListener("transitionend", onTransitionEnd);
  91439. var overlays = template.parent.querySelectorAll('.overlay');
  91440. if (overlays) {
  91441. for (var i = 0; i < overlays.length; ++i) {
  91442. var htmlElement = overlays.item(i);
  91443. htmlElement.style.display = 'none';
  91444. }
  91445. }
  91446. return Promise.resolve(template);
  91447. }));
  91448. };
  91449. DefaultViewer.prototype.showLoadingScreen = function () {
  91450. var _this = this;
  91451. var template = this.templateManager.getTemplate('loadingScreen');
  91452. if (!template)
  91453. return Promise.resolve('Loading Screen template not found');
  91454. return template.show((function (template) {
  91455. var canvasRect = _this.containerElement.getBoundingClientRect();
  91456. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91457. template.parent.style.display = 'flex';
  91458. template.parent.style.width = canvasRect.width + "px";
  91459. template.parent.style.height = canvasRect.height + "px";
  91460. template.parent.style.opacity = "1";
  91461. template.parent.style.backgroundColor = "black";
  91462. return Promise.resolve(template);
  91463. }));
  91464. };
  91465. DefaultViewer.prototype.hideLoadingScreen = function () {
  91466. var template = this.templateManager.getTemplate('loadingScreen');
  91467. if (!template)
  91468. return Promise.resolve('Loading Screen template not found');
  91469. return template.hide((function (template) {
  91470. template.parent.style.opacity = "0";
  91471. var onTransitionEnd = function () {
  91472. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91473. template.parent.style.display = 'none';
  91474. };
  91475. template.parent.addEventListener("transitionend", onTransitionEnd);
  91476. return Promise.resolve(template);
  91477. }));
  91478. };
  91479. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91480. var _this = this;
  91481. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91482. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  91483. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91484. var pointerPosition = BABYLON.Vector3.Zero();
  91485. var lightTarget_1;
  91486. var angle = 0.5;
  91487. var exponent = Math.PI / 2;
  91488. if (typeof this.configuration.lab.flashlight === "object") {
  91489. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91490. angle = this.configuration.lab.flashlight.angle || angle;
  91491. }
  91492. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91493. if (typeof this.configuration.lab.flashlight === "object") {
  91494. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91495. if (this.configuration.lab.flashlight.diffuse) {
  91496. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91497. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91498. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91499. }
  91500. if (this.configuration.lab.flashlight.specular) {
  91501. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91502. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91503. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91504. }
  91505. }
  91506. this.scene.constantlyUpdateMeshUnderPointer = true;
  91507. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91508. if (eventData.type === 4 && eventData.pickInfo) {
  91509. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91510. }
  91511. else {
  91512. lightTarget_1 = undefined;
  91513. }
  91514. });
  91515. var updateFlashlightFunction = function () {
  91516. if (_this.camera && flashlight) {
  91517. flashlight.position.copyFrom(_this.camera.position);
  91518. if (lightTarget_1) {
  91519. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91520. }
  91521. }
  91522. };
  91523. this.scene.registerBeforeRender(updateFlashlightFunction);
  91524. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91525. }
  91526. };
  91527. return DefaultViewer;
  91528. }(viewer_1.AbstractViewer));
  91529. exports.DefaultViewer = DefaultViewer;
  91530. /***/ }),
  91531. /* 5 */
  91532. /***/ (function(module, exports, __webpack_require__) {
  91533. "use strict";
  91534. Object.defineProperty(exports, "__esModule", { value: true });
  91535. var viewerManager_1 = __webpack_require__(3);
  91536. var templateManager_1 = __webpack_require__(19);
  91537. var loader_1 = __webpack_require__(22);
  91538. var babylonjs_1 = __webpack_require__(0);
  91539. var deepmerge = __webpack_require__(13);
  91540. var viewerModel_1 = __webpack_require__(30);
  91541. var AbstractViewer = (function () {
  91542. function AbstractViewer(containerElement, initialConfiguration) {
  91543. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91544. var _this = this;
  91545. this.containerElement = containerElement;
  91546. this.resize = function () {
  91547. if (!_this.isCanvasInDOM()) {
  91548. return;
  91549. }
  91550. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91551. return;
  91552. }
  91553. _this.engine.resize();
  91554. };
  91555. this.render = function () {
  91556. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91557. };
  91558. if (containerElement.id) {
  91559. this.baseId = containerElement.id;
  91560. }
  91561. else {
  91562. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91563. }
  91564. this.onSceneInitObservable = new babylonjs_1.Observable();
  91565. this.onEngineInitObservable = new babylonjs_1.Observable();
  91566. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91567. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91568. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91569. this.onInitDoneObservable = new babylonjs_1.Observable();
  91570. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91571. this.registeredOnBeforerenderFunctions = [];
  91572. this.models = [];
  91573. viewerManager_1.viewerManager.addViewer(this);
  91574. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91575. this.prepareContainerElement();
  91576. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91577. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91578. if (_this.configuration.observers) {
  91579. _this.configureObservers(_this.configuration.observers);
  91580. }
  91581. var templateConfiguration = _this.configuration.templates || {};
  91582. _this.templateManager.initTemplate(templateConfiguration);
  91583. _this.templateManager.onAllLoaded.add(function () {
  91584. var canvas = _this.templateManager.getCanvas();
  91585. if (canvas) {
  91586. _this.canvas = canvas;
  91587. }
  91588. _this._onTemplateLoaded();
  91589. });
  91590. });
  91591. }
  91592. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91593. get: function () {
  91594. return this._hdrSupport;
  91595. },
  91596. enumerable: true,
  91597. configurable: true
  91598. });
  91599. AbstractViewer.prototype.getBaseId = function () {
  91600. return this.baseId;
  91601. };
  91602. AbstractViewer.prototype.isCanvasInDOM = function () {
  91603. return !!this.canvas && !!this.canvas.parentElement;
  91604. };
  91605. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91606. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91607. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91608. if (newConfiguration.scene) {
  91609. this.configureScene(newConfiguration.scene);
  91610. }
  91611. if (newConfiguration.optimizer) {
  91612. this.configureOptimizer(newConfiguration.optimizer);
  91613. }
  91614. if (newConfiguration.observers) {
  91615. this.configureObservers(newConfiguration.observers);
  91616. }
  91617. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91618. this.configureModel(newConfiguration.model);
  91619. }
  91620. if (newConfiguration.lights) {
  91621. this.configureLights(newConfiguration.lights);
  91622. }
  91623. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91624. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91625. }
  91626. if (newConfiguration.camera) {
  91627. this.configureCamera(newConfiguration.camera);
  91628. }
  91629. };
  91630. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91631. if (!skyboxConifguration && !groundConfiguration) {
  91632. if (this.environmentHelper) {
  91633. this.environmentHelper.dispose();
  91634. delete this.environmentHelper;
  91635. }
  91636. ;
  91637. return Promise.resolve(this.scene);
  91638. }
  91639. var options = {
  91640. createGround: !!groundConfiguration,
  91641. createSkybox: !!skyboxConifguration,
  91642. setupImageProcessing: false
  91643. };
  91644. if (groundConfiguration) {
  91645. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91646. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91647. if (groundSize) {
  91648. options.groundSize = groundSize;
  91649. }
  91650. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91651. if (groundConfig.shadowLevel !== undefined) {
  91652. options.groundShadowLevel = groundConfig.shadowLevel;
  91653. }
  91654. options.enableGroundMirror = !!groundConfig.mirror;
  91655. if (groundConfig.texture) {
  91656. options.groundTexture = groundConfig.texture;
  91657. }
  91658. if (groundConfig.color) {
  91659. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91660. }
  91661. if (groundConfig.opacity !== undefined) {
  91662. options.groundOpacity = groundConfig.opacity;
  91663. }
  91664. if (groundConfig.mirror) {
  91665. options.enableGroundMirror = true;
  91666. if (typeof groundConfig.mirror === "object") {
  91667. if (groundConfig.mirror.amount !== undefined)
  91668. options.groundMirrorAmount = groundConfig.mirror.amount;
  91669. if (groundConfig.mirror.sizeRatio !== undefined)
  91670. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91671. if (groundConfig.mirror.blurKernel !== undefined)
  91672. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91673. if (groundConfig.mirror.fresnelWeight !== undefined)
  91674. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91675. if (groundConfig.mirror.fallOffDistance !== undefined)
  91676. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91677. if (this.defaultPipelineTextureType !== undefined)
  91678. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91679. }
  91680. }
  91681. }
  91682. var postInitSkyboxMaterial = false;
  91683. if (skyboxConifguration) {
  91684. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91685. if (conf.material && conf.material.imageProcessingConfiguration) {
  91686. options.setupImageProcessing = false;
  91687. }
  91688. var skyboxSize = conf.scale;
  91689. if (skyboxSize) {
  91690. options.skyboxSize = skyboxSize;
  91691. }
  91692. options.sizeAuto = !options.skyboxSize;
  91693. if (conf.color) {
  91694. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91695. }
  91696. if (conf.cubeTexture && conf.cubeTexture.url) {
  91697. if (typeof conf.cubeTexture.url === "string") {
  91698. options.skyboxTexture = conf.cubeTexture.url;
  91699. }
  91700. else {
  91701. postInitSkyboxMaterial = true;
  91702. }
  91703. }
  91704. if (conf.material && conf.material.imageProcessingConfiguration) {
  91705. postInitSkyboxMaterial = true;
  91706. }
  91707. }
  91708. options.setupImageProcessing = false;
  91709. if (!this.environmentHelper) {
  91710. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91711. }
  91712. else {
  91713. var scene = this.environmentHelper.rootMesh.getScene();
  91714. if (scene !== this.scene) {
  91715. this.environmentHelper.dispose();
  91716. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91717. }
  91718. else {
  91719. this.environmentHelper.updateOptions(options);
  91720. }
  91721. }
  91722. if (postInitSkyboxMaterial) {
  91723. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  91724. if (skyboxMaterial) {
  91725. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  91726. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  91727. }
  91728. }
  91729. }
  91730. };
  91731. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  91732. if (!this.scene) {
  91733. return;
  91734. }
  91735. if (sceneConfig.debug) {
  91736. this.scene.debugLayer.show();
  91737. }
  91738. else {
  91739. if (this.scene.debugLayer.isVisible()) {
  91740. this.scene.debugLayer.hide();
  91741. }
  91742. }
  91743. if (sceneConfig.clearColor) {
  91744. var cc = sceneConfig.clearColor;
  91745. var oldcc = this.scene.clearColor;
  91746. if (cc.r !== undefined) {
  91747. oldcc.r = cc.r;
  91748. }
  91749. if (cc.g !== undefined) {
  91750. oldcc.g = cc.g;
  91751. }
  91752. if (cc.b !== undefined) {
  91753. oldcc.b = cc.b;
  91754. }
  91755. if (cc.a !== undefined) {
  91756. oldcc.a = cc.a;
  91757. }
  91758. }
  91759. if (sceneConfig.imageProcessingConfiguration) {
  91760. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  91761. }
  91762. if (sceneConfig.environmentTexture) {
  91763. if (this.scene.environmentTexture) {
  91764. this.scene.environmentTexture.dispose();
  91765. }
  91766. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  91767. this.scene.environmentTexture = environmentTexture;
  91768. }
  91769. if (sceneConfig.autoRotate) {
  91770. this.camera.useAutoRotationBehavior = true;
  91771. }
  91772. };
  91773. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  91774. if (typeof optimizerConfig === 'boolean') {
  91775. if (this.sceneOptimizer) {
  91776. this.sceneOptimizer.stop();
  91777. this.sceneOptimizer.dispose();
  91778. delete this.sceneOptimizer;
  91779. }
  91780. if (optimizerConfig) {
  91781. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  91782. this.sceneOptimizer.start();
  91783. }
  91784. }
  91785. else {
  91786. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  91787. if (optimizerConfig.degradation) {
  91788. switch (optimizerConfig.degradation) {
  91789. case "low":
  91790. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  91791. break;
  91792. case "moderate":
  91793. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  91794. break;
  91795. case "hight":
  91796. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  91797. break;
  91798. }
  91799. }
  91800. if (this.sceneOptimizer) {
  91801. this.sceneOptimizer.stop();
  91802. this.sceneOptimizer.dispose();
  91803. }
  91804. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  91805. this.sceneOptimizer.start();
  91806. }
  91807. };
  91808. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  91809. if (observersConfiguration.onEngineInit) {
  91810. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  91811. }
  91812. else {
  91813. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  91814. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  91815. }
  91816. }
  91817. if (observersConfiguration.onSceneInit) {
  91818. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  91819. }
  91820. else {
  91821. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  91822. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  91823. }
  91824. }
  91825. if (observersConfiguration.onModelLoaded) {
  91826. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  91827. }
  91828. else {
  91829. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  91830. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  91831. }
  91832. }
  91833. };
  91834. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  91835. var _this = this;
  91836. var focusMeshes = model ? model.meshes : this.scene.meshes;
  91837. if (!this.scene.activeCamera) {
  91838. this.scene.createDefaultCamera(true, true, true);
  91839. this.camera = this.scene.activeCamera;
  91840. }
  91841. if (cameraConfig.position) {
  91842. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  91843. }
  91844. if (cameraConfig.rotation) {
  91845. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  91846. }
  91847. this.extendClassWithConfig(this.camera, cameraConfig);
  91848. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  91849. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  91850. if (cameraConfig.behaviors) {
  91851. for (var name_1 in cameraConfig.behaviors) {
  91852. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  91853. }
  91854. }
  91855. ;
  91856. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  91857. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  91858. });
  91859. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91860. var sceneDiagonalLenght = sceneDiagonal.length();
  91861. if (isFinite(sceneDiagonalLenght))
  91862. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  91863. };
  91864. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91865. var _this = this;
  91866. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91867. var focusMeshes = model ? model.meshes : this.scene.meshes;
  91868. if (!Object.keys(lightsConfiguration).length)
  91869. return;
  91870. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  91871. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  91872. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  91873. lightsAvailable.forEach(function (lName) {
  91874. if (lightsToConfigure.indexOf(lName) === -1) {
  91875. _this.scene.getLightByName(lName).dispose();
  91876. }
  91877. });
  91878. }
  91879. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  91880. var lightConfig = { type: 0 };
  91881. if (typeof lightsConfiguration[name] === 'object') {
  91882. lightConfig = lightsConfiguration[name];
  91883. }
  91884. lightConfig.name = name;
  91885. var light;
  91886. if (lightsAvailable.indexOf(name) === -1) {
  91887. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91888. if (!constructor)
  91889. return;
  91890. light = constructor();
  91891. }
  91892. else {
  91893. light = _this.scene.getLightByName(name);
  91894. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  91895. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  91896. light.dispose();
  91897. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91898. if (!constructor)
  91899. return;
  91900. light = constructor();
  91901. }
  91902. }
  91903. if (lightsConfiguration[name] === false) {
  91904. light.dispose();
  91905. return;
  91906. }
  91907. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  91908. light.setEnabled(enabled);
  91909. _this.extendClassWithConfig(light, lightConfig);
  91910. if (light instanceof babylonjs_1.ShadowLight) {
  91911. if (lightConfig.target) {
  91912. if (light.setDirectionToTarget) {
  91913. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  91914. light.setDirectionToTarget(target);
  91915. }
  91916. }
  91917. else if (lightConfig.direction) {
  91918. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  91919. light.direction = direction;
  91920. }
  91921. var shadowGenerator = light.getShadowGenerator();
  91922. if (lightConfig.shadowEnabled && _this.maxShadows) {
  91923. if (!shadowGenerator) {
  91924. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  91925. }
  91926. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  91927. var shadownMap = shadowGenerator.getShadowMap();
  91928. if (!shadownMap)
  91929. return;
  91930. var renderList = shadownMap.renderList;
  91931. for (var index = 0; index < focusMeshes.length; index++) {
  91932. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  91933. renderList && renderList.push(focusMeshes[index]);
  91934. }
  91935. }
  91936. }
  91937. else if (shadowGenerator) {
  91938. shadowGenerator.dispose();
  91939. }
  91940. }
  91941. });
  91942. };
  91943. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  91944. var focusMeshes = model ? model.meshes : this.scene.meshes;
  91945. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  91946. var updateMeshesWithNoParent = function (variable, value, param) {
  91947. meshesWithNoParent.forEach(function (mesh) {
  91948. if (param) {
  91949. mesh[variable][param] = value;
  91950. }
  91951. else {
  91952. mesh[variable] = value;
  91953. }
  91954. });
  91955. };
  91956. var updateXYZ = function (variable, configValues) {
  91957. if (configValues.x !== undefined) {
  91958. updateMeshesWithNoParent(variable, configValues.x, 'x');
  91959. }
  91960. if (configValues.y !== undefined) {
  91961. updateMeshesWithNoParent(variable, configValues.y, 'y');
  91962. }
  91963. if (configValues.z !== undefined) {
  91964. updateMeshesWithNoParent(variable, configValues.z, 'z');
  91965. }
  91966. if (configValues.w !== undefined) {
  91967. updateMeshesWithNoParent(variable, configValues.w, 'w');
  91968. }
  91969. };
  91970. if (modelConfiguration.position) {
  91971. updateXYZ('position', modelConfiguration.position);
  91972. }
  91973. if (modelConfiguration.rotation) {
  91974. if (modelConfiguration.rotation.w) {
  91975. meshesWithNoParent.forEach(function (mesh) {
  91976. if (!mesh.rotationQuaternion) {
  91977. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  91978. }
  91979. });
  91980. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  91981. }
  91982. else {
  91983. updateXYZ('rotation', modelConfiguration.rotation);
  91984. }
  91985. }
  91986. if (modelConfiguration.scaling) {
  91987. updateXYZ('scaling', modelConfiguration.scaling);
  91988. }
  91989. if (modelConfiguration.castShadow) {
  91990. focusMeshes.forEach(function (mesh) {
  91991. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  91992. });
  91993. }
  91994. if (modelConfiguration.normalize) {
  91995. var center = false;
  91996. var unitSize = false;
  91997. var parentIndex = void 0;
  91998. if (modelConfiguration.normalize === true) {
  91999. center = true;
  92000. unitSize = true;
  92001. parentIndex = 0;
  92002. }
  92003. else {
  92004. center = !!modelConfiguration.normalize.center;
  92005. unitSize = !!modelConfiguration.normalize.unitSize;
  92006. parentIndex = modelConfiguration.normalize.parentIndex;
  92007. }
  92008. var meshesToNormalize = [];
  92009. if (parentIndex !== undefined) {
  92010. meshesToNormalize.push(focusMeshes[parentIndex]);
  92011. }
  92012. else {
  92013. meshesToNormalize = meshesWithNoParent;
  92014. }
  92015. if (unitSize) {
  92016. meshesToNormalize.forEach(function (mesh) {
  92017. mesh.normalizeToUnitCube(true);
  92018. mesh.computeWorldMatrix(true);
  92019. });
  92020. }
  92021. if (center) {
  92022. meshesToNormalize.forEach(function (mesh) {
  92023. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92024. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92025. var halfSizeVec = sizeVec.scale(0.5);
  92026. var center = boundingInfo.min.add(halfSizeVec);
  92027. mesh.position = center.scale(-1);
  92028. mesh.position.y += halfSizeVec.y;
  92029. mesh.computeWorldMatrix(true);
  92030. });
  92031. }
  92032. }
  92033. };
  92034. AbstractViewer.prototype.dispose = function () {
  92035. window.removeEventListener('resize', this.resize);
  92036. if (this.sceneOptimizer) {
  92037. this.sceneOptimizer.stop();
  92038. this.sceneOptimizer.dispose();
  92039. }
  92040. if (this.scene.activeCamera) {
  92041. this.scene.activeCamera.detachControl(this.canvas);
  92042. }
  92043. this.scene.dispose();
  92044. this.engine.dispose();
  92045. this.templateManager.dispose();
  92046. };
  92047. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92048. return Promise.resolve(this);
  92049. };
  92050. AbstractViewer.prototype._onTemplateLoaded = function () {
  92051. var _this = this;
  92052. return this.onTemplatesLoaded().then(function () {
  92053. var autoLoadModel = !!_this.configuration.model;
  92054. return _this.initEngine().then(function (engine) {
  92055. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92056. }).then(function () {
  92057. if (autoLoadModel) {
  92058. return _this.loadModel().then(function () { return _this.scene; });
  92059. }
  92060. else {
  92061. return _this.scene || _this.initScene();
  92062. }
  92063. }).then(function (scene) {
  92064. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92065. }).then(function () {
  92066. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92067. });
  92068. });
  92069. };
  92070. AbstractViewer.prototype.initEngine = function () {
  92071. this.injectCustomShaders();
  92072. var canvasElement = this.templateManager.getCanvas();
  92073. if (!canvasElement) {
  92074. return Promise.reject('Canvas element not found!');
  92075. }
  92076. var config = this.configuration.engine || {};
  92077. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92078. babylonjs_1.Database.IDBStorageEnabled = false;
  92079. if (!config.disableResize) {
  92080. window.addEventListener('resize', this.resize);
  92081. }
  92082. this.engine.runRenderLoop(this.render);
  92083. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92084. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92085. this.engine.setHardwareScalingLevel(scale);
  92086. }
  92087. this.handleHardwareLimitations();
  92088. return Promise.resolve(this.engine);
  92089. };
  92090. AbstractViewer.prototype.initScene = function () {
  92091. if (this.scene) {
  92092. this.scene.dispose();
  92093. }
  92094. this.scene = new babylonjs_1.Scene(this.engine);
  92095. this.scene.createDefaultLight(true);
  92096. if (this.configuration.scene) {
  92097. this.configureScene(this.configuration.scene);
  92098. if (this.configuration.optimizer) {
  92099. this.configureOptimizer(this.configuration.optimizer);
  92100. }
  92101. }
  92102. return Promise.resolve(this.scene);
  92103. };
  92104. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92105. var _this = this;
  92106. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92107. if (clearScene === void 0) { clearScene = true; }
  92108. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92109. if (!modelUrl) {
  92110. return Promise.reject("no model configuration found");
  92111. }
  92112. if (this.isLoading) {
  92113. return Promise.reject("sanother model is curently being loaded.");
  92114. }
  92115. this.isLoading = true;
  92116. if ((typeof modelConfig === 'string')) {
  92117. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92118. this.configuration.model.url = modelConfig;
  92119. }
  92120. }
  92121. else {
  92122. if (this.configuration.model) {
  92123. deepmerge(this.configuration.model, modelConfig);
  92124. }
  92125. else {
  92126. this.configuration.model = modelConfig;
  92127. }
  92128. }
  92129. return Promise.resolve(this.scene).then(function (scene) {
  92130. if (!scene)
  92131. return _this.initScene();
  92132. if (clearScene) {
  92133. _this.models.forEach(function (m) { return m.dispose(); });
  92134. _this.models.length = 0;
  92135. }
  92136. return scene;
  92137. }).then(function () {
  92138. return new Promise(function (resolve, reject) {
  92139. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92140. _this.models.push(model);
  92141. _this.lastUsedLoader = model.loader;
  92142. model.onLoadedObservable.add(function (model) {
  92143. resolve(model);
  92144. });
  92145. model.onLoadErrorObservable.add(function (errorObject) {
  92146. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92147. reject(errorObject.exception);
  92148. });
  92149. });
  92150. model.onLoadProgressObservable.add(function (progressEvent) {
  92151. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92152. });
  92153. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92154. });
  92155. }).then(function (model) {
  92156. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92157. .then(function () {
  92158. _this.configureModel(_this.configuration.model || modelConfig, model);
  92159. _this.configureLights(_this.configuration.lights);
  92160. if (_this.configuration.camera) {
  92161. _this.configureCamera(_this.configuration.camera, model);
  92162. }
  92163. return _this.initEnvironment(model);
  92164. }).then(function () {
  92165. _this.isLoading = false;
  92166. return model;
  92167. });
  92168. });
  92169. };
  92170. AbstractViewer.prototype.initEnvironment = function (model) {
  92171. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92172. return Promise.resolve(this.scene);
  92173. };
  92174. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92175. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92176. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92177. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92178. this.maxShadows = 0;
  92179. }
  92180. else {
  92181. this.maxShadows = 3;
  92182. }
  92183. var caps = this.engine.getCaps();
  92184. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92185. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92186. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92187. if (linearHalfFloatTargets) {
  92188. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92189. this.shadowGeneratorBias = 0.002;
  92190. }
  92191. else if (linearFloatTargets) {
  92192. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92193. this.shadowGeneratorBias = 0.001;
  92194. }
  92195. else {
  92196. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92197. this.shadowGeneratorBias = 0.001;
  92198. }
  92199. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92200. };
  92201. AbstractViewer.prototype.injectCustomShaders = function () {
  92202. var customShaders = this.configuration.customShaders;
  92203. if (!customShaders) {
  92204. return;
  92205. }
  92206. if (customShaders.shaders) {
  92207. Object.keys(customShaders.shaders).forEach(function (key) {
  92208. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92209. });
  92210. }
  92211. if (customShaders.includes) {
  92212. Object.keys(customShaders.includes).forEach(function (key) {
  92213. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92214. });
  92215. }
  92216. };
  92217. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92218. var _this = this;
  92219. if (!config)
  92220. return;
  92221. Object.keys(config).forEach(function (key) {
  92222. if (key in object && typeof object[key] !== 'function') {
  92223. if (typeof object[key] === 'object') {
  92224. _this.extendClassWithConfig(object[key], config[key]);
  92225. }
  92226. else {
  92227. if (config[key] !== undefined) {
  92228. object[key] = config[key];
  92229. }
  92230. }
  92231. }
  92232. });
  92233. };
  92234. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92235. var behavior;
  92236. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92237. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92238. switch (type) {
  92239. case 0:
  92240. this.camera.useAutoRotationBehavior = true;
  92241. behavior = this.camera.autoRotationBehavior;
  92242. break;
  92243. case 1:
  92244. this.camera.useBouncingBehavior = true;
  92245. behavior = this.camera.bouncingBehavior;
  92246. break;
  92247. case 2:
  92248. this.camera.useFramingBehavior = true;
  92249. behavior = this.camera.framingBehavior;
  92250. break;
  92251. default:
  92252. behavior = null;
  92253. break;
  92254. }
  92255. if (behavior) {
  92256. if (typeof behaviorConfig === "object") {
  92257. this.extendClassWithConfig(behavior, behaviorConfig);
  92258. }
  92259. }
  92260. switch (type) {
  92261. case 0:
  92262. break;
  92263. case 1:
  92264. break;
  92265. case 2:
  92266. if (config.zoomOnBoundingInfo) {
  92267. var meshes = payload;
  92268. var bounding = meshes[0].getHierarchyBoundingVectors();
  92269. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92270. }
  92271. break;
  92272. }
  92273. };
  92274. return AbstractViewer;
  92275. }());
  92276. exports.AbstractViewer = AbstractViewer;
  92277. /***/ }),
  92278. /* 6 */
  92279. /***/ (function(module, exports) {
  92280. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92281. /***/ }),
  92282. /* 7 */
  92283. /***/ (function(module, exports) {
  92284. 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}}>";
  92285. /***/ }),
  92286. /* 8 */
  92287. /***/ (function(module, exports) {
  92288. 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=="
  92289. /***/ }),
  92290. /* 9 */
  92291. /***/ (function(module, exports) {
  92292. 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>";
  92293. /***/ }),
  92294. /* 10 */
  92295. /***/ (function(module, exports) {
  92296. 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>";
  92297. /***/ }),
  92298. /* 11 */
  92299. /***/ (function(module, exports) {
  92300. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92301. /***/ }),
  92302. /* 12 */
  92303. /***/ (function(module, exports) {
  92304. module.exports = "Error loading the model";
  92305. /***/ }),
  92306. /* 13 */
  92307. /***/ (function(module, exports, __webpack_require__) {
  92308. (function (global, factory) {
  92309. true ? module.exports = factory() :
  92310. typeof define === 'function' && define.amd ? define(factory) :
  92311. (global.deepmerge = factory());
  92312. }(this, (function () { 'use strict';
  92313. var isMergeableObject = function isMergeableObject(value) {
  92314. return isNonNullObject(value)
  92315. && !isSpecial(value)
  92316. };
  92317. function isNonNullObject(value) {
  92318. return !!value && typeof value === 'object'
  92319. }
  92320. function isSpecial(value) {
  92321. var stringValue = Object.prototype.toString.call(value);
  92322. return stringValue === '[object RegExp]'
  92323. || stringValue === '[object Date]'
  92324. || isReactElement(value)
  92325. }
  92326. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92327. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92328. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92329. function isReactElement(value) {
  92330. return value.$$typeof === REACT_ELEMENT_TYPE
  92331. }
  92332. function emptyTarget(val) {
  92333. return Array.isArray(val) ? [] : {}
  92334. }
  92335. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92336. var clone = !optionsArgument || optionsArgument.clone !== false;
  92337. return (clone && isMergeableObject(value))
  92338. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92339. : value
  92340. }
  92341. function defaultArrayMerge(target, source, optionsArgument) {
  92342. return target.concat(source).map(function(element) {
  92343. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92344. })
  92345. }
  92346. function mergeObject(target, source, optionsArgument) {
  92347. var destination = {};
  92348. if (isMergeableObject(target)) {
  92349. Object.keys(target).forEach(function(key) {
  92350. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92351. });
  92352. }
  92353. Object.keys(source).forEach(function(key) {
  92354. if (!isMergeableObject(source[key]) || !target[key]) {
  92355. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92356. } else {
  92357. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92358. }
  92359. });
  92360. return destination
  92361. }
  92362. function deepmerge(target, source, optionsArgument) {
  92363. var sourceIsArray = Array.isArray(source);
  92364. var targetIsArray = Array.isArray(target);
  92365. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92366. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92367. if (!sourceAndTargetTypesMatch) {
  92368. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92369. } else if (sourceIsArray) {
  92370. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92371. return arrayMerge(target, source, optionsArgument)
  92372. } else {
  92373. return mergeObject(target, source, optionsArgument)
  92374. }
  92375. }
  92376. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92377. if (!Array.isArray(array)) {
  92378. throw new Error('first argument should be an array')
  92379. }
  92380. return array.reduce(function(prev, next) {
  92381. return deepmerge(prev, next, optionsArgument)
  92382. }, {})
  92383. };
  92384. var deepmerge_1 = deepmerge;
  92385. return deepmerge_1;
  92386. })));
  92387. /***/ }),
  92388. /* 14 */
  92389. /***/ (function(module, exports, __webpack_require__) {
  92390. module.exports = __webpack_require__(15);
  92391. /***/ }),
  92392. /* 15 */
  92393. /***/ (function(module, exports, __webpack_require__) {
  92394. "use strict";
  92395. Object.defineProperty(exports, "__esModule", { value: true });
  92396. var mappers_1 = __webpack_require__(1);
  92397. exports.mapperManager = mappers_1.mapperManager;
  92398. var viewerManager_1 = __webpack_require__(3);
  92399. exports.viewerManager = viewerManager_1.viewerManager;
  92400. var defaultViewer_1 = __webpack_require__(4);
  92401. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92402. var viewer_1 = __webpack_require__(5);
  92403. exports.AbstractViewer = viewer_1.AbstractViewer;
  92404. var babylonjs_1 = __webpack_require__(0);
  92405. __webpack_require__(32);
  92406. __webpack_require__(33);
  92407. var initializer_1 = __webpack_require__(34);
  92408. exports.InitTags = initializer_1.InitTags;
  92409. babylonjs_1.PromisePolyfill.Apply();
  92410. exports.disableInit = false;
  92411. document.addEventListener("DOMContentLoaded", function (event) {
  92412. if (exports.disableInit)
  92413. return;
  92414. initializer_1.InitTags();
  92415. });
  92416. /***/ }),
  92417. /* 16 */
  92418. /***/ (function(module, exports) {
  92419. var g;
  92420. // This works in non-strict mode
  92421. g = (function() {
  92422. return this;
  92423. })();
  92424. try {
  92425. // This works if eval is allowed (see CSP)
  92426. g = g || Function("return this")() || (1,eval)("this");
  92427. } catch(e) {
  92428. // This works if the window reference is available
  92429. if(typeof window === "object")
  92430. g = window;
  92431. }
  92432. // g can still be undefined, but nothing to do about it...
  92433. // We return undefined, instead of nothing here, so it's
  92434. // easier to handle this case. if(!global) { ...}
  92435. module.exports = g;
  92436. /***/ }),
  92437. /* 17 */
  92438. /***/ (function(module, exports) {
  92439. module.exports = cannon;
  92440. /***/ }),
  92441. /* 18 */
  92442. /***/ (function(module, exports, __webpack_require__) {
  92443. /**
  92444. * from OimoPhysics DEV 1.1.0a AS3
  92445. * @author Saharan / http://el-ement.com/
  92446. *
  92447. * to Oimo.js 2015 JAVASCRIPT
  92448. * @author LoTh / http://lo-th.github.io/labs/
  92449. */
  92450. var OIMO = {
  92451. REVISION: "1.2",
  92452. // Global identification of next shape.
  92453. // This will be incremented every time a shape is created.
  92454. nextID: 0,
  92455. proxyID: 0,
  92456. // BroadPhase
  92457. BR_NULL: 0,
  92458. BR_BRUTE_FORCE: 1,
  92459. BR_SWEEP_AND_PRUNE: 2,
  92460. BR_BOUNDING_VOLUME_TREE: 3,
  92461. // body type
  92462. BODY_NULL: 0,
  92463. BODY_DYNAMIC: 1,
  92464. BODY_STATIC: 2,
  92465. // shape type
  92466. SHAPE_NULL: 0,
  92467. SHAPE_SPHERE: 1,
  92468. SHAPE_BOX: 2,
  92469. SHAPE_CYLINDER: 3,
  92470. SHAPE_TETRA: 4,
  92471. // joint type
  92472. JOINT_NULL: 0,
  92473. JOINT_DISTANCE: 1,
  92474. JOINT_BALL_AND_SOCKET: 2,
  92475. JOINT_HINGE: 3,
  92476. JOINT_WHEEL: 4,
  92477. JOINT_SLIDER: 5,
  92478. JOINT_PRISMATIC: 6,
  92479. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92480. // scale all by 100 so object is between 10 to 10000 three unit.
  92481. WORLD_SCALE: 100,
  92482. INV_SCALE: 0.01,
  92483. // AABB aproximation
  92484. AABB_PROX: 0.005,
  92485. // Math function
  92486. sqrt: Math.sqrt,
  92487. abs: Math.abs,
  92488. floor: Math.floor,
  92489. cos: Math.cos,
  92490. sin: Math.sin,
  92491. acos: Math.acos,
  92492. asin: Math.asin,
  92493. atan2: Math.atan2,
  92494. round: Math.round,
  92495. pow: Math.pow,
  92496. max: Math.max,
  92497. min: Math.min,
  92498. random: Math.random,
  92499. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92500. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92501. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92502. int: function (x) { return ~~x; },
  92503. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92504. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92505. degtorad: 0.0174532925199432957,
  92506. radtodeg: 57.295779513082320876,
  92507. PI: 3.141592653589793,
  92508. TwoPI: 6.283185307179586,
  92509. PI90: 1.570796326794896,
  92510. PI270: 4.712388980384689,
  92511. CustomError: null,
  92512. Error: function (Class, Msg) {
  92513. if (OIMO.CustomError == null) console.error(Class, Msg);
  92514. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92515. }
  92516. };
  92517. var OIMO_ARRAY_TYPE;
  92518. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92519. try {
  92520. (function (w) {
  92521. var perfNow;
  92522. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92523. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92524. var n = perfNowNames[i];
  92525. if (!!w['performance'][n]) {
  92526. perfNow = function () { return w['performance'][n]() };
  92527. break;
  92528. }
  92529. }
  92530. if (!perfNow) perfNow = Date.now;
  92531. //w.perfNow = perfNow;
  92532. OIMO.now = perfNow;
  92533. })(window);
  92534. } catch (e) { OIMO.now = function () { return 0; }; }
  92535. /**
  92536. * The class of physical computing world.
  92537. * You must be added to the world physical all computing objects
  92538. * @author saharan
  92539. * @author lo-th
  92540. */
  92541. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92542. // The time between each step
  92543. this.timeStep = TimeStep || 0.01666; // 1/60;
  92544. // The number of iterations for constraint solvers.
  92545. this.numIterations = Iterations || 8;
  92546. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92547. switch (BroadPhaseType || 2) {
  92548. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92549. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92550. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92551. }
  92552. // This is the detailed information of the performance.
  92553. this.performance = null;
  92554. this.isNoStat = NoStat || false;
  92555. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92556. // Whether the constraints randomizer is enabled or not.
  92557. this.enableRandomizer = true;
  92558. // The rigid body list
  92559. this.rigidBodies = null;
  92560. // number of rigid body
  92561. this.numRigidBodies = 0;
  92562. // The contact list
  92563. this.contacts = null;
  92564. this.unusedContacts = null;
  92565. // The number of contact
  92566. this.numContacts = 0;
  92567. // The number of contact points
  92568. this.numContactPoints = 0;
  92569. // The joint list
  92570. this.joints = null;
  92571. // The number of joints.
  92572. this.numJoints = 0;
  92573. // The number of simulation islands.
  92574. this.numIslands = 0;
  92575. // The gravity in the world.
  92576. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92577. var numShapeTypes = 5;//4;//3;
  92578. this.detectors = [];
  92579. this.detectors.length = numShapeTypes;
  92580. var i = numShapeTypes;
  92581. while (i--) {
  92582. this.detectors[i] = [];
  92583. this.detectors[i].length = numShapeTypes;
  92584. }
  92585. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92586. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92587. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92588. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92589. // CYLINDER add
  92590. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92591. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92592. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92593. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92594. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92595. // TETRA add
  92596. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92597. this.randX = 65535;
  92598. this.randA = 98765;
  92599. this.randB = 123456789;
  92600. //this.maxIslandRigidBodies = 64;
  92601. this.islandRigidBodies = [];
  92602. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92603. this.islandStack = [];
  92604. //this.islandStack.length = this.maxIslandRigidBodies;
  92605. //this.maxIslandConstraints = 128;
  92606. this.islandConstraints = [];
  92607. //this.islandConstraints.length = this.maxIslandConstraints;
  92608. };
  92609. OIMO.World.prototype = {
  92610. constructor: OIMO.World,
  92611. /**
  92612. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92613. */
  92614. clear: function () {
  92615. this.randX = 65535;
  92616. while (this.joints !== null) {
  92617. this.removeJoint(this.joints);
  92618. }
  92619. while (this.contacts !== null) {
  92620. this.removeContact(this.contacts);
  92621. }
  92622. while (this.rigidBodies !== null) {
  92623. this.removeRigidBody(this.rigidBodies);
  92624. }
  92625. OIMO.nextID = 0;
  92626. OIMO.proxyID = 0;
  92627. },
  92628. /**
  92629. * I'll add a rigid body to the world.
  92630. * Rigid body that has been added will be the operands of each step.
  92631. * @param rigidBody Rigid body that you want to add
  92632. */
  92633. addRigidBody: function (rigidBody) {
  92634. if (rigidBody.parent) {
  92635. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92636. }
  92637. rigidBody.parent = this;
  92638. rigidBody.awake();
  92639. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92640. this.addShape(shape);
  92641. }
  92642. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92643. this.rigidBodies = rigidBody;
  92644. this.numRigidBodies++;
  92645. },
  92646. /**
  92647. * I will remove the rigid body from the world.
  92648. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92649. * @param rigidBody Rigid body to be removed
  92650. */
  92651. removeRigidBody: function (rigidBody) {
  92652. var remove = rigidBody;
  92653. if (remove.parent !== this) return;
  92654. remove.awake();
  92655. var js = remove.jointLink;
  92656. while (js != null) {
  92657. var joint = js.joint;
  92658. js = js.next;
  92659. this.removeJoint(joint);
  92660. }
  92661. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92662. this.removeShape(shape);
  92663. }
  92664. var prev = remove.prev;
  92665. var next = remove.next;
  92666. if (prev !== null) prev.next = next;
  92667. if (next !== null) next.prev = prev;
  92668. if (this.rigidBodies == remove) this.rigidBodies = next;
  92669. remove.prev = null;
  92670. remove.next = null;
  92671. remove.parent = null;
  92672. this.numRigidBodies--;
  92673. },
  92674. getByName: function (name) {
  92675. var result = null;
  92676. var body = this.rigidBodies;
  92677. while (body !== null) {
  92678. if (body.name !== " " && body.name === name) result = body;
  92679. body = body.next;
  92680. }
  92681. var joint = this.joints;
  92682. while (joint !== null) {
  92683. if (joint.name !== "" && joint.name === name) result = joint;
  92684. joint = joint.next;
  92685. }
  92686. return result;
  92687. },
  92688. /**
  92689. * I'll add a shape to the world..
  92690. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92691. * Shape will be added to the world automatically, please do not call from outside this method.
  92692. * @param shape Shape you want to add
  92693. */
  92694. addShape: function (shape) {
  92695. if (!shape.parent || !shape.parent.parent) {
  92696. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92697. }
  92698. shape.proxy = this.broadPhase.createProxy(shape);
  92699. shape.updateProxy();
  92700. this.broadPhase.addProxy(shape.proxy);
  92701. },
  92702. /**
  92703. * I will remove the shape from the world.
  92704. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92705. * Shape will be added to the world automatically, please do not call from outside this method.
  92706. * @param shape Shape you want to delete
  92707. */
  92708. removeShape: function (shape) {
  92709. this.broadPhase.removeProxy(shape.proxy);
  92710. shape.proxy = null;
  92711. },
  92712. /**
  92713. * I'll add a joint to the world.
  92714. * Joint that has been added will be the operands of each step.
  92715. * @param shape Joint to be added
  92716. */
  92717. addJoint: function (joint) {
  92718. if (joint.parent) {
  92719. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92720. }
  92721. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  92722. this.joints = joint;
  92723. joint.parent = this;
  92724. this.numJoints++;
  92725. joint.awake();
  92726. joint.attach();
  92727. },
  92728. /**
  92729. * I will remove the joint from the world.
  92730. * Joint that has been added will be the operands of each step.
  92731. * @param shape Joint to be deleted
  92732. */
  92733. removeJoint: function (joint) {
  92734. var remove = joint;
  92735. var prev = remove.prev;
  92736. var next = remove.next;
  92737. if (prev !== null) prev.next = next;
  92738. if (next !== null) next.prev = prev;
  92739. if (this.joints == remove) this.joints = next;
  92740. remove.prev = null;
  92741. remove.next = null;
  92742. this.numJoints--;
  92743. remove.awake();
  92744. remove.detach();
  92745. remove.parent = null;
  92746. },
  92747. worldscale: function (scale) {
  92748. OIMO.WORLD_SCALE = scale || 100;
  92749. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  92750. },
  92751. addContact: function (s1, s2) {
  92752. var newContact;
  92753. if (this.unusedContacts !== null) {
  92754. newContact = this.unusedContacts;
  92755. this.unusedContacts = this.unusedContacts.next;
  92756. } else {
  92757. newContact = new OIMO.Contact();
  92758. }
  92759. newContact.attach(s1, s2);
  92760. newContact.detector = this.detectors[s1.type][s2.type];
  92761. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  92762. this.contacts = newContact;
  92763. this.numContacts++;
  92764. },
  92765. removeContact: function (contact) {
  92766. var prev = contact.prev;
  92767. var next = contact.next;
  92768. if (next) next.prev = prev;
  92769. if (prev) prev.next = next;
  92770. if (this.contacts == contact) this.contacts = next;
  92771. contact.prev = null;
  92772. contact.next = null;
  92773. contact.detach();
  92774. contact.next = this.unusedContacts;
  92775. this.unusedContacts = contact;
  92776. this.numContacts--;
  92777. },
  92778. checkContact: function (name1, name2) {
  92779. var n1, n2;
  92780. var contact = this.contacts;
  92781. while (contact !== null) {
  92782. n1 = contact.body1.name || ' ';
  92783. n2 = contact.body2.name || ' ';
  92784. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  92785. else contact = contact.next;
  92786. }
  92787. return false;
  92788. },
  92789. callSleep: function (body) {
  92790. if (!body.allowSleep) return false;
  92791. if (body.linearVelocity.lengthSq() > 0.04) return false;
  92792. if (body.angularVelocity.lengthSq() > 0.25) return false;
  92793. return true;
  92794. },
  92795. /**
  92796. * I will proceed only time step seconds time of World.
  92797. */
  92798. step: function () {
  92799. var time0, time1, time2, time3;
  92800. var stat = !this.isNoStat ? true : false;
  92801. if (stat) time0 = OIMO.now();
  92802. var body = this.rigidBodies;
  92803. while (body !== null) {
  92804. body.addedToIsland = false;
  92805. if (body.sleeping) {
  92806. if (
  92807. body.linearVelocity.testZero() ||
  92808. body.angularVelocity.testZero() ||
  92809. body.position.testDiff(body.sleepPosition) ||
  92810. body.orientation.testDiff(body.sleepOrientation)
  92811. ) body.awake(); // awake the body
  92812. }
  92813. body = body.next;
  92814. }
  92815. //------------------------------------------------------
  92816. // UPDATE CONTACT
  92817. //------------------------------------------------------
  92818. // broad phase
  92819. if (stat) time1 = OIMO.now();
  92820. this.broadPhase.detectPairs();
  92821. var pairs = this.broadPhase.pairs;
  92822. var i = this.broadPhase.numPairs;
  92823. //do{
  92824. while (i--) {
  92825. //for(var i=0, l=numPairs; i<l; i++){
  92826. var pair = pairs[i];
  92827. var s1;
  92828. var s2;
  92829. if (pair.shape1.id < pair.shape2.id) {
  92830. s1 = pair.shape1;
  92831. s2 = pair.shape2;
  92832. } else {
  92833. s1 = pair.shape2;
  92834. s2 = pair.shape1;
  92835. }
  92836. var link;
  92837. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  92838. else link = s2.contactLink;
  92839. var exists = false;
  92840. while (link) {
  92841. var contact = link.contact;
  92842. if (contact.shape1 == s1 && contact.shape2 == s2) {
  92843. contact.persisting = true;
  92844. exists = true;// contact already exists
  92845. break;
  92846. }
  92847. link = link.next;
  92848. }
  92849. if (!exists) {
  92850. this.addContact(s1, s2);
  92851. }
  92852. }// while(i-- >0);
  92853. if (stat) {
  92854. time2 = OIMO.now();
  92855. this.performance.broadPhaseTime = time2 - time1;
  92856. }
  92857. // update & narrow phase
  92858. this.numContactPoints = 0;
  92859. contact = this.contacts;
  92860. while (contact !== null) {
  92861. if (!contact.persisting) {
  92862. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  92863. /*var aabb1=contact.shape1.aabb;
  92864. var aabb2=contact.shape2.aabb;
  92865. if(
  92866. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  92867. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  92868. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  92869. ){*/
  92870. var next = contact.next;
  92871. this.removeContact(contact);
  92872. contact = next;
  92873. continue;
  92874. }
  92875. }
  92876. var b1 = contact.body1;
  92877. var b2 = contact.body2;
  92878. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  92879. contact.updateManifold();
  92880. }
  92881. this.numContactPoints += contact.manifold.numPoints;
  92882. contact.persisting = false;
  92883. contact.constraint.addedToIsland = false;
  92884. contact = contact.next;
  92885. }
  92886. if (stat) {
  92887. time3 = OIMO.now();
  92888. this.performance.narrowPhaseTime = time3 - time2;
  92889. }
  92890. //------------------------------------------------------
  92891. // SOLVE ISLANDS
  92892. //------------------------------------------------------
  92893. var invTimeStep = 1 / this.timeStep;
  92894. //var body;
  92895. var joint;
  92896. var constraint;
  92897. //var num;
  92898. for (joint = this.joints; joint !== null; joint = joint.next) {
  92899. joint.addedToIsland = false;
  92900. }
  92901. // clear old island array
  92902. this.islandRigidBodies = [];
  92903. this.islandConstraints = [];
  92904. this.islandStack = [];
  92905. // expand island buffers
  92906. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  92907. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  92908. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  92909. this.islandRigidBodies=[];
  92910. this.islandStack=[];
  92911. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92912. this.islandStack.length = this.maxIslandRigidBodies;
  92913. }
  92914. var numConstraints=this.numJoints+this.numContacts;
  92915. if(this.maxIslandConstraints<numConstraints){
  92916. this.maxIslandConstraints=numConstraints<<1;
  92917. //this.maxIslandConstraints=numConstraints*2;
  92918. this.islandConstraints=[];
  92919. this.islandConstraints.length = this.maxIslandConstraints;
  92920. }*/
  92921. time1 = OIMO.now();
  92922. this.numIslands = 0;
  92923. // build and solve simulation islands
  92924. for (var base = this.rigidBodies; base !== null; base = base.next) {
  92925. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  92926. if (base.isLonely()) {// update single body
  92927. if (base.isDynamic) {
  92928. base.linearVelocity.addTime(this.gravity, this.timeStep);
  92929. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  92930. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  92931. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  92932. }
  92933. if (this.callSleep(base)) {
  92934. base.sleepTime += this.timeStep;
  92935. if (base.sleepTime > 0.5) base.sleep();
  92936. else base.updatePosition(this.timeStep);
  92937. } else {
  92938. base.sleepTime = 0;
  92939. base.updatePosition(this.timeStep);
  92940. }
  92941. this.numIslands++;
  92942. continue;
  92943. }
  92944. var islandNumRigidBodies = 0;
  92945. var islandNumConstraints = 0;
  92946. var stackCount = 1;
  92947. // add rigid body to stack
  92948. this.islandStack[0] = base;
  92949. base.addedToIsland = true;
  92950. // build an island
  92951. do {
  92952. // get rigid body from stack
  92953. body = this.islandStack[--stackCount];
  92954. this.islandStack[stackCount] = null;
  92955. body.sleeping = false;
  92956. // add rigid body to the island
  92957. this.islandRigidBodies[islandNumRigidBodies++] = body;
  92958. if (body.isStatic) continue;
  92959. // search connections
  92960. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  92961. var contact = cs.contact;
  92962. constraint = contact.constraint;
  92963. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  92964. // add constraint to the island
  92965. this.islandConstraints[islandNumConstraints++] = constraint;
  92966. constraint.addedToIsland = true;
  92967. var next = cs.body;
  92968. if (next.addedToIsland) continue;
  92969. // add rigid body to stack
  92970. this.islandStack[stackCount++] = next;
  92971. next.addedToIsland = true;
  92972. }
  92973. for (var js = body.jointLink; js !== null; js = js.next) {
  92974. constraint = js.joint;
  92975. if (constraint.addedToIsland) continue;// ignore
  92976. // add constraint to the island
  92977. this.islandConstraints[islandNumConstraints++] = constraint;
  92978. constraint.addedToIsland = true;
  92979. next = js.body;
  92980. if (next.addedToIsland || !next.isDynamic) continue;
  92981. // add rigid body to stack
  92982. this.islandStack[stackCount++] = next;
  92983. next.addedToIsland = true;
  92984. }
  92985. } while (stackCount != 0);
  92986. // update velocities
  92987. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  92988. /*var gx=this.gravity.x*this.timeStep;
  92989. var gy=this.gravity.y*this.timeStep;
  92990. var gz=this.gravity.z*this.timeStep;*/
  92991. var j = islandNumRigidBodies;
  92992. while (j--) {
  92993. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  92994. body = this.islandRigidBodies[j];
  92995. if (body.isDynamic) {
  92996. body.linearVelocity.addEqual(gVel);
  92997. /*body.linearVelocity.x+=gx;
  92998. body.linearVelocity.y+=gy;
  92999. body.linearVelocity.z+=gz;*/
  93000. }
  93001. }
  93002. // randomizing order
  93003. if (this.enableRandomizer) {
  93004. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93005. j = islandNumConstraints;
  93006. while (j--) {
  93007. if (j !== 0) {
  93008. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93009. constraint = this.islandConstraints[j];
  93010. this.islandConstraints[j] = this.islandConstraints[swap];
  93011. this.islandConstraints[swap] = constraint;
  93012. }
  93013. }
  93014. }
  93015. // solve contraints
  93016. j = islandNumConstraints;
  93017. while (j--) {
  93018. //for(j=0, l=islandNumConstraints; j<l; j++){
  93019. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93020. }
  93021. var k = this.numIterations;
  93022. while (k--) {
  93023. //for(var k=0, l=this.numIterations; k<l; k++){
  93024. j = islandNumConstraints;
  93025. while (j--) {
  93026. //for(j=0, m=islandNumConstraints; j<m; j++){
  93027. this.islandConstraints[j].solve();// main-solve
  93028. }
  93029. }
  93030. j = islandNumConstraints;
  93031. while (j--) {
  93032. //for(j=0, l=islandNumConstraints; j<l; j++){
  93033. this.islandConstraints[j].postSolve();// post-solve
  93034. this.islandConstraints[j] = null;// gc
  93035. }
  93036. // sleeping check
  93037. var sleepTime = 10;
  93038. j = islandNumRigidBodies;
  93039. while (j--) {
  93040. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93041. body = this.islandRigidBodies[j];
  93042. if (this.callSleep(body)) {
  93043. body.sleepTime += this.timeStep;
  93044. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93045. } else {
  93046. body.sleepTime = 0;
  93047. sleepTime = 0;
  93048. continue;
  93049. }
  93050. }
  93051. if (sleepTime > 0.5) {
  93052. // sleep the island
  93053. j = islandNumRigidBodies;
  93054. while (j--) {
  93055. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93056. this.islandRigidBodies[j].sleep();
  93057. this.islandRigidBodies[j] = null;// gc
  93058. }
  93059. } else {
  93060. // update positions
  93061. j = islandNumRigidBodies;
  93062. while (j--) {
  93063. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93064. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93065. this.islandRigidBodies[j] = null;// gc
  93066. }
  93067. }
  93068. this.numIslands++;
  93069. }
  93070. if (stat) {
  93071. time2 = OIMO.now();
  93072. this.performance.solvingTime = time2 - time1;
  93073. //------------------------------------------------------
  93074. // END SIMULATION
  93075. //------------------------------------------------------
  93076. time2 = OIMO.now();
  93077. // fps update
  93078. this.performance.upfps();
  93079. this.performance.totalTime = time2 - time0;
  93080. }
  93081. }
  93082. }
  93083. /**
  93084. * The class of rigid body.
  93085. * Rigid body has the shape of a single or multiple collision processing,
  93086. * I can set the parameters individually.
  93087. * @author saharan
  93088. */
  93089. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93090. this.name = " ";
  93091. // The maximum number of shapes that can be added to a one rigid.
  93092. this.MAX_SHAPES = 64;//64;
  93093. this.prev = null;
  93094. this.next = null;
  93095. // I represent the kind of rigid body.
  93096. // Please do not change from the outside this variable.
  93097. // If you want to change the type of rigid body, always
  93098. // Please specify the type you want to set the arguments of setupMass method.
  93099. this.type = OIMO.BODY_NULL;
  93100. this.massInfo = new OIMO.MassInfo();
  93101. // It is the world coordinate of the center of gravity.
  93102. this.position = new OIMO.Vec3(x, y, z);
  93103. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93104. this.newPosition = new OIMO.Vec3();
  93105. this.controlPos = false;
  93106. this.newOrientation = new OIMO.Quat();
  93107. this.newRotation = new OIMO.Vec3();
  93108. this.currentRotation = new OIMO.Vec3();
  93109. this.controlRot = false;
  93110. this.controlRotInTime = false;
  93111. // Is the translational velocity.
  93112. this.linearVelocity = new OIMO.Vec3();
  93113. // Is the angular velocity.
  93114. this.angularVelocity = new OIMO.Vec3();
  93115. // return matrix for three.js
  93116. this.matrix = new OIMO.Mat44();
  93117. //--------------------------------------------
  93118. // Please do not change from the outside this variables.
  93119. //--------------------------------------------
  93120. // It is a world that rigid body has been added.
  93121. this.parent = null;
  93122. this.contactLink = null;
  93123. this.numContacts = 0;
  93124. // An array of shapes that are included in the rigid body.
  93125. this.shapes = null;
  93126. // The number of shapes that are included in the rigid body.
  93127. this.numShapes = 0;
  93128. // It is the link array of joint that is connected to the rigid body.
  93129. this.jointLink = null;
  93130. // The number of joints that are connected to the rigid body.
  93131. this.numJoints = 0;
  93132. // It is the world coordinate of the center of gravity in the sleep just before.
  93133. this.sleepPosition = new OIMO.Vec3();
  93134. // It is a quaternion that represents the attitude of sleep just before.
  93135. this.sleepOrientation = new OIMO.Quat();
  93136. // I will show this rigid body to determine whether it is a rigid body static.
  93137. this.isStatic = false;
  93138. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93139. this.isDynamic = false;
  93140. // It is a rotation matrix representing the orientation.
  93141. this.rotation = new OIMO.Mat33();
  93142. //--------------------------------------------
  93143. // It will be recalculated automatically from the shape, which is included.
  93144. //--------------------------------------------
  93145. // This is the weight.
  93146. this.mass = NaN;
  93147. // It is the reciprocal of the mass.
  93148. this.inverseMass = NaN;
  93149. // It is the inverse of the inertia tensor in the world system.
  93150. this.inverseInertia = new OIMO.Mat33();
  93151. // It is the inertia tensor in the initial state.
  93152. this.localInertia = new OIMO.Mat33();
  93153. // It is the inverse of the inertia tensor in the initial state.
  93154. this.inverseLocalInertia = new OIMO.Mat33();
  93155. // I indicates rigid body whether it has been added to the simulation Island.
  93156. this.addedToIsland = false;
  93157. // It shows how to sleep rigid body.
  93158. this.allowSleep = true;
  93159. // This is the time from when the rigid body at rest.
  93160. this.sleepTime = 0;
  93161. // I shows rigid body to determine whether it is a sleep state.
  93162. this.sleeping = false;
  93163. };
  93164. OIMO.RigidBody.prototype = {
  93165. constructor: OIMO.RigidBody,
  93166. /**
  93167. * I'll add a shape to rigid body.
  93168. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93169. * @param shape shape to Add
  93170. */
  93171. addShape: function (shape) {
  93172. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93173. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93174. this.shapes = shape;
  93175. shape.parent = this;
  93176. if (this.parent) this.parent.addShape(shape);
  93177. this.numShapes++;
  93178. },
  93179. /**
  93180. * I will delete the shape from the rigid body.
  93181. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93182. * @param shape shape to Delete
  93183. */
  93184. removeShape: function (shape) {
  93185. var remove = shape;
  93186. if (remove.parent != this) return;
  93187. var prev = remove.prev;
  93188. var next = remove.next;
  93189. if (prev != null) prev.next = next;
  93190. if (next != null) next.prev = prev;
  93191. if (this.shapes == remove) this.shapes = next;
  93192. remove.prev = null;
  93193. remove.next = null;
  93194. remove.parent = null;
  93195. if (this.parent) this.parent.removeShape(remove);
  93196. this.numShapes--;
  93197. },
  93198. remove: function () {
  93199. this.dispose();
  93200. },
  93201. dispose: function () {
  93202. this.parent.removeRigidBody(this);
  93203. },
  93204. checkContact: function (name) {
  93205. this.parent.checkContact(this.name, name);
  93206. },
  93207. /**
  93208. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93209. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93210. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93211. * the rigid body's position will be adjusted to the center of gravity.
  93212. * @param type
  93213. * @param adjustPosition
  93214. */
  93215. setupMass: function (type, AdjustPosition) {
  93216. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93217. this.type = type || OIMO.BODY_DYNAMIC;
  93218. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93219. this.isStatic = this.type == OIMO.BODY_STATIC;
  93220. this.mass = 0;
  93221. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93222. var te = this.localInertia.elements;
  93223. //
  93224. var tmpM = new OIMO.Mat33();
  93225. var tmpV = new OIMO.Vec3();
  93226. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93227. shape.calculateMassInfo(this.massInfo);
  93228. var shapeMass = this.massInfo.mass;
  93229. var relX = shape.relativePosition.x;
  93230. var relY = shape.relativePosition.y;
  93231. var relZ = shape.relativePosition.z;
  93232. /*tmpV.x+=relX*shapeMass;
  93233. tmpV.y+=relY*shapeMass;
  93234. tmpV.z+=relZ*shapeMass;*/
  93235. tmpV.addScale(shape.relativePosition, shapeMass);
  93236. this.mass += shapeMass;
  93237. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93238. this.localInertia.addEqual(tmpM);
  93239. // add offset inertia
  93240. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93241. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93242. te[8] += shapeMass * (relX * relX + relY * relY);
  93243. var xy = shapeMass * relX * relY;
  93244. var yz = shapeMass * relY * relZ;
  93245. var zx = shapeMass * relZ * relX;
  93246. te[1] -= xy;
  93247. te[3] -= xy;
  93248. te[2] -= yz;
  93249. te[6] -= yz;
  93250. te[5] -= zx;
  93251. te[7] -= zx;
  93252. }
  93253. this.inverseMass = 1 / this.mass;
  93254. tmpV.scaleEqual(this.inverseMass);
  93255. if (adjustPosition) {
  93256. this.position.addEqual(tmpV);
  93257. for (shape = this.shapes; shape != null; shape = shape.next) {
  93258. shape.relativePosition.subEqual(tmpV);
  93259. }
  93260. // subtract offset inertia
  93261. relX = tmpV.x;
  93262. relY = tmpV.y;
  93263. relZ = tmpV.z;
  93264. //var te = this.localInertia.elements;
  93265. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93266. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93267. te[8] -= this.mass * (relX * relX + relY * relY);
  93268. xy = this.mass * relX * relY;
  93269. yz = this.mass * relY * relZ;
  93270. zx = this.mass * relZ * relX;
  93271. te[1] += xy;
  93272. te[3] += xy;
  93273. te[2] += yz;
  93274. te[6] += yz;
  93275. te[5] += zx;
  93276. te[7] += zx;
  93277. }
  93278. this.inverseLocalInertia.invert(this.localInertia);
  93279. if (this.type == OIMO.BODY_STATIC) {
  93280. this.inverseMass = 0;
  93281. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93282. }
  93283. this.syncShapes();
  93284. this.awake();
  93285. },
  93286. /**
  93287. * Awake the rigid body.
  93288. */
  93289. awake: function () {
  93290. if (!this.allowSleep || !this.sleeping) return;
  93291. this.sleeping = false;
  93292. this.sleepTime = 0;
  93293. // awake connected constraints
  93294. var cs = this.contactLink;
  93295. while (cs != null) {
  93296. cs.body.sleepTime = 0;
  93297. cs.body.sleeping = false;
  93298. cs = cs.next;
  93299. }
  93300. var js = this.jointLink;
  93301. while (js != null) {
  93302. js.body.sleepTime = 0;
  93303. js.body.sleeping = false;
  93304. js = js.next;
  93305. }
  93306. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93307. shape.updateProxy();
  93308. }
  93309. },
  93310. /**
  93311. * Sleep the rigid body.
  93312. */
  93313. sleep: function () {
  93314. if (!this.allowSleep || this.sleeping) return;
  93315. this.linearVelocity.set(0, 0, 0);
  93316. this.angularVelocity.set(0, 0, 0);
  93317. this.sleepPosition.copy(this.position);
  93318. this.sleepOrientation.copy(this.orientation);
  93319. /*this.linearVelocity.x=0;
  93320. this.linearVelocity.y=0;
  93321. this.linearVelocity.z=0;
  93322. this.angularVelocity.x=0;
  93323. this.angularVelocity.y=0;
  93324. this.angularVelocity.z=0;
  93325. this.sleepPosition.x=this.position.x;
  93326. this.sleepPosition.y=this.position.y;
  93327. this.sleepPosition.z=this.position.z;*/
  93328. /*this.sleepOrientation.s=this.orientation.s;
  93329. this.sleepOrientation.x=this.orientation.x;
  93330. this.sleepOrientation.y=this.orientation.y;
  93331. this.sleepOrientation.z=this.orientation.z;*/
  93332. this.sleepTime = 0;
  93333. this.sleeping = true;
  93334. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93335. shape.updateProxy();
  93336. }
  93337. },
  93338. /**
  93339. * Get whether the rigid body has not any connection with others.
  93340. * @return
  93341. */
  93342. isLonely: function () {
  93343. return this.numJoints == 0 && this.numContacts == 0;
  93344. },
  93345. /**
  93346. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93347. * This method is invoked automatically when calling the step of the World,
  93348. * There is no need to call from outside usually.
  93349. * @param timeStep time
  93350. */
  93351. updatePosition: function (timeStep) {
  93352. switch (this.type) {
  93353. case OIMO.BODY_STATIC:
  93354. this.linearVelocity.set(0, 0, 0);
  93355. this.angularVelocity.set(0, 0, 0);
  93356. // ONLY FOR TEST
  93357. if (this.controlPos) {
  93358. this.position.copy(this.newPosition);
  93359. this.controlPos = false;
  93360. }
  93361. if (this.controlRot) {
  93362. this.orientation.copy(this.newOrientation);
  93363. this.controlRot = false;
  93364. }
  93365. /*this.linearVelocity.x=0;
  93366. this.linearVelocity.y=0;
  93367. this.linearVelocity.z=0;
  93368. this.angularVelocity.x=0;
  93369. this.angularVelocity.y=0;
  93370. this.angularVelocity.z=0;*/
  93371. break;
  93372. case OIMO.BODY_DYNAMIC:
  93373. if (this.controlPos) {
  93374. this.angularVelocity.set(0, 0, 0);
  93375. this.linearVelocity.set(0, 0, 0);
  93376. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93377. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93378. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93379. this.controlPos = false;
  93380. }
  93381. if (this.controlRot) {
  93382. this.angularVelocity.set(0, 0, 0);
  93383. this.orientation.copy(this.newOrientation);
  93384. //var t=timeStep//*0.5;
  93385. //var q = new OIMO.Quat();
  93386. //q.sub(this.newOrientation, this.orientation);
  93387. //q.normalize(q);
  93388. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93389. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93390. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93391. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93392. //this.angularVelocity.applyQuaternion(q);
  93393. //this.angularVelocity.x = this.angularVelocity.x/t;
  93394. //this.angularVelocity.y = this.angularVelocity.y/t;
  93395. //this.angularVelocity.z = this.angularVelocity.z/t;
  93396. this.controlRot = false;
  93397. }
  93398. this.position.addTime(this.linearVelocity, timeStep);
  93399. this.orientation.addTime(this.angularVelocity, timeStep);
  93400. break;
  93401. default: OIMO.Error("RigidBody", "Invalid type.");
  93402. }
  93403. this.syncShapes();
  93404. },
  93405. rotateInertia: function (rot, inertia, out) {
  93406. var tm1 = rot.elements;
  93407. var tm2 = inertia.elements;
  93408. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93409. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93410. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93411. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93412. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93413. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93414. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93415. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93416. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93417. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93418. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93419. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93420. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93421. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93422. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93423. var oe = out.elements;
  93424. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93425. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93426. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93427. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93428. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93429. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93430. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93431. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93432. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93433. },
  93434. syncShapes: function () {
  93435. var s = this.orientation.s;
  93436. var x = this.orientation.x;
  93437. var y = this.orientation.y;
  93438. var z = this.orientation.z;
  93439. var x2 = 2 * x;
  93440. var y2 = 2 * y;
  93441. var z2 = 2 * z;
  93442. var xx = x * x2;
  93443. var yy = y * y2;
  93444. var zz = z * z2;
  93445. var xy = x * y2;
  93446. var yz = y * z2;
  93447. var xz = x * z2;
  93448. var sx = s * x2;
  93449. var sy = s * y2;
  93450. var sz = s * z2;
  93451. var tr = this.rotation.elements;
  93452. tr[0] = 1 - yy - zz;
  93453. tr[1] = xy - sz;
  93454. tr[2] = xz + sy;
  93455. tr[3] = xy + sz;
  93456. tr[4] = 1 - xx - zz;
  93457. tr[5] = yz - sx;
  93458. tr[6] = xz - sy;
  93459. tr[7] = yz + sx;
  93460. tr[8] = 1 - xx - yy;
  93461. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93462. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93463. //var relPos=shape.relativePosition;
  93464. //var relRot=shape.relativeRotation;
  93465. //var rot=shape.rotation;
  93466. /*var lx=relPos.x;
  93467. var ly=relPos.y;
  93468. var lz=relPos.z;
  93469. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93470. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93471. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93472. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93473. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93474. // add by QuaziKb
  93475. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93476. shape.updateProxy();
  93477. }
  93478. },
  93479. applyImpulse: function (position, force) {
  93480. this.linearVelocity.addScale(force, this.inverseMass);
  93481. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93482. this.linearVelocity.y+=force.y*this.inverseMass;
  93483. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93484. var rel = new OIMO.Vec3();
  93485. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93486. this.angularVelocity.addEqual(rel);
  93487. /*this.angularVelocity.x+=rel.x;
  93488. this.angularVelocity.y+=rel.y;
  93489. this.angularVelocity.z+=rel.z;*/
  93490. },
  93491. //---------------------------------------------
  93492. //
  93493. // FOR THREE JS
  93494. //
  93495. //---------------------------------------------
  93496. rotationVectToQuad: function (rot) {
  93497. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93498. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93499. },
  93500. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93501. var len = ax * ax + ay * ay + az * az;
  93502. if (len > 0) {
  93503. len = 1 / OIMO.sqrt(len);
  93504. ax *= len;
  93505. ay *= len;
  93506. az *= len;
  93507. }
  93508. var sin = OIMO.sin(rad * 0.5);
  93509. var cos = OIMO.cos(rad * 0.5);
  93510. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93511. },
  93512. //---------------------------------------------
  93513. // SET DYNAMIQUE POSITION AND ROTATION
  93514. //---------------------------------------------
  93515. setPosition: function (pos) {
  93516. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93517. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93518. this.controlPos = true;
  93519. },
  93520. setQuaternion: function (q) {
  93521. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93522. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93523. this.controlRot = true;
  93524. },
  93525. setRotation: function (rot) {
  93526. this.newOrientation = this.rotationVectToQuad(rot);
  93527. this.controlRot = true;
  93528. },
  93529. //---------------------------------------------
  93530. // RESET DYNAMIQUE POSITION AND ROTATION
  93531. //---------------------------------------------
  93532. resetPosition: function (x, y, z) {
  93533. this.linearVelocity.set(0, 0, 0);
  93534. this.angularVelocity.set(0, 0, 0);
  93535. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93536. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93537. this.awake();
  93538. },
  93539. resetQuaternion: function (q) {
  93540. this.angularVelocity.set(0, 0, 0);
  93541. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93542. this.awake();
  93543. },
  93544. resetRotation: function (x, y, z) {
  93545. this.angularVelocity.set(0, 0, 0);
  93546. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93547. this.awake();
  93548. },
  93549. //---------------------------------------------
  93550. // GET POSITION AND ROTATION
  93551. //---------------------------------------------
  93552. getPosition: function () {
  93553. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93554. },
  93555. getRotation: function () {
  93556. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93557. },
  93558. getQuaternion: function () {
  93559. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93560. },
  93561. getMatrix: function () {
  93562. var m = this.matrix.elements;
  93563. var r, p;
  93564. if (!this.sleeping) {
  93565. // rotation matrix
  93566. r = this.rotation.elements;
  93567. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93568. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93569. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93570. // position matrix
  93571. p = this.position;
  93572. m[12] = p.x * OIMO.WORLD_SCALE;
  93573. m[13] = p.y * OIMO.WORLD_SCALE;
  93574. m[14] = p.z * OIMO.WORLD_SCALE;
  93575. // sleep or not ?
  93576. m[15] = 0;
  93577. } else {
  93578. m[15] = 1;
  93579. }
  93580. return m;
  93581. }
  93582. };
  93583. /**
  93584. * The main class of body.
  93585. * is for simplify creation process and data access of rigidRody
  93586. * Rigid body has the shape of a single or multiple collision processing,
  93587. * all setting in object
  93588. *
  93589. * @author loth
  93590. */
  93591. OIMO.Body = function (Obj) {
  93592. var obj = Obj || {};
  93593. if (!obj.world) return;
  93594. if (obj.type === undefined) obj.type = "box";
  93595. this.name = obj.name || '';
  93596. // obsolete use world.add(obj)
  93597. this.body = obj.world.add(obj);
  93598. /*
  93599. // the world where i am
  93600. this.parent = obj.world;
  93601. // Yep my name
  93602. this.name = obj.name || '';
  93603. // I'm dynamique or not
  93604. var move = obj.move || false;
  93605. // I can sleep or not
  93606. var noSleep = obj.noSleep || false;
  93607. // My start position
  93608. var p = obj.pos || [0,0,0];
  93609. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93610. // My size
  93611. var s = obj.size || [1,1,1];
  93612. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93613. // My rotation in degre
  93614. var rot = obj.rot || [0,0,0];
  93615. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93616. var r = [];
  93617. for (var i=0; i<rot.length/3; i++){
  93618. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93619. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93620. }
  93621. // My physics setting
  93622. var sc = obj.sc || new OIMO.ShapeConfig();
  93623. if(obj.config){
  93624. // The density of the shape.
  93625. sc.density = obj.config[0] || 1;
  93626. // The coefficient of friction of the shape.
  93627. sc.friction = obj.config[1] || 0.4;
  93628. // The coefficient of restitution of the shape.
  93629. sc.restitution = obj.config[2] || 0.2;
  93630. // The bits of the collision groups to which the shape belongs.
  93631. sc.belongsTo = obj.config[3] || 1;
  93632. // The bits of the collision groups with which the shape collides.
  93633. sc.collidesWith = obj.config[4] || 0xffffffff;
  93634. }
  93635. if(obj.massPos){
  93636. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93637. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93638. }
  93639. if(obj.massRot){
  93640. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93641. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93642. }
  93643. // My rigidbody
  93644. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93645. // My shapes
  93646. var shapes = [];
  93647. var type = obj.type || "box";
  93648. if( typeof type === 'string' ) type = [type];// single shape
  93649. var n, n2;
  93650. for(var i=0; i<type.length; i++){
  93651. n = i*3;
  93652. n2 = i*4;
  93653. switch(type[i]){
  93654. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93655. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93656. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93657. }
  93658. this.body.addShape(shapes[i]);
  93659. if(i>0){
  93660. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93661. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93662. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93663. }
  93664. }
  93665. // I'm static or i move
  93666. if(move){
  93667. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93668. else this.body.setupMass(0x1, true);
  93669. if(noSleep) this.body.allowSleep = false;
  93670. else this.body.allowSleep = true;
  93671. } else {
  93672. this.body.setupMass(0x2);
  93673. }
  93674. this.body.name = this.name;
  93675. this.sleeping = this.body.sleeping;
  93676. // finaly add to physics world
  93677. this.parent.addRigidBody(this.body);*/
  93678. }
  93679. OIMO.Body.prototype = {
  93680. constructor: OIMO.Body,
  93681. // SET
  93682. setPosition: function (pos) {
  93683. this.body.setPosition(pos);
  93684. },
  93685. setQuaternion: function (q) {
  93686. this.body.setQuaternion(q);
  93687. },
  93688. setRotation: function (rot) {
  93689. this.body.setRotation(rot);
  93690. },
  93691. // GET
  93692. getPosition: function () {
  93693. return this.body.getPosition();
  93694. },
  93695. getRotation: function () {
  93696. return this.body.getRotation();
  93697. },
  93698. getQuaternion: function () {
  93699. return this.body.getQuaternion();
  93700. },
  93701. getMatrix: function () {
  93702. return this.body.getMatrix();
  93703. },
  93704. getSleep: function () {
  93705. return this.body.sleeping;
  93706. },
  93707. // RESET
  93708. resetPosition: function (x, y, z) {
  93709. this.body.resetPosition(x, y, z);
  93710. },
  93711. resetRotation: function (x, y, z) {
  93712. this.body.resetRotation(x, y, z);
  93713. },
  93714. // force wakeup
  93715. awake: function () {
  93716. this.body.awake();
  93717. },
  93718. // remove rigidbody
  93719. remove: function () {
  93720. this.body.dispose();
  93721. //this.parent.removeRigidBody(this.body);
  93722. },
  93723. // test if this object hit another
  93724. checkContact: function (name) {
  93725. this.body.checkContact(name);
  93726. //this.parent.checkContact(this.name, name);
  93727. }
  93728. }
  93729. /**
  93730. * The main class of link.
  93731. * is for simplify creation process and data access of Joint
  93732. * all setting in object
  93733. *
  93734. * @author loth
  93735. */
  93736. OIMO.Link = function (Obj) {
  93737. var obj = Obj || {};
  93738. if (!obj.world) return;
  93739. if (obj.type === undefined) obj.type = "jointHinge";
  93740. this.name = obj.name || '';
  93741. // obsolete use world.add(obj)
  93742. this.joint = obj.world.add(obj);
  93743. // the world where i am
  93744. /*this.parent = obj.world;
  93745. this.name = obj.name || '';
  93746. var type = obj.type || "jointHinge";
  93747. var axe1 = obj.axe1 || [1,0,0];
  93748. var axe2 = obj.axe2 || [1,0,0];
  93749. var pos1 = obj.pos1 || [0,0,0];
  93750. var pos2 = obj.pos2 || [0,0,0];
  93751. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  93752. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  93753. var min, max;
  93754. if(type==="jointDistance"){
  93755. min = obj.min || 0;
  93756. max = obj.max || 10;
  93757. min = min*OIMO.INV_SCALE;
  93758. max = max*OIMO.INV_SCALE;
  93759. }else{
  93760. min = obj.min || 57.29578;
  93761. max = obj.max || 0;
  93762. min = min*OIMO.TO_RAD;
  93763. max = max*OIMO.TO_RAD;
  93764. }
  93765. var limit = obj.limit || null;
  93766. var spring = obj.spring || null;
  93767. var motor = obj.motor || null;
  93768. // joint setting
  93769. var jc = new OIMO.JointConfig();
  93770. jc.allowCollision = obj.collision || false;;
  93771. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  93772. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  93773. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  93774. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  93775. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  93776. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  93777. jc.body1 = obj.body1;
  93778. jc.body2 = obj.body2;
  93779. switch(type){
  93780. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  93781. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  93782. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93783. break;
  93784. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  93785. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  93786. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93787. break;
  93788. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  93789. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  93790. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  93791. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  93792. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  93793. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  93794. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  93795. break;
  93796. }
  93797. this.joint.name = this.name;
  93798. // finaly add to physics world
  93799. this.parent.addJoint(this.joint);*/
  93800. }
  93801. OIMO.Link.prototype = {
  93802. constructor: OIMO.Link,
  93803. getPosition: function () {
  93804. // array of two vect3 [point1, point2]
  93805. return this.joint.getPosition();
  93806. },
  93807. getMatrix: function () {
  93808. return this.joint.getMatrix();
  93809. },
  93810. // remove joint
  93811. remove: function () {
  93812. this.joint.dispose();
  93813. //this.parent.removeJoint(this.joint);
  93814. },
  93815. // force wakeup linked body
  93816. awake: function () {
  93817. this.joint.awake();
  93818. }
  93819. }
  93820. /**
  93821. * The Dictionary class for testing
  93822. * @author lo-th
  93823. */
  93824. OIMO.Dictionary = function () {
  93825. this.data = {};
  93826. this.keys = [];
  93827. };
  93828. OIMO.Dictionary.prototype = {
  93829. constructor: OIMO.Dictionary,
  93830. set: function (value) {
  93831. var key = value.id;
  93832. if (!this.get[key]) this.keys.push(key);
  93833. this.data[key] = value;
  93834. },
  93835. get: function (id) {
  93836. return this.data[id];
  93837. },
  93838. del: function (value) {
  93839. var k = this.keys;
  93840. var n = k.indexOf(value.id);
  93841. if (n > -1) {
  93842. delete this.data[k[n]];
  93843. k.splice(n, 1);
  93844. }
  93845. },
  93846. reset: function () {
  93847. var data = this.data, keys = this.keys, key;
  93848. while (keys.length > 0) {
  93849. key = keys.pop();
  93850. delete data[key];
  93851. }
  93852. }
  93853. };
  93854. OIMO.Performance = function (world) {
  93855. this.parent = world;
  93856. this.infos = new OIMO_ARRAY_TYPE(13);
  93857. this.f = [0, 0, 0];
  93858. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  93859. this.broadPhase = this.types[this.parent.broadPhase.types];
  93860. this.version = OIMO.REVISION;
  93861. this.fps = 0;
  93862. this.broadPhaseTime = 0;
  93863. this.narrowPhaseTime = 0;
  93864. this.solvingTime = 0;
  93865. //this.updatingTime = 0;
  93866. this.totalTime = 0;
  93867. };
  93868. OIMO.Performance.prototype = {
  93869. upfps: function () {
  93870. this.f[1] = Date.now();
  93871. 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]++;
  93872. },
  93873. updatingTime: function () {
  93874. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  93875. },
  93876. show: function () {
  93877. var info = [
  93878. "Oimo.js " + this.version + "<br>",
  93879. this.broadPhase + "<br><br>",
  93880. "FPS: " + this.fps + " fps<br><br>",
  93881. "rigidbody " + this.parent.numRigidBodies + "<br>",
  93882. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  93883. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  93884. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  93885. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  93886. "Time in milliseconde<br><br>",
  93887. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  93888. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  93889. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  93890. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  93891. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  93892. ].join("\n");
  93893. return info;
  93894. },
  93895. toArray: function () {
  93896. this.infos[0] = this.parent.broadPhase.types;
  93897. this.infos[1] = this.parent.numRigidBodies;
  93898. this.infos[2] = this.parent.numContacts;
  93899. this.infos[3] = this.parent.broadPhase.numPairChecks;
  93900. this.infos[4] = this.parent.numContactPoints;
  93901. this.infos[5] = this.parent.numIslands;
  93902. this.infos[6] = this.broadPhaseTime;
  93903. this.infos[7] = this.narrowPhaseTime;
  93904. this.infos[8] = this.solvingTime;
  93905. this.infos[9] = this.updatingTime();
  93906. this.infos[10] = this.totalTime;
  93907. this.infos[11] = this.fps;
  93908. return this.infos;
  93909. }
  93910. };
  93911. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93912. this.elements = new OIMO_ARRAY_TYPE(16);
  93913. var te = this.elements;
  93914. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  93915. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  93916. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  93917. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  93918. };
  93919. OIMO.Mat44.prototype = {
  93920. constructor: OIMO.Mat44,
  93921. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93922. var te = this.elements;
  93923. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  93924. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  93925. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  93926. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  93927. return this;
  93928. }/*,
  93929. extractRotation: function () {
  93930. var v1 = new THREE.Vector3();
  93931. return function ( m ) {
  93932. var te = this.elements;
  93933. var me = m.elements;
  93934. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  93935. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  93936. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  93937. te[ 0 ] = me[ 0 ] * scaleX;
  93938. te[ 1 ] = me[ 1 ] * scaleX;
  93939. te[ 2 ] = me[ 2 ] * scaleX;
  93940. te[ 4 ] = me[ 4 ] * scaleY;
  93941. te[ 5 ] = me[ 5 ] * scaleY;
  93942. te[ 6 ] = me[ 6 ] * scaleY;
  93943. te[ 8 ] = me[ 8 ] * scaleZ;
  93944. te[ 9 ] = me[ 9 ] * scaleZ;
  93945. te[ 10 ] = me[ 10 ] * scaleZ;
  93946. return this;
  93947. };
  93948. }() */
  93949. }
  93950. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93951. this.elements = new OIMO_ARRAY_TYPE(9);
  93952. var te = this.elements;
  93953. this.init(
  93954. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  93955. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  93956. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  93957. );
  93958. };
  93959. OIMO.Mat33.prototype = {
  93960. constructor: OIMO.Mat33,
  93961. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93962. var te = this.elements;
  93963. te[0] = e00; te[1] = e01; te[2] = e02;
  93964. te[3] = e10; te[4] = e11; te[5] = e12;
  93965. te[6] = e20; te[7] = e21; te[8] = e22;
  93966. return this;
  93967. },
  93968. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93969. var te = this.elements;
  93970. te[0] = e00; te[1] = e01; te[2] = e02;
  93971. te[3] = e10; te[4] = e11; te[5] = e12;
  93972. te[6] = e20; te[7] = e21; te[8] = e22;
  93973. return this;
  93974. },
  93975. multiply: function (s) {
  93976. var te = this.elements;
  93977. te[0] *= s; te[1] *= s; te[2] *= s;
  93978. te[3] *= s; te[4] *= s; te[5] *= s;
  93979. te[6] *= s; te[7] *= s; te[8] *= s;
  93980. return this;
  93981. },
  93982. add: function (m1, m2) {
  93983. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93984. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  93985. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  93986. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  93987. return this;
  93988. },
  93989. addEqual: function (m) {
  93990. var te = this.elements, tem = m.elements;
  93991. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  93992. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  93993. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  93994. return this;
  93995. },
  93996. sub: function (m1, m2) {
  93997. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93998. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  93999. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94000. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94001. return this;
  94002. },
  94003. subEqual: function (m) {
  94004. var te = this.elements, tem = m.elements;
  94005. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94006. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94007. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94008. return this;
  94009. },
  94010. scale: function (m, s) {
  94011. var te = this.elements, tm = m.elements;
  94012. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94013. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94014. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94015. return this;
  94016. },
  94017. scaleEqual: function (s) {
  94018. var te = this.elements;
  94019. te[0] *= s; te[1] *= s; te[2] *= s;
  94020. te[3] *= s; te[4] *= s; te[5] *= s;
  94021. te[6] *= s; te[7] *= s; te[8] *= s;
  94022. return this;
  94023. },
  94024. mul: function (m1, m2) {
  94025. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94026. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94027. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94028. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94029. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94030. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94031. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94032. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94033. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94034. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94035. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94036. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94037. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94038. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94039. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94040. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94041. return this;
  94042. },
  94043. mulScale: function (m, sx, sy, sz, Prepend) {
  94044. var prepend = Prepend || false;
  94045. var te = this.elements, tm = m.elements;
  94046. if (prepend) {
  94047. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94048. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94049. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94050. } else {
  94051. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94052. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94053. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94054. }
  94055. return this;
  94056. },
  94057. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94058. var prepend = Prepend || false;
  94059. var s = OIMO.sin(rad);
  94060. var c = OIMO.cos(rad);
  94061. var c1 = 1 - c;
  94062. var r00 = ax * ax * c1 + c;
  94063. var r01 = ax * ay * c1 - az * s;
  94064. var r02 = ax * az * c1 + ay * s;
  94065. var r10 = ay * ax * c1 + az * s;
  94066. var r11 = ay * ay * c1 + c;
  94067. var r12 = ay * az * c1 - ax * s;
  94068. var r20 = az * ax * c1 - ay * s;
  94069. var r21 = az * ay * c1 + ax * s;
  94070. var r22 = az * az * c1 + c;
  94071. var tm = m.elements;
  94072. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94073. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94074. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94075. var te = this.elements;
  94076. if (prepend) {
  94077. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94078. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94079. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94080. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94081. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94082. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94083. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94084. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94085. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94086. } else {
  94087. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94088. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94089. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94090. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94091. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94092. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94093. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94094. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94095. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94096. }
  94097. return this;
  94098. },
  94099. transpose: function (m) {
  94100. var te = this.elements, tm = m.elements;
  94101. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94102. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94103. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94104. return this;
  94105. },
  94106. setQuat: function (q) {
  94107. var te = this.elements,
  94108. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94109. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94110. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94111. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94112. te[0] = 1 - yy - zz;
  94113. te[1] = xy - sz;
  94114. te[2] = xz + sy;
  94115. te[3] = xy + sz;
  94116. te[4] = 1 - xx - zz;
  94117. te[5] = yz - sx;
  94118. te[6] = xz - sy;
  94119. te[7] = yz + sx;
  94120. te[8] = 1 - xx - yy;
  94121. return this;
  94122. },
  94123. invert: function (m) {
  94124. var te = this.elements, tm = m.elements,
  94125. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94126. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94127. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94128. b01 = a4 * a8 - a7 * a5,
  94129. b11 = a7 * a2 - a1 * a8,
  94130. b21 = a1 * a5 - a4 * a2,
  94131. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94132. if (dt != 0) { dt = 1.0 / dt; }
  94133. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94134. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94135. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94136. te[3] = dt * (a5 * a6 - a3 * a8);
  94137. te[4] = dt * (a0 * a8 - a2 * a6);
  94138. te[5] = dt * (a2 * a3 - a0 * a5);
  94139. te[6] = dt * (a3 * a7 - a4 * a6);
  94140. te[7] = dt * (a1 * a6 - a0 * a7);
  94141. te[8] = dt * (a0 * a4 - a1 * a3);
  94142. return this;
  94143. },
  94144. /*copy: function(m){
  94145. var te = this.elements, tem = m.elements;
  94146. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94147. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94148. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94149. return this;
  94150. },*/
  94151. toEuler: function () { // not work !!
  94152. function clamp(x) {
  94153. return OIMO.min(OIMO.max(x, -1), 1);
  94154. }
  94155. var te = this.elements;
  94156. var m11 = te[0], m12 = te[3], m13 = te[6];
  94157. var m21 = te[1], m22 = te[4], m23 = te[7];
  94158. var m31 = te[2], m32 = te[5], m33 = te[8];
  94159. var p = new OIMO.Vec3();
  94160. var d = new OIMO.Quat();
  94161. var s;
  94162. p.y = OIMO.asin(clamp(m13));
  94163. if (OIMO.abs(m13) < 0.99999) {
  94164. p.x = OIMO.atan2(-m23, m33);
  94165. p.z = OIMO.atan2(-m12, m11);
  94166. } else {
  94167. p.x = OIMO.atan2(m32, m22);
  94168. p.z = 0;
  94169. }
  94170. return p;
  94171. },
  94172. /*clone: function(){
  94173. var te = this.elements;
  94174. return new OIMO.Mat33(
  94175. te[0], te[1], te[2],
  94176. te[3], te[4], te[5],
  94177. te[6], te[7], te[8]
  94178. );
  94179. },*/
  94180. toString: function () {
  94181. var te = this.elements;
  94182. var text =
  94183. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94184. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94185. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94186. return text;
  94187. },
  94188. // OK
  94189. multiplyScalar: function (s) {
  94190. var te = this.elements;
  94191. te[0] *= s; te[3] *= s; te[6] *= s;
  94192. te[1] *= s; te[4] *= s; te[7] *= s;
  94193. te[2] *= s; te[5] *= s; te[8] *= s;
  94194. return this;
  94195. },
  94196. identity: function () {
  94197. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94198. return this;
  94199. },
  94200. clone: function () {
  94201. return new this.constructor().fromArray(this.elements);
  94202. },
  94203. copy: function (m) {
  94204. var me = m.elements;
  94205. this.set(
  94206. me[0], me[3], me[6],
  94207. me[1], me[4], me[7],
  94208. me[2], me[5], me[8]
  94209. );
  94210. return this;
  94211. },
  94212. fromArray: function (array) {
  94213. this.elements.set(array);
  94214. return this;
  94215. },
  94216. toArray: function () {
  94217. var te = this.elements;
  94218. return [
  94219. te[0], te[1], te[2],
  94220. te[3], te[4], te[5],
  94221. te[6], te[7], te[8]
  94222. ];
  94223. }
  94224. };
  94225. OIMO.Quat = function (s, x, y, z) {
  94226. this.s = (s !== undefined) ? s : 1;
  94227. this.x = x || 0;
  94228. this.y = y || 0;
  94229. this.z = z || 0;
  94230. };
  94231. OIMO.Quat.prototype = {
  94232. constructor: OIMO.Quat,
  94233. set: function (x, y, z, w) {
  94234. this.x = x;
  94235. this.y = y;
  94236. this.z = z;
  94237. this.s = w;
  94238. return this;
  94239. },
  94240. init: function (s, x, y, z) {
  94241. this.s = (s !== undefined) ? s : 1;
  94242. this.x = x || 0;
  94243. this.y = y || 0;
  94244. this.z = z || 0;
  94245. return this;
  94246. },
  94247. add: function (q1, q2) {
  94248. this.s = q1.s + q2.s;
  94249. this.x = q1.x + q2.x;
  94250. this.y = q1.y + q2.y;
  94251. this.z = q1.z + q2.z;
  94252. return this;
  94253. },
  94254. addTime: function (v, t) {
  94255. var x = v.x;
  94256. var y = v.y;
  94257. var z = v.z;
  94258. var qs = this.s;
  94259. var qx = this.x;
  94260. var qy = this.y;
  94261. var qz = this.z;
  94262. t *= 0.5;
  94263. var ns = (-x * qx - y * qy - z * qz) * t;
  94264. var nx = (x * qs + y * qz - z * qy) * t;
  94265. var ny = (-x * qz + y * qs + z * qx) * t;
  94266. var nz = (x * qy - y * qx + z * qs) * t;
  94267. qs += ns;
  94268. qx += nx;
  94269. qy += ny;
  94270. qz += nz;
  94271. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94272. this.s = qs * s;
  94273. this.x = qx * s;
  94274. this.y = qy * s;
  94275. this.z = qz * s;
  94276. return this;
  94277. },
  94278. sub: function (q1, q2) {
  94279. this.s = q1.s - q2.s;
  94280. this.x = q1.x - q2.x;
  94281. this.y = q1.y - q2.y;
  94282. this.z = q1.z - q2.z;
  94283. return this;
  94284. },
  94285. scale: function (q, s) {
  94286. this.s = q.s * s;
  94287. this.x = q.x * s;
  94288. this.y = q.y * s;
  94289. this.z = q.z * s;
  94290. return this;
  94291. },
  94292. mul: function (q1, q2) {
  94293. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94294. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94295. this.x = ax * bs + as * bx + ay * bz - az * by;
  94296. this.y = ay * bs + as * by + az * bx - ax * bz;
  94297. this.z = az * bs + as * bz + ax * by - ay * bx;
  94298. this.s = as * bs - ax * bx - ay * by - az * bz;
  94299. return this;
  94300. },
  94301. arc: function (v1, v2) {
  94302. var x1 = v1.x;
  94303. var y1 = v1.y;
  94304. var z1 = v1.z;
  94305. var x2 = v2.x;
  94306. var y2 = v2.y;
  94307. var z2 = v2.z;
  94308. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94309. if (d == -1) {
  94310. x2 = y1 * x1 - z1 * z1;
  94311. y2 = -z1 * y1 - x1 * x1;
  94312. z2 = x1 * z1 + y1 * y1;
  94313. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94314. this.s = 0;
  94315. this.x = x2 * d;
  94316. this.y = y2 * d;
  94317. this.z = z2 * d;
  94318. return this;
  94319. }
  94320. var cx = y1 * z2 - z1 * y2;
  94321. var cy = z1 * x2 - x1 * z2;
  94322. var cz = x1 * y2 - y1 * x2;
  94323. this.s = OIMO.sqrt((1 + d) * 0.5);
  94324. d = 0.5 / this.s;
  94325. this.x = cx * d;
  94326. this.y = cy * d;
  94327. this.z = cz * d;
  94328. return this;
  94329. },
  94330. normalize: function (q) {
  94331. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94332. if (len > 0) { len = 1 / len; }
  94333. this.s = q.s * len;
  94334. this.x = q.x * len;
  94335. this.y = q.y * len;
  94336. this.z = q.z * len;
  94337. return this;
  94338. },
  94339. invert: function (q) {
  94340. this.s = q.s;
  94341. this.x = -q.x;
  94342. this.y = -q.y;
  94343. this.z = -q.z;
  94344. return this;
  94345. },
  94346. length: function () {
  94347. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94348. },
  94349. copy: function (q) {
  94350. this.s = q.s;
  94351. this.x = q.x;
  94352. this.y = q.y;
  94353. this.z = q.z;
  94354. return this;
  94355. },
  94356. testDiff: function (q) {
  94357. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94358. else return false;
  94359. },
  94360. clone: function (q) {
  94361. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94362. },
  94363. toString: function () {
  94364. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94365. }
  94366. }
  94367. // for three easy export
  94368. OIMO.Quaternion = function (x, y, z, w) {
  94369. this.x = x || 0;
  94370. this.y = y || 0;
  94371. this.z = z || 0;
  94372. this.w = (w !== undefined) ? w : 1;
  94373. };
  94374. OIMO.Quaternion.prototype = {
  94375. constructor: OIMO.Quaternion,
  94376. setFromRotationMatrix: function (m) {
  94377. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94378. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94379. var te = m.elements,
  94380. m11 = te[0], m12 = te[1], m13 = te[2],
  94381. m21 = te[3], m22 = te[4], m23 = te[5],
  94382. m31 = te[6], m32 = te[7], m33 = te[8],
  94383. trace = m11 + m22 + m33,
  94384. s;
  94385. if (trace > 0) {
  94386. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94387. this.w = 0.25 / s;
  94388. this.x = (m32 - m23) * s;
  94389. this.y = (m13 - m31) * s;
  94390. this.z = (m21 - m12) * s;
  94391. } else if (m11 > m22 && m11 > m33) {
  94392. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94393. this.w = (m32 - m23) / s;
  94394. this.x = 0.25 * s;
  94395. this.y = (m12 + m21) / s;
  94396. this.z = (m13 + m31) / s;
  94397. } else if (m22 > m33) {
  94398. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94399. this.w = (m13 - m31) / s;
  94400. this.x = (m12 + m21) / s;
  94401. this.y = 0.25 * s;
  94402. this.z = (m23 + m32) / s;
  94403. } else {
  94404. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94405. this.w = (m21 - m12) / s;
  94406. this.x = (m13 + m31) / s;
  94407. this.y = (m23 + m32) / s;
  94408. this.z = 0.25 * s;
  94409. }
  94410. //this.onChangeCallback();
  94411. return this;
  94412. }
  94413. }
  94414. OIMO.Vec3 = function (x, y, z) {
  94415. this.x = x || 0;
  94416. this.y = y || 0;
  94417. this.z = z || 0;
  94418. };
  94419. OIMO.Vec3.prototype = {
  94420. constructor: OIMO.Vec3,
  94421. init: function (x, y, z) {
  94422. this.x = x || 0;
  94423. this.y = y || 0;
  94424. this.z = z || 0;
  94425. return this;
  94426. },
  94427. set: function (x, y, z) {
  94428. this.x = x;
  94429. this.y = y;
  94430. this.z = z;
  94431. return this;
  94432. },
  94433. add: function (v1, v2) {
  94434. this.x = v1.x + v2.x;
  94435. this.y = v1.y + v2.y;
  94436. this.z = v1.z + v2.z;
  94437. return this;
  94438. },
  94439. addEqual: function (v) {
  94440. this.x += v.x;
  94441. this.y += v.y;
  94442. this.z += v.z;
  94443. return this;
  94444. },
  94445. addTime: function (v, t) {
  94446. this.x += v.x * t;
  94447. this.y += v.y * t;
  94448. this.z += v.z * t;
  94449. return this;
  94450. },
  94451. sub: function (v1, v2) {
  94452. this.x = v1.x - v2.x;
  94453. this.y = v1.y - v2.y;
  94454. this.z = v1.z - v2.z;
  94455. return this;
  94456. },
  94457. subEqual: function (v) {
  94458. this.x -= v.x;
  94459. this.y -= v.y;
  94460. this.z -= v.z;
  94461. return this;
  94462. },
  94463. addScale: function (v, s) {
  94464. this.x += v.x * s;
  94465. this.y += v.y * s;
  94466. this.z += v.z * s;
  94467. return this;
  94468. },
  94469. scale: function (v, s) {
  94470. this.x = v.x * s;
  94471. this.y = v.y * s;
  94472. this.z = v.z * s;
  94473. return this;
  94474. },
  94475. scaleEqual: function (s) {
  94476. this.x *= s;
  94477. this.y *= s;
  94478. this.z *= s;
  94479. return this;
  94480. },
  94481. /*dot: function(v){
  94482. return this.x*v.x+this.y*v.y+this.z*v.z;
  94483. },*/
  94484. cross: function (v1, v2) {
  94485. var ax = v1.x, ay = v1.y, az = v1.z,
  94486. bx = v2.x, by = v2.y, bz = v2.z;
  94487. this.x = ay * bz - az * by;
  94488. this.y = az * bx - ax * bz;
  94489. this.z = ax * by - ay * bx;
  94490. return this;
  94491. },
  94492. mul: function (o, v, m) {
  94493. var te = m.elements;
  94494. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94495. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94496. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94497. return this;
  94498. },
  94499. mulMat: function (m, v) {
  94500. var te = m.elements;
  94501. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94502. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94503. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94504. return this;
  94505. },
  94506. normalize: function (v) {
  94507. var x = v.x, y = v.y, z = v.z;
  94508. var l = x * x + y * y + z * z;
  94509. if (l > 0) {
  94510. l = 1 / OIMO.sqrt(l);
  94511. this.x = x * l;
  94512. this.y = y * l;
  94513. this.z = z * l;
  94514. }
  94515. return this;
  94516. },
  94517. /*norm: function(){
  94518. var x = this.x, y = this.y, z = this.z;
  94519. var l = x*x + y*y + z*z;
  94520. if (l > 0) {
  94521. l = 1 / OIMO.sqrt(l);
  94522. this.x = x*l;
  94523. this.y = y*l;
  94524. this.z = z*l;
  94525. }
  94526. return this;
  94527. },*/
  94528. invert: function (v) {
  94529. this.x = -v.x;
  94530. this.y = -v.y;
  94531. this.z = -v.z;
  94532. return this;
  94533. },
  94534. /*length: function(){
  94535. var x = this.x, y = this.y, z = this.z;
  94536. return OIMO.sqrt(x*x + y*y + z*z);
  94537. },*/
  94538. negate: function () {
  94539. this.x = -this.x;
  94540. this.y = -this.y;
  94541. this.z = -this.z;
  94542. return this;
  94543. },
  94544. dot: function (v) {
  94545. return this.x * v.x + this.y * v.y + this.z * v.z;
  94546. },
  94547. lengthSq: function () {
  94548. return this.x * this.x + this.y * this.y + this.z * this.z;
  94549. },
  94550. length: function () {
  94551. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94552. },
  94553. /*len: function(){
  94554. var x = this.x, y = this.y, z = this.z;
  94555. return x*x + y*y + z*z;
  94556. },*/
  94557. copy: function (v) {
  94558. this.x = v.x;
  94559. this.y = v.y;
  94560. this.z = v.z;
  94561. return this;
  94562. },
  94563. applyQuaternion: function (q) {
  94564. var x = this.x;
  94565. var y = this.y;
  94566. var z = this.z;
  94567. var qx = q.x;
  94568. var qy = q.y;
  94569. var qz = q.z;
  94570. var qs = q.s;
  94571. // calculate quat * vector
  94572. var ix = qs * x + qy * z - qz * y;
  94573. var iy = qs * y + qz * x - qx * z;
  94574. var iz = qs * z + qx * y - qy * x;
  94575. var iw = -qx * x - qy * y - qz * z;
  94576. // calculate result * inverse quat
  94577. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94578. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94579. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94580. return this;
  94581. },
  94582. testZero: function () {
  94583. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94584. else return false;
  94585. },
  94586. testDiff: function (v) {
  94587. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94588. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94589. //else return false;
  94590. },
  94591. equals: function (v) {
  94592. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94593. },
  94594. clone: function () {
  94595. return new this.constructor(this.x, this.y, this.z);
  94596. },
  94597. toString: function () {
  94598. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94599. },
  94600. multiplyScalar: function (scalar) {
  94601. if (isFinite(scalar)) {
  94602. this.x *= scalar;
  94603. this.y *= scalar;
  94604. this.z *= scalar;
  94605. } else {
  94606. this.x = 0;
  94607. this.y = 0;
  94608. this.z = 0;
  94609. }
  94610. return this;
  94611. },
  94612. divideScalar: function (scalar) {
  94613. return this.multiplyScalar(1 / scalar);
  94614. },
  94615. // TODO rename to normalize
  94616. norm: function () {
  94617. return this.divideScalar(this.length());
  94618. },
  94619. }
  94620. OIMO.Euler = function (x, y, z, order) {
  94621. this._x = x || 0;
  94622. this._y = y || 0;
  94623. this._z = z || 0;
  94624. this._order = order || OIMO.Euler.DefaultOrder;
  94625. };
  94626. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94627. OIMO.Euler.DefaultOrder = 'XYZ';
  94628. OIMO.clamp = function (x, a, b) {
  94629. return (x < a) ? a : ((x > b) ? b : x);
  94630. }
  94631. OIMO.Euler.prototype = {
  94632. constructor: OIMO.Euler,
  94633. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94634. get x() {
  94635. return this._x;
  94636. },
  94637. set x(value) {
  94638. this._x = value;
  94639. this.onChangeCallback();
  94640. },
  94641. get y() {
  94642. return this._y;
  94643. },
  94644. set y(value) {
  94645. this._y = value;
  94646. this.onChangeCallback();
  94647. },
  94648. get z() {
  94649. return this._z;
  94650. },
  94651. set z(value) {
  94652. this._z = value;
  94653. this.onChangeCallback();
  94654. },
  94655. get order() {
  94656. return this._order;
  94657. },
  94658. set order(value) {
  94659. this._order = value;
  94660. this.onChangeCallback();
  94661. },
  94662. set: function (x, y, z, order) {
  94663. this._x = x;
  94664. this._y = y;
  94665. this._z = z;
  94666. this._order = order || this._order;
  94667. this.onChangeCallback();
  94668. return this;
  94669. },
  94670. copy: function (euler) {
  94671. this._x = euler._x;
  94672. this._y = euler._y;
  94673. this._z = euler._z;
  94674. this._order = euler._order;
  94675. this.onChangeCallback();
  94676. return this;
  94677. },
  94678. setFromRotationMatrix: function (m, order) {
  94679. var clamp = OIMO.clamp;
  94680. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94681. var te = m.elements;
  94682. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94683. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94684. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94685. var m11 = te[0], m12 = te[1], m13 = te[2],
  94686. m21 = te[3], m22 = te[4], m23 = te[5],
  94687. m31 = te[6], m32 = te[7], m33 = te[8];
  94688. order = order || this._order;
  94689. if (order === 'XYZ') {
  94690. this._y = OIMO.asin(clamp(m13, -1, 1));
  94691. if (OIMO.abs(m13) < 0.99999) {
  94692. this._x = OIMO.atan2(-m23, m33);
  94693. this._z = OIMO.atan2(-m12, m11);
  94694. } else {
  94695. this._x = OIMO.atan2(m32, m22);
  94696. this._z = 0;
  94697. }
  94698. } else if (order === 'YXZ') {
  94699. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94700. if (OIMO.abs(m23) < 0.99999) {
  94701. this._y = OIMO.atan2(m13, m33);
  94702. this._z = OIMO.atan2(m21, m22);
  94703. } else {
  94704. this._y = OIMO.atan2(-m31, m11);
  94705. this._z = 0;
  94706. }
  94707. } else if (order === 'ZXY') {
  94708. this._x = OIMO.asin(clamp(m32, -1, 1));
  94709. if (OIMO.abs(m32) < 0.99999) {
  94710. this._y = OIMO.atan2(-m31, m33);
  94711. this._z = OIMO.atan2(-m12, m22);
  94712. } else {
  94713. this._y = 0;
  94714. this._z = OIMO.atan2(m21, m11);
  94715. }
  94716. } else if (order === 'ZYX') {
  94717. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94718. if (OIMO.abs(m31) < 0.99999) {
  94719. this._x = OIMO.atan2(m32, m33);
  94720. this._z = OIMO.atan2(m21, m11);
  94721. } else {
  94722. this._x = 0;
  94723. this._z = OIMO.atan2(-m12, m22);
  94724. }
  94725. } else if (order === 'YZX') {
  94726. this._z = OIMO.asin(clamp(m21, -1, 1));
  94727. if (OIMO.abs(m21) < 0.99999) {
  94728. this._x = OIMO.atan2(-m23, m22);
  94729. this._y = OIMO.atan2(-m31, m11);
  94730. } else {
  94731. this._x = 0;
  94732. this._y = OIMO.atan2(m13, m33);
  94733. }
  94734. } else if (order === 'XZY') {
  94735. this._z = OIMO.asin(-clamp(m12, -1, 1));
  94736. if (OIMO.abs(m12) < 0.99999) {
  94737. this._x = OIMO.atan2(m32, m22);
  94738. this._y = OIMO.atan2(m13, m11);
  94739. } else {
  94740. this._x = OIMO.atan2(-m23, m33);
  94741. this._y = 0;
  94742. }
  94743. } else {
  94744. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  94745. }
  94746. this._order = order;
  94747. this.onChangeCallback();
  94748. return this;
  94749. },
  94750. setFromQuaternion: function (q, order, update) {
  94751. var clamp = OIMO.clamp;
  94752. // q is assumed to be normalized
  94753. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  94754. var sqx = q.x * q.x;
  94755. var sqy = q.y * q.y;
  94756. var sqz = q.z * q.z;
  94757. var sqw = q.s * q.s;
  94758. order = order || this._order;
  94759. if (order === 'XYZ') {
  94760. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  94761. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  94762. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  94763. } else if (order === 'YXZ') {
  94764. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  94765. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  94766. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  94767. } else if (order === 'ZXY') {
  94768. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  94769. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  94770. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  94771. } else if (order === 'ZYX') {
  94772. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  94773. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  94774. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  94775. } else if (order === 'YZX') {
  94776. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  94777. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  94778. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  94779. } else if (order === 'XZY') {
  94780. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  94781. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  94782. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  94783. } else {
  94784. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  94785. }
  94786. this._order = order;
  94787. if (update !== false) this.onChangeCallback();
  94788. return this;
  94789. },
  94790. reorder: function () {
  94791. // WARNING: this discards revolution information -bhouston
  94792. var q = new OIMO.Quat();
  94793. return function (newOrder) {
  94794. q.setFromEuler(this);
  94795. this.setFromQuaternion(q, newOrder);
  94796. };
  94797. }(),
  94798. equals: function (euler) {
  94799. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  94800. },
  94801. fromArray: function (array) {
  94802. this._x = array[0];
  94803. this._y = array[1];
  94804. this._z = array[2];
  94805. if (array[3] !== undefined) this._order = array[3];
  94806. this.onChangeCallback();
  94807. return this;
  94808. },
  94809. toArray: function () {
  94810. return [this._x, this._y, this._z, this._order];
  94811. },
  94812. onChange: function (callback) {
  94813. this.onChangeCallback = callback;
  94814. return this;
  94815. },
  94816. onChangeCallback: function () { },
  94817. clone: function () {
  94818. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  94819. }
  94820. };
  94821. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  94822. var c1 = OIMO.cos(oy * 0.5);//heading
  94823. var s1 = OIMO.sin(oy * 0.5);
  94824. var c2 = OIMO.cos(oz * 0.5);//altitude
  94825. var s2 = OIMO.sin(oz * 0.5);
  94826. var c3 = OIMO.cos(ox * 0.5);//bank
  94827. var s3 = OIMO.sin(ox * 0.5);
  94828. var c1c2 = c1 * c2;
  94829. var s1s2 = s1 * s2;
  94830. var w = c1c2 * c3 - s1s2 * s3;
  94831. var x = c1c2 * s3 + s1s2 * c3;
  94832. var y = s1 * c2 * c3 + c1 * s2 * s3;
  94833. var z = c1 * s2 * c3 - s1 * c2 * s3;
  94834. var angle = 2 * OIMO.acos(w);
  94835. var norm = x * x + y * y + z * z;
  94836. if (norm < 0.001) {
  94837. x = 1;
  94838. y = z = 0;
  94839. } else {
  94840. norm = OIMO.sqrt(norm);
  94841. x /= norm;
  94842. y /= norm;
  94843. z /= norm;
  94844. }
  94845. return [angle, x, y, z];
  94846. }
  94847. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  94848. var ch = OIMO.cos(oy);//heading
  94849. var sh = OIMO.sin(oy);
  94850. var ca = OIMO.cos(oz);//altitude
  94851. var sa = OIMO.sin(oz);
  94852. var cb = OIMO.cos(ox);//bank
  94853. var sb = OIMO.sin(ox);
  94854. var mtx = new OIMO.Mat33();
  94855. var te = mtx.elements;
  94856. te[0] = ch * ca;
  94857. te[1] = sh * sb - ch * sa * cb;
  94858. te[2] = ch * sa * sb + sh * cb;
  94859. te[3] = sa;
  94860. te[4] = ca * cb;
  94861. te[5] = -ca * sb;
  94862. te[6] = -sh * ca;
  94863. te[7] = sh * sa * cb + ch * sb;
  94864. te[8] = -sh * sa * sb + ch * cb;
  94865. return mtx;
  94866. }
  94867. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  94868. var te = mtx.elements;
  94869. var x, y, z;
  94870. if (te[3] > 0.998) { // singularity at north pole
  94871. y = OIMO.atan2(te[2], te[8]);
  94872. z = OIMO.PI / 2;
  94873. x = 0;
  94874. } else if (te[3] < -0.998) { // singularity at south pole
  94875. y = OIMO.atan2(te[2], te[8]);
  94876. z = -OIMO.PI / 2;
  94877. x = 0;
  94878. } else {
  94879. y = OIMO.atan2(-te[6], te[0]);
  94880. x = OIMO.atan2(-te[5], te[4]);
  94881. z = OIMO.asin(te[3]);
  94882. }
  94883. return [x, y, z];
  94884. }
  94885. OIMO.unwrapDegrees = function (r) {
  94886. r = r % 360;
  94887. if (r > 180) r -= 360;
  94888. if (r < -180) r += 360;
  94889. return r;
  94890. }
  94891. OIMO.unwrapRadian = function (r) {
  94892. r = r % OIMO.TwoPI;
  94893. if (r > OIMO.PI) r -= OIMO.TwoPI;
  94894. if (r < -OIMO.PI) r += OIMO.TwoPI;
  94895. return r;
  94896. }
  94897. OIMO.Distance3d = function (p1, p2) {
  94898. var xd = p2[0] - p1[0];
  94899. var yd = p2[1] - p1[1];
  94900. var zd = p2[2] - p1[2];
  94901. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  94902. }
  94903. /**
  94904. * The base class of all type of the constraints.
  94905. * @author saharan
  94906. */
  94907. OIMO.Constraint = function () {
  94908. // The parent world of the constraint.
  94909. this.parent = null;
  94910. // The first body of the constraint.
  94911. this.body1 = null;
  94912. // The second body of the constraint.
  94913. this.body2 = null;
  94914. // Internal
  94915. this.addedToIsland = false;
  94916. }
  94917. OIMO.Constraint.prototype = {
  94918. constructor: OIMO.Constraint,
  94919. /**
  94920. * Prepare for solving the constraint.
  94921. * @param timeStep
  94922. * @param invTimeStep
  94923. */
  94924. preSolve: function (timeStep, invTimeStep) {
  94925. OIMO.Error("Constraint", "Inheritance error.");
  94926. },
  94927. /**
  94928. * Solve the constraint.
  94929. * This is usually called iteratively.
  94930. */
  94931. solve: function () {
  94932. OIMO.Error("Constraint", "Inheritance error.");
  94933. },
  94934. /**
  94935. * Do the post-processing.
  94936. */
  94937. postSolve: function () {
  94938. OIMO.Error("Constraint", "Inheritance error.");
  94939. }
  94940. }
  94941. /**
  94942. * Joints are used to constrain the motion between two rigid bodies.
  94943. * @author saharan
  94944. * @author lo-th
  94945. */
  94946. OIMO.Joint = function (config) {
  94947. OIMO.Constraint.call(this);
  94948. // joint name
  94949. this.name = "";
  94950. // The type of the joint.
  94951. this.type = OIMO.JOINT_NULL;
  94952. // The previous joint in the world.
  94953. this.prev = null;
  94954. // The next joint in the world.
  94955. this.next = null;
  94956. this.body1 = config.body1;
  94957. this.body2 = config.body2;
  94958. // The anchor point on the first rigid body in local coordinate system.
  94959. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  94960. // The anchor point on the second rigid body in local coordinate system.
  94961. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  94962. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  94963. this.relativeAnchorPoint1 = new OIMO.Vec3();
  94964. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  94965. this.relativeAnchorPoint2 = new OIMO.Vec3();
  94966. // The anchor point on the first rigid body in world coordinate system.
  94967. this.anchorPoint1 = new OIMO.Vec3();
  94968. // The anchor point on the second rigid body in world coordinate system.
  94969. this.anchorPoint2 = new OIMO.Vec3();
  94970. // Whether allow collision between connected rigid bodies or not.
  94971. this.allowCollision = config.allowCollision;
  94972. this.b1Link = new OIMO.JointLink(this);
  94973. this.b2Link = new OIMO.JointLink(this);
  94974. this.matrix = new OIMO.Mat44();
  94975. };
  94976. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  94977. OIMO.Joint.prototype.constructor = OIMO.Joint;
  94978. // Update all the anchor points.
  94979. OIMO.Joint.prototype.updateAnchorPoints = function () {
  94980. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  94981. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  94982. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  94983. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  94984. };
  94985. // Attach the joint from the bodies.
  94986. OIMO.Joint.prototype.attach = function () {
  94987. this.b1Link.body = this.body2;
  94988. this.b2Link.body = this.body1;
  94989. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  94990. else this.b1Link.next = null;
  94991. this.body1.jointLink = this.b1Link;
  94992. this.body1.numJoints++;
  94993. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  94994. else this.b2Link.next = null;
  94995. this.body2.jointLink = this.b2Link;
  94996. this.body2.numJoints++;
  94997. };
  94998. // Detach the joint from the bodies.
  94999. OIMO.Joint.prototype.detach = function () {
  95000. var prev = this.b1Link.prev;
  95001. var next = this.b1Link.next;
  95002. if (prev != null) prev.next = next;
  95003. if (next != null) next.prev = prev;
  95004. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95005. this.b1Link.prev = null;
  95006. this.b1Link.next = null;
  95007. this.b1Link.body = null;
  95008. this.body1.numJoints--;
  95009. prev = this.b2Link.prev;
  95010. next = this.b2Link.next;
  95011. if (prev != null) prev.next = next;
  95012. if (next != null) next.prev = prev;
  95013. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95014. this.b2Link.prev = null;
  95015. this.b2Link.next = null;
  95016. this.b2Link.body = null;
  95017. this.body2.numJoints--;
  95018. this.b1Link.body = null;
  95019. this.b2Link.body = null;
  95020. };
  95021. // Awake the bodies.
  95022. OIMO.Joint.prototype.awake = function () {
  95023. this.body1.awake();
  95024. this.body2.awake();
  95025. };
  95026. // calculation function
  95027. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95028. };
  95029. OIMO.Joint.prototype.solve = function () {
  95030. };
  95031. OIMO.Joint.prototype.postSolve = function () {
  95032. };
  95033. // Delete process
  95034. OIMO.Joint.prototype.remove = function () {
  95035. this.dispose();
  95036. };
  95037. OIMO.Joint.prototype.dispose = function () {
  95038. this.parent.removeJoint(this);
  95039. };
  95040. // Three js add
  95041. OIMO.Joint.prototype.getPosition = function () {
  95042. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95043. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95044. return [p1, p2];
  95045. };
  95046. OIMO.Joint.prototype.getMatrix = function () {
  95047. var m = this.matrix.elements;
  95048. var p1 = this.anchorPoint1;
  95049. var p2 = this.anchorPoint2;
  95050. m[0] = p1.x * OIMO.WORLD_SCALE;
  95051. m[1] = p1.y * OIMO.WORLD_SCALE;
  95052. m[2] = p1.z * OIMO.WORLD_SCALE;
  95053. m[3] = 0;
  95054. m[4] = p2.x * OIMO.WORLD_SCALE;
  95055. m[5] = p2.y * OIMO.WORLD_SCALE;
  95056. m[6] = p2.z * OIMO.WORLD_SCALE;
  95057. m[7] = 0;
  95058. return m;
  95059. };
  95060. /**
  95061. * A joint configuration holds all configuration data for constructing a joint.
  95062. * Joint configurations can be reused safely.
  95063. * @author saharan
  95064. */
  95065. OIMO.JointConfig = function () {
  95066. // The first rigid body of the joint.
  95067. this.body1 = null;
  95068. // The second rigid body of the joint.
  95069. this.body2 = null;
  95070. // The anchor point on the first rigid body in local coordinate system.
  95071. this.localAnchorPoint1 = new OIMO.Vec3();
  95072. // The anchor point on the second rigid body in local coordinate system.
  95073. this.localAnchorPoint2 = new OIMO.Vec3();
  95074. // The axis in the first body's coordinate system.
  95075. // his property is available in some joints.
  95076. this.localAxis1 = new OIMO.Vec3();
  95077. // The axis in the second body's coordinate system.
  95078. // This property is available in some joints.
  95079. this.localAxis2 = new OIMO.Vec3();
  95080. // Whether allow collision between connected rigid bodies or not.
  95081. this.allowCollision = false;
  95082. };
  95083. /**
  95084. * A link list of joints.
  95085. * @author saharan
  95086. */
  95087. OIMO.JointLink = function (joint) {
  95088. // The previous joint link.
  95089. this.prev = null;
  95090. // The next joint link.
  95091. this.next = null;
  95092. // The other rigid body connected to the joint.
  95093. this.body = null;
  95094. // The joint of the link.
  95095. this.joint = joint;
  95096. };
  95097. /**
  95098. * An information of limit and motor.
  95099. * @author saharan
  95100. */
  95101. OIMO.LimitMotor = function (axis, fixed) {
  95102. fixed = fixed || false;
  95103. // The axis of the constraint.
  95104. this.axis = axis;
  95105. // The current angle for rotational constraints.
  95106. this.angle = 0;
  95107. // The lower limit. Set lower > upper to disable
  95108. this.lowerLimit = fixed ? 0 : 1;
  95109. //if(fixed)this.lowerLimit = 0;
  95110. //else this.lowerLimit = 1;
  95111. // The upper limit. Set lower > upper to disable.
  95112. this.upperLimit = 0;
  95113. // The target motor speed.
  95114. this.motorSpeed = 0;
  95115. // The maximum motor force or torque. Set 0 to disable.
  95116. this.maxMotorForce = 0;
  95117. // The frequency of the spring. Set 0 to disable.
  95118. this.frequency = 0;
  95119. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95120. this.dampingRatio = 0;
  95121. };
  95122. OIMO.LimitMotor.prototype = {
  95123. constructor: OIMO.LimitMotor,
  95124. /**
  95125. * Set limit data into this constraint.
  95126. * @param lowerLimit
  95127. * @param upperLimit
  95128. */
  95129. setLimit: function (lowerLimit, upperLimit) {
  95130. this.lowerLimit = lowerLimit;
  95131. this.upperLimit = upperLimit;
  95132. },
  95133. /**
  95134. * Set motor data into this constraint.
  95135. * @param motorSpeed
  95136. * @param maxMotorForce
  95137. */
  95138. setMotor: function (motorSpeed, maxMotorForce) {
  95139. this.motorSpeed = motorSpeed;
  95140. this.maxMotorForce = maxMotorForce;
  95141. },
  95142. /**
  95143. * Set spring data into this constraint.
  95144. * @param frequency
  95145. * @param dampingRatio
  95146. */
  95147. setSpring: function (frequency, dampingRatio) {
  95148. this.frequency = frequency;
  95149. this.dampingRatio = dampingRatio;
  95150. }
  95151. };
  95152. /**
  95153. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95154. * @author saharan
  95155. * @author lo-th
  95156. */
  95157. OIMO.BallAndSocketJoint = function (config) {
  95158. OIMO.Joint.call(this, config);
  95159. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95160. this.lc = new OIMO.LinearConstraint(this);
  95161. };
  95162. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95163. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95164. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95165. this.updateAnchorPoints();
  95166. this.lc.preSolve(timeStep, invTimeStep);
  95167. };
  95168. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95169. this.lc.solve();
  95170. };
  95171. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95172. };
  95173. /**
  95174. * A distance joint limits the distance between two anchor points on rigid bodies.
  95175. * @author saharan
  95176. * @author lo-th
  95177. */
  95178. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95179. OIMO.Joint.call(this, config);
  95180. this.type = OIMO.JOINT_DISTANCE;
  95181. this.normal = new OIMO.Vec3();
  95182. this.nr = new OIMO.Vec3();
  95183. // The limit and motor information of the joint.
  95184. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95185. this.limitMotor.lowerLimit = minDistance;
  95186. this.limitMotor.upperLimit = maxDistance;
  95187. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95188. };
  95189. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95190. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95191. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95192. this.updateAnchorPoints();
  95193. //var nr = this.nr;
  95194. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95195. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95196. //if(len>0) len = 1/len;
  95197. //this.normal.scale( nr, len );
  95198. this.normal.normalize(this.nr);
  95199. this.t.preSolve(timeStep, invTimeStep);
  95200. };
  95201. OIMO.DistanceJoint.prototype.solve = function () {
  95202. this.t.solve();
  95203. };
  95204. OIMO.DistanceJoint.prototype.postSolve = function () {
  95205. };
  95206. /**
  95207. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95208. * @author saharan
  95209. * @author lo-th
  95210. */
  95211. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95212. OIMO.Joint.call(this, config);
  95213. this.type = OIMO.JOINT_HINGE;
  95214. // The axis in the first body's coordinate system.
  95215. this.localAxis1 = config.localAxis1.clone().norm();
  95216. // The axis in the second body's coordinate system.
  95217. this.localAxis2 = config.localAxis2.clone().norm();
  95218. // make angle axis 1
  95219. this.localAngle1 = new OIMO.Vec3(
  95220. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95221. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95222. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95223. ).norm();
  95224. // make angle axis 2
  95225. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95226. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95227. this.nor = new OIMO.Vec3();
  95228. this.tan = new OIMO.Vec3();
  95229. this.bin = new OIMO.Vec3();
  95230. this.ax1 = new OIMO.Vec3();
  95231. this.ax2 = new OIMO.Vec3();
  95232. this.an1 = new OIMO.Vec3();
  95233. this.an2 = new OIMO.Vec3();
  95234. // The rotational limit and motor information of the joint.
  95235. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95236. this.limitMotor.lowerLimit = lowerAngleLimit;
  95237. this.limitMotor.upperLimit = upperAngleLimit;
  95238. this.lc = new OIMO.LinearConstraint(this);
  95239. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95240. };
  95241. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95242. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95243. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95244. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95245. this.updateAnchorPoints();
  95246. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95247. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95248. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95249. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95250. this.nor.set(
  95251. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95252. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95253. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95254. ).norm();
  95255. this.tan.set(
  95256. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95257. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95258. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95259. ).norm();
  95260. this.bin.set(
  95261. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95262. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95263. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95264. );
  95265. // calculate hinge angle
  95266. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95267. if (
  95268. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95269. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95270. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95271. ) {
  95272. this.limitMotor.angle = -limite;
  95273. } else {
  95274. this.limitMotor.angle = limite;
  95275. }
  95276. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95277. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95278. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95279. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95280. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95281. this.r3.preSolve(timeStep, invTimeStep);
  95282. this.lc.preSolve(timeStep, invTimeStep);
  95283. };
  95284. OIMO.HingeJoint.prototype.solve = function () {
  95285. this.r3.solve();
  95286. this.lc.solve();
  95287. };
  95288. OIMO.HingeJoint.prototype.postSolve = function () {
  95289. };
  95290. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95291. if (cos > 1) return 0;
  95292. else if (cos < -1) return OIMO.PI;
  95293. else return OIMO.acos(cos);
  95294. };
  95295. /**
  95296. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95297. * @author saharan
  95298. * @author lo-th
  95299. */
  95300. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95301. OIMO.Joint.call(this, config);
  95302. this.type = OIMO.JOINT_PRISMATIC;
  95303. // The axis in the first body's coordinate system.
  95304. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95305. // The axis in the second body's coordinate system.
  95306. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95307. this.localAxis1X = this.localAxis1.x;
  95308. this.localAxis1Y = this.localAxis1.y;
  95309. this.localAxis1Z = this.localAxis1.z;
  95310. this.localAxis2X = this.localAxis2.x;
  95311. this.localAxis2Y = this.localAxis2.y;
  95312. this.localAxis2Z = this.localAxis2.z;
  95313. this.nor = new OIMO.Vec3();
  95314. this.tan = new OIMO.Vec3();
  95315. this.bin = new OIMO.Vec3();
  95316. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95317. // The translational limit and motor information of the joint.
  95318. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95319. this.limitMotor.lowerLimit = lowerTranslation;
  95320. this.limitMotor.upperLimit = upperTranslation;
  95321. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95322. };
  95323. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95324. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95325. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95326. var tmpM;
  95327. var tmp1X;
  95328. var tmp1Y;
  95329. var tmp1Z;
  95330. this.updateAnchorPoints();
  95331. tmpM = this.body1.rotation.elements;
  95332. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95333. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95334. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95335. tmpM = this.body2.rotation.elements;
  95336. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95337. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95338. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95339. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95340. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95341. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95342. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95343. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95344. nx *= tmp1X;
  95345. ny *= tmp1X;
  95346. nz *= tmp1X;
  95347. var tx = ny * nx - nz * nz;
  95348. var ty = -nz * ny - nx * nx;
  95349. var tz = nx * nz + ny * ny;
  95350. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95351. tx *= tmp1X;
  95352. ty *= tmp1X;
  95353. tz *= tmp1X;
  95354. var bx = ny * tz - nz * ty;
  95355. var by = nz * tx - nx * tz;
  95356. var bz = nx * ty - ny * tx;
  95357. this.nor.init(nx, ny, nz);
  95358. this.tan.init(tx, ty, tz);
  95359. this.bin.init(bx, by, bz);
  95360. this.ac.preSolve(timeStep, invTimeStep);
  95361. this.t3.preSolve(timeStep, invTimeStep);
  95362. };
  95363. OIMO.PrismaticJoint.prototype.solve = function () {
  95364. this.ac.solve();
  95365. this.t3.solve();
  95366. };
  95367. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95368. };
  95369. /**
  95370. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95371. * @author saharan
  95372. * @author lo-th
  95373. */
  95374. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95375. OIMO.Joint.call(this, config);
  95376. this.type = OIMO.JOINT_SLIDER;
  95377. // The first axis in local coordinate system.
  95378. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95379. // The second axis in local coordinate system.
  95380. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95381. var len;
  95382. this.localAxis1X = this.localAxis1.x;
  95383. this.localAxis1Y = this.localAxis1.y;
  95384. this.localAxis1Z = this.localAxis1.z;
  95385. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95386. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95387. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95388. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95389. this.localAngAxis1X *= len;
  95390. this.localAngAxis1Y *= len;
  95391. this.localAngAxis1Z *= len;
  95392. this.localAxis2X = this.localAxis2.x;
  95393. this.localAxis2Y = this.localAxis2.y;
  95394. this.localAxis2Z = this.localAxis2.z;
  95395. // make angle axis 2
  95396. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95397. var tarc = arc.elements;
  95398. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95399. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95400. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95401. this.nor = new OIMO.Vec3();
  95402. this.tan = new OIMO.Vec3();
  95403. this.bin = new OIMO.Vec3();
  95404. // The limit and motor for the rotation
  95405. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95406. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95407. // The limit and motor for the translation.
  95408. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95409. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95410. this.translationalLimitMotor.upperLimit = upperTranslation;
  95411. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95412. };
  95413. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95414. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95415. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95416. var tmpM;
  95417. var tmp1X;
  95418. var tmp1Y;
  95419. var tmp1Z;
  95420. this.updateAnchorPoints();
  95421. tmpM = this.body1.rotation.elements;
  95422. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95423. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95424. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95425. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95426. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95427. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95428. tmpM = this.body2.rotation.elements;
  95429. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95430. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95431. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95432. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95433. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95434. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95435. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95436. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95437. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95438. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95439. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95440. nx *= tmp1X;
  95441. ny *= tmp1X;
  95442. nz *= tmp1X;
  95443. var tx = ny * nx - nz * nz;
  95444. var ty = -nz * ny - nx * nx;
  95445. var tz = nx * nz + ny * ny;
  95446. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95447. tx *= tmp1X;
  95448. ty *= tmp1X;
  95449. tz *= tmp1X;
  95450. var bx = ny * tz - nz * ty;
  95451. var by = nz * tx - nx * tz;
  95452. var bz = nx * ty - ny * tx;
  95453. this.nor.init(nx, ny, nz);
  95454. this.tan.init(tx, ty, tz);
  95455. this.bin.init(bx, by, bz);
  95456. // ----------------------------------------------
  95457. // calculate hinge angle
  95458. // ----------------------------------------------
  95459. if (
  95460. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95461. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95462. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95463. ) {
  95464. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95465. } else {
  95466. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95467. }
  95468. // angular error
  95469. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95470. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95471. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95472. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95473. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95474. this.r3.preSolve(timeStep, invTimeStep);
  95475. this.t3.preSolve(timeStep, invTimeStep);
  95476. };
  95477. OIMO.SliderJoint.prototype.solve = function () {
  95478. this.r3.solve();
  95479. this.t3.solve();
  95480. };
  95481. OIMO.SliderJoint.prototype.postSolve = function () {
  95482. };
  95483. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95484. if (cos > 1) return 0;
  95485. else if (cos < -1) return OIMO.PI;
  95486. else return OIMO.acos(cos);
  95487. };
  95488. /**
  95489. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95490. * The wheel joint also allows for relative translation for the suspension.
  95491. * @author saharan
  95492. * @author lo-th
  95493. */
  95494. OIMO.WheelJoint = function (config) {
  95495. OIMO.Joint.call(this, config);
  95496. this.type = OIMO.JOINT_WHEEL;
  95497. // The first axis in local coordinate system.
  95498. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95499. // The second axis in local coordinate system.
  95500. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95501. var len;
  95502. this.localAxis1X = this.localAxis1.x;
  95503. this.localAxis1Y = this.localAxis1.y;
  95504. this.localAxis1Z = this.localAxis1.z;
  95505. this.localAxis2X = this.localAxis2.x;
  95506. this.localAxis2Y = this.localAxis2.y;
  95507. this.localAxis2Z = this.localAxis2.z;
  95508. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95509. if (dot > -1 && dot < 1) {
  95510. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95511. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95512. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95513. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95514. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95515. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95516. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95517. this.localAngAxis1X *= len;
  95518. this.localAngAxis1Y *= len;
  95519. this.localAngAxis1Z *= len;
  95520. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95521. this.localAngAxis2X *= len;
  95522. this.localAngAxis2Y *= len;
  95523. this.localAngAxis2Z *= len;
  95524. } else {
  95525. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95526. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95527. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95528. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95529. this.localAngAxis1X *= len;
  95530. this.localAngAxis1Y *= len;
  95531. this.localAngAxis1Z *= len;
  95532. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95533. var tarc = arc.elements;
  95534. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95535. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95536. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95537. }
  95538. this.nor = new OIMO.Vec3();
  95539. this.tan = new OIMO.Vec3();
  95540. this.bin = new OIMO.Vec3();
  95541. // The translational limit and motor information of the joint.
  95542. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95543. this.translationalLimitMotor.frequency = 8;
  95544. this.translationalLimitMotor.dampingRatio = 1;
  95545. // The first rotational limit and motor information of the joint.
  95546. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95547. // The second rotational limit and motor information of the joint.
  95548. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95549. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95550. this.t3.weight = 1;
  95551. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95552. };
  95553. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95554. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95555. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95556. var tmpM;
  95557. var tmp1X;
  95558. var tmp1Y;
  95559. var tmp1Z;
  95560. this.updateAnchorPoints();
  95561. tmpM = this.body1.rotation.elements;
  95562. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95563. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95564. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95565. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95566. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95567. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95568. tmpM = this.body2.rotation.elements;
  95569. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95570. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95571. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95572. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95573. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95574. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95575. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95576. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95577. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95578. } else {
  95579. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95580. }
  95581. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95582. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95583. } else {
  95584. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95585. }
  95586. var nx = y2 * z1 - z2 * y1;
  95587. var ny = z2 * x1 - x2 * z1;
  95588. var nz = x2 * y1 - y2 * x1;
  95589. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95590. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95591. nx *= tmp1X;
  95592. ny *= tmp1X;
  95593. nz *= tmp1X;
  95594. var tx = ny * z2 - nz * y2;
  95595. var ty = nz * x2 - nx * z2;
  95596. var tz = nx * y2 - ny * x2;
  95597. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95598. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95599. tx *= tmp1X;
  95600. ty *= tmp1X;
  95601. tz *= tmp1X;
  95602. var bx = y1 * nz - z1 * ny;
  95603. var by = z1 * nx - x1 * nz;
  95604. var bz = x1 * ny - y1 * nx;
  95605. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95606. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95607. bx *= tmp1X;
  95608. by *= tmp1X;
  95609. bz *= tmp1X;
  95610. this.nor.init(nx, ny, nz);
  95611. this.tan.init(tx, ty, tz);
  95612. this.bin.init(bx, by, bz);
  95613. this.r3.preSolve(timeStep, invTimeStep);
  95614. this.t3.preSolve(timeStep, invTimeStep);
  95615. };
  95616. OIMO.WheelJoint.prototype.solve = function () {
  95617. this.r3.solve();
  95618. this.t3.solve();
  95619. };
  95620. OIMO.WheelJoint.prototype.postSolve = function () {
  95621. };
  95622. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95623. if (cos > 1) return 0;
  95624. else if (cos < -1) return OIMO.PI;
  95625. else return OIMO.acos(cos);
  95626. };
  95627. /**
  95628. * An angular constraint for all axes for various joints.
  95629. * @author saharan
  95630. */
  95631. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95632. this.joint = joint;
  95633. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95634. this.relativeOrientation = new OIMO.Quat();
  95635. this.ii1 = null;
  95636. this.ii2 = null;
  95637. this.dd = null;
  95638. this.vel = new OIMO.Vec3();
  95639. this.imp = new OIMO.Vec3();
  95640. this.rn0 = new OIMO.Vec3();
  95641. this.rn1 = new OIMO.Vec3();
  95642. this.rn2 = new OIMO.Vec3();
  95643. this.b1 = joint.body1;
  95644. this.b2 = joint.body2;
  95645. this.a1 = this.b1.angularVelocity;
  95646. this.a2 = this.b2.angularVelocity;
  95647. this.i1 = this.b1.inverseInertia;
  95648. this.i2 = this.b2.inverseInertia;
  95649. };
  95650. OIMO.AngularConstraint.prototype = {
  95651. constructor: OIMO.AngularConstraint,
  95652. preSolve: function (timeStep, invTimeStep) {
  95653. var inv, len, v, vv;
  95654. this.ii1 = this.i1.clone();
  95655. this.ii2 = this.i2.clone();
  95656. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95657. 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]));
  95658. this.dd = new OIMO.Mat33(
  95659. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95660. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95661. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95662. ).multiply(inv);
  95663. this.relativeOrientation.invert(this.b1.orientation);
  95664. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95665. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95666. inv = this.relativeOrientation.s * 2;
  95667. this.vel.scale(this.relativeOrientation, inv);
  95668. len = this.vel.length();
  95669. if (len > 0.02) {
  95670. len = (0.02 - len) / len * invTimeStep * 0.05;
  95671. this.vel.scaleEqual(len);
  95672. } else {
  95673. this.vel.init();
  95674. }
  95675. this.rn1.mulMat(this.ii1, this.imp);
  95676. this.rn2.mulMat(this.ii2, this.imp);
  95677. this.a1.addEqual(this.rn1);
  95678. this.a2.subEqual(this.rn2);
  95679. },
  95680. solve: function () {
  95681. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95682. this.rn0.mulMat(this.dd, r);
  95683. this.rn1.mulMat(this.ii1, this.rn0);
  95684. this.rn2.mulMat(this.ii2, this.rn0);
  95685. this.imp.addEqual(this.rn0);
  95686. this.a1.addEqual(this.rn1);
  95687. this.a2.subEqual(this.rn2);
  95688. }
  95689. };
  95690. /**
  95691. * A linear constraint for all axes for various joints.
  95692. * @author saharan
  95693. */
  95694. OIMO.LinearConstraint = function (joint) {
  95695. this.m1 = NaN;
  95696. this.m2 = NaN;
  95697. this.ii1 = null;
  95698. this.ii2 = null;
  95699. this.dd = null;
  95700. this.r1x = NaN;
  95701. this.r1y = NaN;
  95702. this.r1z = NaN;
  95703. this.r2x = NaN;
  95704. this.r2y = NaN;
  95705. this.r2z = NaN;
  95706. this.ax1x = NaN;
  95707. this.ax1y = NaN;
  95708. this.ax1z = NaN;
  95709. this.ay1x = NaN;
  95710. this.ay1y = NaN;
  95711. this.ay1z = NaN;
  95712. this.az1x = NaN;
  95713. this.az1y = NaN;
  95714. this.az1z = NaN;
  95715. this.ax2x = NaN;
  95716. this.ax2y = NaN;
  95717. this.ax2z = NaN;
  95718. this.ay2x = NaN;
  95719. this.ay2y = NaN;
  95720. this.ay2z = NaN;
  95721. this.az2x = NaN;
  95722. this.az2y = NaN;
  95723. this.az2z = NaN;
  95724. this.vel = NaN;
  95725. this.velx = NaN;
  95726. this.vely = NaN;
  95727. this.velz = NaN;
  95728. this.joint = joint;
  95729. this.r1 = joint.relativeAnchorPoint1;
  95730. this.r2 = joint.relativeAnchorPoint2;
  95731. this.p1 = joint.anchorPoint1;
  95732. this.p2 = joint.anchorPoint2;
  95733. this.b1 = joint.body1;
  95734. this.b2 = joint.body2;
  95735. this.l1 = this.b1.linearVelocity;
  95736. this.l2 = this.b2.linearVelocity;
  95737. this.a1 = this.b1.angularVelocity;
  95738. this.a2 = this.b2.angularVelocity;
  95739. this.i1 = this.b1.inverseInertia;
  95740. this.i2 = this.b2.inverseInertia;
  95741. this.impx = 0;
  95742. this.impy = 0;
  95743. this.impz = 0;
  95744. }
  95745. OIMO.LinearConstraint.prototype = {
  95746. constructor: OIMO.LinearConstraint,
  95747. preSolve: function (timeStep, invTimeStep) {
  95748. this.r1x = this.r1.x;
  95749. this.r1y = this.r1.y;
  95750. this.r1z = this.r1.z;
  95751. this.r2x = this.r2.x;
  95752. this.r2y = this.r2.y;
  95753. this.r2z = this.r2.z;
  95754. this.m1 = this.b1.inverseMass;
  95755. this.m2 = this.b2.inverseMass;
  95756. this.ii1 = this.i1.clone();
  95757. this.ii2 = this.i2.clone();
  95758. var ii1 = this.ii1.elements;
  95759. var ii2 = this.ii2.elements;
  95760. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  95761. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  95762. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  95763. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  95764. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  95765. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  95766. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  95767. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  95768. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  95769. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  95770. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  95771. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  95772. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  95773. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  95774. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  95775. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  95776. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  95777. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  95778. // calculate point-to-point mass matrix
  95779. // from impulse equation
  95780. //
  95781. // M = ([/m] - [r^][/I][r^]) ^ -1
  95782. //
  95783. // where
  95784. //
  95785. // [/m] = |1/m, 0, 0|
  95786. // |0, 1/m, 0|
  95787. // |0, 0, 1/m|
  95788. //
  95789. // [r^] = |0, -rz, ry|
  95790. // |rz, 0, -rx|
  95791. // |-ry, rx, 0|
  95792. //
  95793. // [/I] = Inverted moment inertia
  95794. var rxx = this.m1 + this.m2;
  95795. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  95796. var k = kk.elements;
  95797. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  95798. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95799. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  95800. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95801. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  95802. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  95803. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  95804. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  95805. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  95806. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  95807. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95808. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  95809. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95810. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  95811. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  95812. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  95813. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  95814. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  95815. 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]));
  95816. this.dd = new OIMO.Mat33(
  95817. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  95818. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  95819. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  95820. ).multiply(inv);
  95821. this.velx = this.p2.x - this.p1.x;
  95822. this.vely = this.p2.y - this.p1.y;
  95823. this.velz = this.p2.z - this.p1.z;
  95824. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  95825. if (len > 0.005) {
  95826. len = (0.005 - len) / len * invTimeStep * 0.05;
  95827. this.velx *= len;
  95828. this.vely *= len;
  95829. this.velz *= len;
  95830. } else {
  95831. this.velx = 0;
  95832. this.vely = 0;
  95833. this.velz = 0;
  95834. }
  95835. this.impx *= 0.95;
  95836. this.impy *= 0.95;
  95837. this.impz *= 0.95;
  95838. this.l1.x += this.impx * this.m1;
  95839. this.l1.y += this.impy * this.m1;
  95840. this.l1.z += this.impz * this.m1;
  95841. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  95842. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  95843. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  95844. this.l2.x -= this.impx * this.m2;
  95845. this.l2.y -= this.impy * this.m2;
  95846. this.l2.z -= this.impz * this.m2;
  95847. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  95848. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  95849. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  95850. },
  95851. solve: function () {
  95852. var d = this.dd.elements;
  95853. 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;
  95854. 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;
  95855. 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;
  95856. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  95857. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  95858. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  95859. this.impx += nimpx;
  95860. this.impy += nimpy;
  95861. this.impz += nimpz;
  95862. this.l1.x += nimpx * this.m1;
  95863. this.l1.y += nimpy * this.m1;
  95864. this.l1.z += nimpz * this.m1;
  95865. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  95866. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  95867. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  95868. this.l2.x -= nimpx * this.m2;
  95869. this.l2.y -= nimpy * this.m2;
  95870. this.l2.z -= nimpz * this.m2;
  95871. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  95872. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  95873. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  95874. }
  95875. }
  95876. /**
  95877. * A three-axis rotational constraint for various joints.
  95878. * @author saharan
  95879. */
  95880. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95881. this.cfm1 = NaN;
  95882. this.cfm2 = NaN;
  95883. this.cfm3 = NaN;
  95884. this.i1e00 = NaN;
  95885. this.i1e01 = NaN;
  95886. this.i1e02 = NaN;
  95887. this.i1e10 = NaN;
  95888. this.i1e11 = NaN;
  95889. this.i1e12 = NaN;
  95890. this.i1e20 = NaN;
  95891. this.i1e21 = NaN;
  95892. this.i1e22 = NaN;
  95893. this.i2e00 = NaN;
  95894. this.i2e01 = NaN;
  95895. this.i2e02 = NaN;
  95896. this.i2e10 = NaN;
  95897. this.i2e11 = NaN;
  95898. this.i2e12 = NaN;
  95899. this.i2e20 = NaN;
  95900. this.i2e21 = NaN;
  95901. this.i2e22 = NaN;
  95902. this.ax1 = NaN;
  95903. this.ay1 = NaN;
  95904. this.az1 = NaN;
  95905. this.ax2 = NaN;
  95906. this.ay2 = NaN;
  95907. this.az2 = NaN;
  95908. this.ax3 = NaN;
  95909. this.ay3 = NaN;
  95910. this.az3 = NaN;
  95911. this.a1x1 = NaN; // jacoians
  95912. this.a1y1 = NaN;
  95913. this.a1z1 = NaN;
  95914. this.a2x1 = NaN;
  95915. this.a2y1 = NaN;
  95916. this.a2z1 = NaN;
  95917. this.a1x2 = NaN;
  95918. this.a1y2 = NaN;
  95919. this.a1z2 = NaN;
  95920. this.a2x2 = NaN;
  95921. this.a2y2 = NaN;
  95922. this.a2z2 = NaN;
  95923. this.a1x3 = NaN;
  95924. this.a1y3 = NaN;
  95925. this.a1z3 = NaN;
  95926. this.a2x3 = NaN;
  95927. this.a2y3 = NaN;
  95928. this.a2z3 = NaN;
  95929. this.lowerLimit1 = NaN;
  95930. this.upperLimit1 = NaN;
  95931. this.limitVelocity1 = NaN;
  95932. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95933. this.enableMotor1 = false;
  95934. this.motorSpeed1 = NaN;
  95935. this.maxMotorForce1 = NaN;
  95936. this.maxMotorImpulse1 = NaN;
  95937. this.lowerLimit2 = NaN;
  95938. this.upperLimit2 = NaN;
  95939. this.limitVelocity2 = NaN;
  95940. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95941. this.enableMotor2 = false;
  95942. this.motorSpeed2 = NaN;
  95943. this.maxMotorForce2 = NaN;
  95944. this.maxMotorImpulse2 = NaN;
  95945. this.lowerLimit3 = NaN;
  95946. this.upperLimit3 = NaN;
  95947. this.limitVelocity3 = NaN;
  95948. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95949. this.enableMotor3 = false;
  95950. this.motorSpeed3 = NaN;
  95951. this.maxMotorForce3 = NaN;
  95952. this.maxMotorImpulse3 = NaN;
  95953. this.k00 = NaN; // K = J*M*JT
  95954. this.k01 = NaN;
  95955. this.k02 = NaN;
  95956. this.k10 = NaN;
  95957. this.k11 = NaN;
  95958. this.k12 = NaN;
  95959. this.k20 = NaN;
  95960. this.k21 = NaN;
  95961. this.k22 = NaN;
  95962. this.kv00 = NaN; // diagonals without CFMs
  95963. this.kv11 = NaN;
  95964. this.kv22 = NaN;
  95965. this.dv00 = NaN; // ...inverted
  95966. this.dv11 = NaN;
  95967. this.dv22 = NaN;
  95968. this.d00 = NaN; // K^-1
  95969. this.d01 = NaN;
  95970. this.d02 = NaN;
  95971. this.d10 = NaN;
  95972. this.d11 = NaN;
  95973. this.d12 = NaN;
  95974. this.d20 = NaN;
  95975. this.d21 = NaN;
  95976. this.d22 = NaN;
  95977. this.limitMotor1 = limitMotor1;
  95978. this.limitMotor2 = limitMotor2;
  95979. this.limitMotor3 = limitMotor3;
  95980. this.b1 = joint.body1;
  95981. this.b2 = joint.body2;
  95982. this.a1 = this.b1.angularVelocity;
  95983. this.a2 = this.b2.angularVelocity;
  95984. this.i1 = this.b1.inverseInertia;
  95985. this.i2 = this.b2.inverseInertia;
  95986. this.limitImpulse1 = 0;
  95987. this.motorImpulse1 = 0;
  95988. this.limitImpulse2 = 0;
  95989. this.motorImpulse2 = 0;
  95990. this.limitImpulse3 = 0;
  95991. this.motorImpulse3 = 0;
  95992. }
  95993. OIMO.Rotational3Constraint.prototype = {
  95994. constructor: OIMO.Rotational3Constraint,
  95995. preSolve: function (timeStep, invTimeStep) {
  95996. this.ax1 = this.limitMotor1.axis.x;
  95997. this.ay1 = this.limitMotor1.axis.y;
  95998. this.az1 = this.limitMotor1.axis.z;
  95999. this.ax2 = this.limitMotor2.axis.x;
  96000. this.ay2 = this.limitMotor2.axis.y;
  96001. this.az2 = this.limitMotor2.axis.z;
  96002. this.ax3 = this.limitMotor3.axis.x;
  96003. this.ay3 = this.limitMotor3.axis.y;
  96004. this.az3 = this.limitMotor3.axis.z;
  96005. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96006. this.upperLimit1 = this.limitMotor1.upperLimit;
  96007. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96008. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96009. this.enableMotor1 = this.maxMotorForce1 > 0;
  96010. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96011. this.upperLimit2 = this.limitMotor2.upperLimit;
  96012. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96013. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96014. this.enableMotor2 = this.maxMotorForce2 > 0;
  96015. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96016. this.upperLimit3 = this.limitMotor3.upperLimit;
  96017. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96018. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96019. this.enableMotor3 = this.maxMotorForce3 > 0;
  96020. var ti1 = this.i1.elements;
  96021. var ti2 = this.i2.elements;
  96022. this.i1e00 = ti1[0];
  96023. this.i1e01 = ti1[1];
  96024. this.i1e02 = ti1[2];
  96025. this.i1e10 = ti1[3];
  96026. this.i1e11 = ti1[4];
  96027. this.i1e12 = ti1[5];
  96028. this.i1e20 = ti1[6];
  96029. this.i1e21 = ti1[7];
  96030. this.i1e22 = ti1[8];
  96031. this.i2e00 = ti2[0];
  96032. this.i2e01 = ti2[1];
  96033. this.i2e02 = ti2[2];
  96034. this.i2e10 = ti2[3];
  96035. this.i2e11 = ti2[4];
  96036. this.i2e12 = ti2[5];
  96037. this.i2e20 = ti2[6];
  96038. this.i2e21 = ti2[7];
  96039. this.i2e22 = ti2[8];
  96040. var frequency1 = this.limitMotor1.frequency;
  96041. var frequency2 = this.limitMotor2.frequency;
  96042. var frequency3 = this.limitMotor3.frequency;
  96043. var enableSpring1 = frequency1 > 0;
  96044. var enableSpring2 = frequency2 > 0;
  96045. var enableSpring3 = frequency3 > 0;
  96046. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96047. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96048. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96049. var angle1 = this.limitMotor1.angle;
  96050. if (enableLimit1) {
  96051. if (this.lowerLimit1 == this.upperLimit1) {
  96052. if (this.limitState1 != 0) {
  96053. this.limitState1 = 0;
  96054. this.limitImpulse1 = 0;
  96055. }
  96056. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96057. } else if (angle1 < this.lowerLimit1) {
  96058. if (this.limitState1 != -1) {
  96059. this.limitState1 = -1;
  96060. this.limitImpulse1 = 0;
  96061. }
  96062. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96063. } else if (angle1 > this.upperLimit1) {
  96064. if (this.limitState1 != 1) {
  96065. this.limitState1 = 1;
  96066. this.limitImpulse1 = 0;
  96067. }
  96068. this.limitVelocity1 = this.upperLimit1 - angle1;
  96069. } else {
  96070. this.limitState1 = 2;
  96071. this.limitImpulse1 = 0;
  96072. this.limitVelocity1 = 0;
  96073. }
  96074. if (!enableSpring1) {
  96075. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96076. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96077. else this.limitVelocity1 = 0;
  96078. }
  96079. } else {
  96080. this.limitState1 = 2;
  96081. this.limitImpulse1 = 0;
  96082. }
  96083. var angle2 = this.limitMotor2.angle;
  96084. if (enableLimit2) {
  96085. if (this.lowerLimit2 == this.upperLimit2) {
  96086. if (this.limitState2 != 0) {
  96087. this.limitState2 = 0;
  96088. this.limitImpulse2 = 0;
  96089. }
  96090. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96091. } else if (angle2 < this.lowerLimit2) {
  96092. if (this.limitState2 != -1) {
  96093. this.limitState2 = -1;
  96094. this.limitImpulse2 = 0;
  96095. }
  96096. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96097. } else if (angle2 > this.upperLimit2) {
  96098. if (this.limitState2 != 1) {
  96099. this.limitState2 = 1;
  96100. this.limitImpulse2 = 0;
  96101. }
  96102. this.limitVelocity2 = this.upperLimit2 - angle2;
  96103. } else {
  96104. this.limitState2 = 2;
  96105. this.limitImpulse2 = 0;
  96106. this.limitVelocity2 = 0;
  96107. }
  96108. if (!enableSpring2) {
  96109. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96110. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96111. else this.limitVelocity2 = 0;
  96112. }
  96113. } else {
  96114. this.limitState2 = 2;
  96115. this.limitImpulse2 = 0;
  96116. }
  96117. var angle3 = this.limitMotor3.angle;
  96118. if (enableLimit3) {
  96119. if (this.lowerLimit3 == this.upperLimit3) {
  96120. if (this.limitState3 != 0) {
  96121. this.limitState3 = 0;
  96122. this.limitImpulse3 = 0;
  96123. }
  96124. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96125. } else if (angle3 < this.lowerLimit3) {
  96126. if (this.limitState3 != -1) {
  96127. this.limitState3 = -1;
  96128. this.limitImpulse3 = 0;
  96129. }
  96130. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96131. } else if (angle3 > this.upperLimit3) {
  96132. if (this.limitState3 != 1) {
  96133. this.limitState3 = 1;
  96134. this.limitImpulse3 = 0;
  96135. }
  96136. this.limitVelocity3 = this.upperLimit3 - angle3;
  96137. } else {
  96138. this.limitState3 = 2;
  96139. this.limitImpulse3 = 0;
  96140. this.limitVelocity3 = 0;
  96141. }
  96142. if (!enableSpring3) {
  96143. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96144. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96145. else this.limitVelocity3 = 0;
  96146. }
  96147. } else {
  96148. this.limitState3 = 2;
  96149. this.limitImpulse3 = 0;
  96150. }
  96151. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96152. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96153. } else {
  96154. this.motorImpulse1 = 0;
  96155. this.maxMotorImpulse1 = 0;
  96156. }
  96157. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96158. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96159. } else {
  96160. this.motorImpulse2 = 0;
  96161. this.maxMotorImpulse2 = 0;
  96162. }
  96163. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96164. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96165. } else {
  96166. this.motorImpulse3 = 0;
  96167. this.maxMotorImpulse3 = 0;
  96168. }
  96169. // build jacobians
  96170. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96171. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96172. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96173. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96174. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96175. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96176. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96177. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96178. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96179. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96180. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96181. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96182. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96183. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96184. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96185. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96186. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96187. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96188. // build an impulse matrix
  96189. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96190. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96191. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96192. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96193. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96194. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96195. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96196. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96197. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96198. this.kv00 = this.k00;
  96199. this.kv11 = this.k11;
  96200. this.kv22 = this.k22;
  96201. this.dv00 = 1 / this.kv00;
  96202. this.dv11 = 1 / this.kv11;
  96203. this.dv22 = 1 / this.kv22;
  96204. if (enableSpring1 && this.limitState1 != 2) {
  96205. var omega = 6.2831853 * frequency1;
  96206. var k = omega * omega * timeStep;
  96207. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96208. this.cfm1 = this.kv00 * dmp;
  96209. this.limitVelocity1 *= k * dmp;
  96210. } else {
  96211. this.cfm1 = 0;
  96212. this.limitVelocity1 *= invTimeStep * 0.05;
  96213. }
  96214. if (enableSpring2 && this.limitState2 != 2) {
  96215. omega = 6.2831853 * frequency2;
  96216. k = omega * omega * timeStep;
  96217. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96218. this.cfm2 = this.kv11 * dmp;
  96219. this.limitVelocity2 *= k * dmp;
  96220. } else {
  96221. this.cfm2 = 0;
  96222. this.limitVelocity2 *= invTimeStep * 0.05;
  96223. }
  96224. if (enableSpring3 && this.limitState3 != 2) {
  96225. omega = 6.2831853 * frequency3;
  96226. k = omega * omega * timeStep;
  96227. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96228. this.cfm3 = this.kv22 * dmp;
  96229. this.limitVelocity3 *= k * dmp;
  96230. } else {
  96231. this.cfm3 = 0;
  96232. this.limitVelocity3 *= invTimeStep * 0.05;
  96233. }
  96234. this.k00 += this.cfm1;
  96235. this.k11 += this.cfm2;
  96236. this.k22 += this.cfm3;
  96237. var inv = 1 / (
  96238. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96239. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96240. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96241. );
  96242. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96243. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96244. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96245. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96246. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96247. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96248. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96249. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96250. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96251. this.limitImpulse1 *= 0.95;
  96252. this.motorImpulse1 *= 0.95;
  96253. this.limitImpulse2 *= 0.95;
  96254. this.motorImpulse2 *= 0.95;
  96255. this.limitImpulse3 *= 0.95;
  96256. this.motorImpulse3 *= 0.95;
  96257. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96258. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96259. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96260. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96261. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96262. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96263. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96264. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96265. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96266. },
  96267. solve_: function () {
  96268. var rvx = this.a2.x - this.a1.x;
  96269. var rvy = this.a2.y - this.a1.y;
  96270. var rvz = this.a2.z - this.a1.z;
  96271. this.limitVelocity3 = 30;
  96272. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96273. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96274. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96275. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96276. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96277. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96278. this.limitImpulse1 += dLimitImpulse1;
  96279. this.limitImpulse2 += dLimitImpulse2;
  96280. this.limitImpulse3 += dLimitImpulse3;
  96281. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96282. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96283. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96284. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96285. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96286. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96287. },
  96288. solve: function () {
  96289. var rvx = this.a2.x - this.a1.x;
  96290. var rvy = this.a2.y - this.a1.y;
  96291. var rvz = this.a2.z - this.a1.z;
  96292. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96293. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96294. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96295. var oldMotorImpulse1 = this.motorImpulse1;
  96296. var oldMotorImpulse2 = this.motorImpulse2;
  96297. var oldMotorImpulse3 = this.motorImpulse3;
  96298. var dMotorImpulse1 = 0;
  96299. var dMotorImpulse2 = 0;
  96300. var dMotorImpulse3 = 0;
  96301. if (this.enableMotor1) {
  96302. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96303. this.motorImpulse1 += dMotorImpulse1;
  96304. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96305. this.motorImpulse1 = this.maxMotorImpulse1;
  96306. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96307. this.motorImpulse1 = -this.maxMotorImpulse1;
  96308. }
  96309. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96310. }
  96311. if (this.enableMotor2) {
  96312. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96313. this.motorImpulse2 += dMotorImpulse2;
  96314. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96315. this.motorImpulse2 = this.maxMotorImpulse2;
  96316. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96317. this.motorImpulse2 = -this.maxMotorImpulse2;
  96318. }
  96319. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96320. }
  96321. if (this.enableMotor3) {
  96322. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96323. this.motorImpulse3 += dMotorImpulse3;
  96324. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96325. this.motorImpulse3 = this.maxMotorImpulse3;
  96326. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96327. this.motorImpulse3 = -this.maxMotorImpulse3;
  96328. }
  96329. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96330. }
  96331. // apply motor impulse to relative velocity
  96332. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96333. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96334. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96335. // subtract target velocity and applied impulse
  96336. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96337. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96338. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96339. var oldLimitImpulse1 = this.limitImpulse1;
  96340. var oldLimitImpulse2 = this.limitImpulse2;
  96341. var oldLimitImpulse3 = this.limitImpulse3;
  96342. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96343. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96344. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96345. this.limitImpulse1 += dLimitImpulse1;
  96346. this.limitImpulse2 += dLimitImpulse2;
  96347. this.limitImpulse3 += dLimitImpulse3;
  96348. // clamp
  96349. var clampState = 0;
  96350. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96351. dLimitImpulse1 = -oldLimitImpulse1;
  96352. rvn2 += dLimitImpulse1 * this.k10;
  96353. rvn3 += dLimitImpulse1 * this.k20;
  96354. clampState |= 1;
  96355. }
  96356. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96357. dLimitImpulse2 = -oldLimitImpulse2;
  96358. rvn1 += dLimitImpulse2 * this.k01;
  96359. rvn3 += dLimitImpulse2 * this.k21;
  96360. clampState |= 2;
  96361. }
  96362. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96363. dLimitImpulse3 = -oldLimitImpulse3;
  96364. rvn1 += dLimitImpulse3 * this.k02;
  96365. rvn2 += dLimitImpulse3 * this.k12;
  96366. clampState |= 4;
  96367. }
  96368. // update un-clamped impulse
  96369. // TODO: isolate division
  96370. var det;
  96371. switch (clampState) {
  96372. case 1: // update 2 3
  96373. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96374. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96375. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96376. break;
  96377. case 2: // update 1 3
  96378. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96379. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96380. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96381. break;
  96382. case 3: // update 3
  96383. dLimitImpulse3 = rvn3 / this.k22;
  96384. break;
  96385. case 4: // update 1 2
  96386. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96387. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96388. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96389. break;
  96390. case 5: // update 2
  96391. dLimitImpulse2 = rvn2 / this.k11;
  96392. break;
  96393. case 6: // update 1
  96394. dLimitImpulse1 = rvn1 / this.k00;
  96395. break;
  96396. }
  96397. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96398. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96399. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96400. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96401. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96402. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96403. // apply impulse
  96404. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96405. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96406. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96407. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96408. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96409. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96410. rvx = this.a2.x - this.a1.x;
  96411. rvy = this.a2.y - this.a1.y;
  96412. rvz = this.a2.z - this.a1.z;
  96413. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96414. }
  96415. }
  96416. /**
  96417. * A rotational constraint for various joints.
  96418. * @author saharan
  96419. */
  96420. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96421. this.cfm = NaN;
  96422. this.i1e00 = NaN;
  96423. this.i1e01 = NaN;
  96424. this.i1e02 = NaN;
  96425. this.i1e10 = NaN;
  96426. this.i1e11 = NaN;
  96427. this.i1e12 = NaN;
  96428. this.i1e20 = NaN;
  96429. this.i1e21 = NaN;
  96430. this.i1e22 = NaN;
  96431. this.i2e00 = NaN;
  96432. this.i2e01 = NaN;
  96433. this.i2e02 = NaN;
  96434. this.i2e10 = NaN;
  96435. this.i2e11 = NaN;
  96436. this.i2e12 = NaN;
  96437. this.i2e20 = NaN;
  96438. this.i2e21 = NaN;
  96439. this.i2e22 = NaN;
  96440. this.motorDenom = NaN;
  96441. this.invMotorDenom = NaN;
  96442. this.invDenom = NaN;
  96443. this.ax = NaN;
  96444. this.ay = NaN;
  96445. this.az = NaN;
  96446. this.a1x = NaN;
  96447. this.a1y = NaN;
  96448. this.a1z = NaN;
  96449. this.a2x = NaN;
  96450. this.a2y = NaN;
  96451. this.a2z = NaN;
  96452. this.enableLimit = false;
  96453. this.lowerLimit = NaN;
  96454. this.upperLimit = NaN;
  96455. this.limitVelocity = NaN;
  96456. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96457. this.enableMotor = false;
  96458. this.motorSpeed = NaN;
  96459. this.maxMotorForce = NaN;
  96460. this.maxMotorImpulse = NaN;
  96461. this.limitMotor = limitMotor;
  96462. this.b1 = joint.body1;
  96463. this.b2 = joint.body2;
  96464. this.a1 = this.b1.angularVelocity;
  96465. this.a2 = this.b2.angularVelocity;
  96466. this.i1 = this.b1.inverseInertia;
  96467. this.i2 = this.b2.inverseInertia;
  96468. this.limitImpulse = 0;
  96469. this.motorImpulse = 0;
  96470. }
  96471. OIMO.RotationalConstraint.prototype = {
  96472. constructor: OIMO.RotationalConstraint,
  96473. preSolve: function (timeStep, invTimeStep) {
  96474. this.ax = this.limitMotor.axis.x;
  96475. this.ay = this.limitMotor.axis.y;
  96476. this.az = this.limitMotor.axis.z;
  96477. this.lowerLimit = this.limitMotor.lowerLimit;
  96478. this.upperLimit = this.limitMotor.upperLimit;
  96479. this.motorSpeed = this.limitMotor.motorSpeed;
  96480. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96481. this.enableMotor = this.maxMotorForce > 0;
  96482. var ti1 = this.i1.elements;
  96483. var ti2 = this.i2.elements;
  96484. this.i1e00 = ti1[0];
  96485. this.i1e01 = ti1[1];
  96486. this.i1e02 = ti1[2];
  96487. this.i1e10 = ti1[3];
  96488. this.i1e11 = ti1[4];
  96489. this.i1e12 = ti1[5];
  96490. this.i1e20 = ti1[6];
  96491. this.i1e21 = ti1[7];
  96492. this.i1e22 = ti1[8];
  96493. this.i2e00 = ti2[0];
  96494. this.i2e01 = ti2[1];
  96495. this.i2e02 = ti2[2];
  96496. this.i2e10 = ti2[3];
  96497. this.i2e11 = ti2[4];
  96498. this.i2e12 = ti2[5];
  96499. this.i2e20 = ti2[6];
  96500. this.i2e21 = ti2[7];
  96501. this.i2e22 = ti2[8];
  96502. var frequency = this.limitMotor.frequency;
  96503. var enableSpring = frequency > 0;
  96504. var enableLimit = this.lowerLimit <= this.upperLimit;
  96505. var angle = this.limitMotor.angle;
  96506. if (enableLimit) {
  96507. if (this.lowerLimit == this.upperLimit) {
  96508. if (this.limitState != 0) {
  96509. this.limitState = 0;
  96510. this.limitImpulse = 0;
  96511. }
  96512. this.limitVelocity = this.lowerLimit - angle;
  96513. } else if (angle < this.lowerLimit) {
  96514. if (this.limitState != -1) {
  96515. this.limitState = -1;
  96516. this.limitImpulse = 0;
  96517. }
  96518. this.limitVelocity = this.lowerLimit - angle;
  96519. } else if (angle > this.upperLimit) {
  96520. if (this.limitState != 1) {
  96521. this.limitState = 1;
  96522. this.limitImpulse = 0;
  96523. }
  96524. this.limitVelocity = this.upperLimit - angle;
  96525. } else {
  96526. this.limitState = 2;
  96527. this.limitImpulse = 0;
  96528. this.limitVelocity = 0;
  96529. }
  96530. if (!enableSpring) {
  96531. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96532. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96533. else this.limitVelocity = 0;
  96534. }
  96535. } else {
  96536. this.limitState = 2;
  96537. this.limitImpulse = 0;
  96538. }
  96539. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96540. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96541. } else {
  96542. this.motorImpulse = 0;
  96543. this.maxMotorImpulse = 0;
  96544. }
  96545. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96546. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96547. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96548. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96549. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96550. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96551. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96552. this.invMotorDenom = 1 / this.motorDenom;
  96553. if (enableSpring && this.limitState != 2) {
  96554. var omega = 6.2831853 * frequency;
  96555. var k = omega * omega * timeStep;
  96556. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96557. this.cfm = this.motorDenom * dmp;
  96558. this.limitVelocity *= k * dmp;
  96559. } else {
  96560. this.cfm = 0;
  96561. this.limitVelocity *= invTimeStep * 0.05;
  96562. }
  96563. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96564. this.limitImpulse *= 0.95;
  96565. this.motorImpulse *= 0.95;
  96566. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96567. this.a1.x += totalImpulse * this.a1x;
  96568. this.a1.y += totalImpulse * this.a1y;
  96569. this.a1.z += totalImpulse * this.a1z;
  96570. this.a2.x -= totalImpulse * this.a2x;
  96571. this.a2.y -= totalImpulse * this.a2y;
  96572. this.a2.z -= totalImpulse * this.a2z;
  96573. },
  96574. solve: function () {
  96575. 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);
  96576. // motor part
  96577. var newMotorImpulse;
  96578. if (this.enableMotor) {
  96579. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96580. var oldMotorImpulse = this.motorImpulse;
  96581. this.motorImpulse += newMotorImpulse;
  96582. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96583. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96584. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96585. rvn -= newMotorImpulse * this.motorDenom;
  96586. } else newMotorImpulse = 0;
  96587. // limit part
  96588. var newLimitImpulse;
  96589. if (this.limitState != 2) {
  96590. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96591. var oldLimitImpulse = this.limitImpulse;
  96592. this.limitImpulse += newLimitImpulse;
  96593. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96594. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96595. } else newLimitImpulse = 0;
  96596. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96597. this.a1.x += totalImpulse * this.a1x;
  96598. this.a1.y += totalImpulse * this.a1y;
  96599. this.a1.z += totalImpulse * this.a1z;
  96600. this.a2.x -= totalImpulse * this.a2x;
  96601. this.a2.y -= totalImpulse * this.a2y;
  96602. this.a2.z -= totalImpulse * this.a2z;
  96603. }
  96604. }
  96605. /**
  96606. * A three-axis translational constraint for various joints.
  96607. * @author saharan
  96608. */
  96609. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96610. this.m1 = NaN;
  96611. this.m2 = NaN;
  96612. this.i1e00 = NaN;
  96613. this.i1e01 = NaN;
  96614. this.i1e02 = NaN;
  96615. this.i1e10 = NaN;
  96616. this.i1e11 = NaN;
  96617. this.i1e12 = NaN;
  96618. this.i1e20 = NaN;
  96619. this.i1e21 = NaN;
  96620. this.i1e22 = NaN;
  96621. this.i2e00 = NaN;
  96622. this.i2e01 = NaN;
  96623. this.i2e02 = NaN;
  96624. this.i2e10 = NaN;
  96625. this.i2e11 = NaN;
  96626. this.i2e12 = NaN;
  96627. this.i2e20 = NaN;
  96628. this.i2e21 = NaN;
  96629. this.i2e22 = NaN;
  96630. this.ax1 = NaN;
  96631. this.ay1 = NaN;
  96632. this.az1 = NaN;
  96633. this.ax2 = NaN;
  96634. this.ay2 = NaN;
  96635. this.az2 = NaN;
  96636. this.ax3 = NaN;
  96637. this.ay3 = NaN;
  96638. this.az3 = NaN;
  96639. this.r1x = NaN;
  96640. this.r1y = NaN;
  96641. this.r1z = NaN;
  96642. this.r2x = NaN;
  96643. this.r2y = NaN;
  96644. this.r2z = NaN;
  96645. this.t1x1 = NaN;// jacobians
  96646. this.t1y1 = NaN;
  96647. this.t1z1 = NaN;
  96648. this.t2x1 = NaN;
  96649. this.t2y1 = NaN;
  96650. this.t2z1 = NaN;
  96651. this.l1x1 = NaN;
  96652. this.l1y1 = NaN;
  96653. this.l1z1 = NaN;
  96654. this.l2x1 = NaN;
  96655. this.l2y1 = NaN;
  96656. this.l2z1 = NaN;
  96657. this.a1x1 = NaN;
  96658. this.a1y1 = NaN;
  96659. this.a1z1 = NaN;
  96660. this.a2x1 = NaN;
  96661. this.a2y1 = NaN;
  96662. this.a2z1 = NaN;
  96663. this.t1x2 = NaN;
  96664. this.t1y2 = NaN;
  96665. this.t1z2 = NaN;
  96666. this.t2x2 = NaN;
  96667. this.t2y2 = NaN;
  96668. this.t2z2 = NaN;
  96669. this.l1x2 = NaN;
  96670. this.l1y2 = NaN;
  96671. this.l1z2 = NaN;
  96672. this.l2x2 = NaN;
  96673. this.l2y2 = NaN;
  96674. this.l2z2 = NaN;
  96675. this.a1x2 = NaN;
  96676. this.a1y2 = NaN;
  96677. this.a1z2 = NaN;
  96678. this.a2x2 = NaN;
  96679. this.a2y2 = NaN;
  96680. this.a2z2 = NaN;
  96681. this.t1x3 = NaN;
  96682. this.t1y3 = NaN;
  96683. this.t1z3 = NaN;
  96684. this.t2x3 = NaN;
  96685. this.t2y3 = NaN;
  96686. this.t2z3 = NaN;
  96687. this.l1x3 = NaN;
  96688. this.l1y3 = NaN;
  96689. this.l1z3 = NaN;
  96690. this.l2x3 = NaN;
  96691. this.l2y3 = NaN;
  96692. this.l2z3 = NaN;
  96693. this.a1x3 = NaN;
  96694. this.a1y3 = NaN;
  96695. this.a1z3 = NaN;
  96696. this.a2x3 = NaN;
  96697. this.a2y3 = NaN;
  96698. this.a2z3 = NaN;
  96699. this.lowerLimit1 = NaN;
  96700. this.upperLimit1 = NaN;
  96701. this.limitVelocity1 = NaN;
  96702. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96703. this.enableMotor1 = false;
  96704. this.motorSpeed1 = NaN;
  96705. this.maxMotorForce1 = NaN;
  96706. this.maxMotorImpulse1 = NaN;
  96707. this.lowerLimit2 = NaN;
  96708. this.upperLimit2 = NaN;
  96709. this.limitVelocity2 = NaN;
  96710. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96711. this.enableMotor2 = false;
  96712. this.motorSpeed2 = NaN;
  96713. this.maxMotorForce2 = NaN;
  96714. this.maxMotorImpulse2 = NaN;
  96715. this.lowerLimit3 = NaN;
  96716. this.upperLimit3 = NaN;
  96717. this.limitVelocity3 = NaN;
  96718. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96719. this.enableMotor3 = false;
  96720. this.motorSpeed3 = NaN;
  96721. this.maxMotorForce3 = NaN;
  96722. this.maxMotorImpulse3 = NaN;
  96723. this.k00 = NaN; // K = J*M*JT
  96724. this.k01 = NaN;
  96725. this.k02 = NaN;
  96726. this.k10 = NaN;
  96727. this.k11 = NaN;
  96728. this.k12 = NaN;
  96729. this.k20 = NaN;
  96730. this.k21 = NaN;
  96731. this.k22 = NaN;
  96732. this.kv00 = NaN; // diagonals without CFMs
  96733. this.kv11 = NaN;
  96734. this.kv22 = NaN;
  96735. this.dv00 = NaN; // ...inverted
  96736. this.dv11 = NaN;
  96737. this.dv22 = NaN;
  96738. this.d00 = NaN; // K^-1
  96739. this.d01 = NaN;
  96740. this.d02 = NaN;
  96741. this.d10 = NaN;
  96742. this.d11 = NaN;
  96743. this.d12 = NaN;
  96744. this.d20 = NaN;
  96745. this.d21 = NaN;
  96746. this.d22 = NaN;
  96747. this.limitMotor1 = limitMotor1;
  96748. this.limitMotor2 = limitMotor2;
  96749. this.limitMotor3 = limitMotor3;
  96750. this.b1 = joint.body1;
  96751. this.b2 = joint.body2;
  96752. this.p1 = joint.anchorPoint1;
  96753. this.p2 = joint.anchorPoint2;
  96754. this.r1 = joint.relativeAnchorPoint1;
  96755. this.r2 = joint.relativeAnchorPoint2;
  96756. this.l1 = this.b1.linearVelocity;
  96757. this.l2 = this.b2.linearVelocity;
  96758. this.a1 = this.b1.angularVelocity;
  96759. this.a2 = this.b2.angularVelocity;
  96760. this.i1 = this.b1.inverseInertia;
  96761. this.i2 = this.b2.inverseInertia;
  96762. this.limitImpulse1 = 0;
  96763. this.motorImpulse1 = 0;
  96764. this.limitImpulse2 = 0;
  96765. this.motorImpulse2 = 0;
  96766. this.limitImpulse3 = 0;
  96767. this.motorImpulse3 = 0;
  96768. this.cfm1 = 0;// Constraint Force Mixing
  96769. this.cfm2 = 0;
  96770. this.cfm3 = 0;
  96771. this.weight = -1;
  96772. }
  96773. OIMO.Translational3Constraint.prototype = {
  96774. constructor: OIMO.Translational3Constraint,
  96775. preSolve: function (timeStep, invTimeStep) {
  96776. this.ax1 = this.limitMotor1.axis.x;
  96777. this.ay1 = this.limitMotor1.axis.y;
  96778. this.az1 = this.limitMotor1.axis.z;
  96779. this.ax2 = this.limitMotor2.axis.x;
  96780. this.ay2 = this.limitMotor2.axis.y;
  96781. this.az2 = this.limitMotor2.axis.z;
  96782. this.ax3 = this.limitMotor3.axis.x;
  96783. this.ay3 = this.limitMotor3.axis.y;
  96784. this.az3 = this.limitMotor3.axis.z;
  96785. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96786. this.upperLimit1 = this.limitMotor1.upperLimit;
  96787. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96788. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96789. this.enableMotor1 = this.maxMotorForce1 > 0;
  96790. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96791. this.upperLimit2 = this.limitMotor2.upperLimit;
  96792. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96793. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96794. this.enableMotor2 = this.maxMotorForce2 > 0;
  96795. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96796. this.upperLimit3 = this.limitMotor3.upperLimit;
  96797. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96798. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96799. this.enableMotor3 = this.maxMotorForce3 > 0;
  96800. this.m1 = this.b1.inverseMass;
  96801. this.m2 = this.b2.inverseMass;
  96802. var ti1 = this.i1.elements;
  96803. var ti2 = this.i2.elements;
  96804. this.i1e00 = ti1[0];
  96805. this.i1e01 = ti1[1];
  96806. this.i1e02 = ti1[2];
  96807. this.i1e10 = ti1[3];
  96808. this.i1e11 = ti1[4];
  96809. this.i1e12 = ti1[5];
  96810. this.i1e20 = ti1[6];
  96811. this.i1e21 = ti1[7];
  96812. this.i1e22 = ti1[8];
  96813. this.i2e00 = ti2[0];
  96814. this.i2e01 = ti2[1];
  96815. this.i2e02 = ti2[2];
  96816. this.i2e10 = ti2[3];
  96817. this.i2e11 = ti2[4];
  96818. this.i2e12 = ti2[5];
  96819. this.i2e20 = ti2[6];
  96820. this.i2e21 = ti2[7];
  96821. this.i2e22 = ti2[8];
  96822. var dx = this.p2.x - this.p1.x;
  96823. var dy = this.p2.y - this.p1.y;
  96824. var dz = this.p2.z - this.p1.z;
  96825. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  96826. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  96827. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  96828. var frequency1 = this.limitMotor1.frequency;
  96829. var frequency2 = this.limitMotor2.frequency;
  96830. var frequency3 = this.limitMotor3.frequency;
  96831. var enableSpring1 = frequency1 > 0;
  96832. var enableSpring2 = frequency2 > 0;
  96833. var enableSpring3 = frequency3 > 0;
  96834. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96835. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96836. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96837. // for stability
  96838. if (enableSpring1 && d1 > 20 || d1 < -20) {
  96839. enableSpring1 = false;
  96840. }
  96841. if (enableSpring2 && d2 > 20 || d2 < -20) {
  96842. enableSpring2 = false;
  96843. }
  96844. if (enableSpring3 && d3 > 20 || d3 < -20) {
  96845. enableSpring3 = false;
  96846. }
  96847. if (enableLimit1) {
  96848. if (this.lowerLimit1 == this.upperLimit1) {
  96849. if (this.limitState1 != 0) {
  96850. this.limitState1 = 0;
  96851. this.limitImpulse1 = 0;
  96852. }
  96853. this.limitVelocity1 = this.lowerLimit1 - d1;
  96854. if (!enableSpring1) d1 = this.lowerLimit1;
  96855. } else if (d1 < this.lowerLimit1) {
  96856. if (this.limitState1 != -1) {
  96857. this.limitState1 = -1;
  96858. this.limitImpulse1 = 0;
  96859. }
  96860. this.limitVelocity1 = this.lowerLimit1 - d1;
  96861. if (!enableSpring1) d1 = this.lowerLimit1;
  96862. } else if (d1 > this.upperLimit1) {
  96863. if (this.limitState1 != 1) {
  96864. this.limitState1 = 1;
  96865. this.limitImpulse1 = 0;
  96866. }
  96867. this.limitVelocity1 = this.upperLimit1 - d1;
  96868. if (!enableSpring1) d1 = this.upperLimit1;
  96869. } else {
  96870. this.limitState1 = 2;
  96871. this.limitImpulse1 = 0;
  96872. this.limitVelocity1 = 0;
  96873. }
  96874. if (!enableSpring1) {
  96875. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  96876. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  96877. else this.limitVelocity1 = 0;
  96878. }
  96879. } else {
  96880. this.limitState1 = 2;
  96881. this.limitImpulse1 = 0;
  96882. }
  96883. if (enableLimit2) {
  96884. if (this.lowerLimit2 == this.upperLimit2) {
  96885. if (this.limitState2 != 0) {
  96886. this.limitState2 = 0;
  96887. this.limitImpulse2 = 0;
  96888. }
  96889. this.limitVelocity2 = this.lowerLimit2 - d2;
  96890. if (!enableSpring2) d2 = this.lowerLimit2;
  96891. } else if (d2 < this.lowerLimit2) {
  96892. if (this.limitState2 != -1) {
  96893. this.limitState2 = -1;
  96894. this.limitImpulse2 = 0;
  96895. }
  96896. this.limitVelocity2 = this.lowerLimit2 - d2;
  96897. if (!enableSpring2) d2 = this.lowerLimit2;
  96898. } else if (d2 > this.upperLimit2) {
  96899. if (this.limitState2 != 1) {
  96900. this.limitState2 = 1;
  96901. this.limitImpulse2 = 0;
  96902. }
  96903. this.limitVelocity2 = this.upperLimit2 - d2;
  96904. if (!enableSpring2) d2 = this.upperLimit2;
  96905. } else {
  96906. this.limitState2 = 2;
  96907. this.limitImpulse2 = 0;
  96908. this.limitVelocity2 = 0;
  96909. }
  96910. if (!enableSpring2) {
  96911. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  96912. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  96913. else this.limitVelocity2 = 0;
  96914. }
  96915. } else {
  96916. this.limitState2 = 2;
  96917. this.limitImpulse2 = 0;
  96918. }
  96919. if (enableLimit3) {
  96920. if (this.lowerLimit3 == this.upperLimit3) {
  96921. if (this.limitState3 != 0) {
  96922. this.limitState3 = 0;
  96923. this.limitImpulse3 = 0;
  96924. }
  96925. this.limitVelocity3 = this.lowerLimit3 - d3;
  96926. if (!enableSpring3) d3 = this.lowerLimit3;
  96927. } else if (d3 < this.lowerLimit3) {
  96928. if (this.limitState3 != -1) {
  96929. this.limitState3 = -1;
  96930. this.limitImpulse3 = 0;
  96931. }
  96932. this.limitVelocity3 = this.lowerLimit3 - d3;
  96933. if (!enableSpring3) d3 = this.lowerLimit3;
  96934. } else if (d3 > this.upperLimit3) {
  96935. if (this.limitState3 != 1) {
  96936. this.limitState3 = 1;
  96937. this.limitImpulse3 = 0;
  96938. }
  96939. this.limitVelocity3 = this.upperLimit3 - d3;
  96940. if (!enableSpring3) d3 = this.upperLimit3;
  96941. } else {
  96942. this.limitState3 = 2;
  96943. this.limitImpulse3 = 0;
  96944. this.limitVelocity3 = 0;
  96945. }
  96946. if (!enableSpring3) {
  96947. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  96948. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  96949. else this.limitVelocity3 = 0;
  96950. }
  96951. } else {
  96952. this.limitState3 = 2;
  96953. this.limitImpulse3 = 0;
  96954. }
  96955. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96956. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96957. } else {
  96958. this.motorImpulse1 = 0;
  96959. this.maxMotorImpulse1 = 0;
  96960. }
  96961. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96962. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96963. } else {
  96964. this.motorImpulse2 = 0;
  96965. this.maxMotorImpulse2 = 0;
  96966. }
  96967. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96968. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96969. } else {
  96970. this.motorImpulse3 = 0;
  96971. this.maxMotorImpulse3 = 0;
  96972. }
  96973. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  96974. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  96975. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  96976. var w1 = this.m2 / (this.m1 + this.m2);
  96977. if (this.weight >= 0) w1 = this.weight; // use given weight
  96978. var w2 = 1 - w1;
  96979. this.r1x = this.r1.x + rdx * w1;
  96980. this.r1y = this.r1.y + rdy * w1;
  96981. this.r1z = this.r1.z + rdz * w1;
  96982. this.r2x = this.r2.x - rdx * w2;
  96983. this.r2y = this.r2.y - rdy * w2;
  96984. this.r2z = this.r2.z - rdz * w2;
  96985. // build jacobians
  96986. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  96987. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  96988. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  96989. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  96990. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  96991. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  96992. this.l1x1 = this.ax1 * this.m1;
  96993. this.l1y1 = this.ay1 * this.m1;
  96994. this.l1z1 = this.az1 * this.m1;
  96995. this.l2x1 = this.ax1 * this.m2;
  96996. this.l2y1 = this.ay1 * this.m2;
  96997. this.l2z1 = this.az1 * this.m2;
  96998. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  96999. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97000. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97001. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97002. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97003. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97004. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97005. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97006. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97007. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97008. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97009. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97010. this.l1x2 = this.ax2 * this.m1;
  97011. this.l1y2 = this.ay2 * this.m1;
  97012. this.l1z2 = this.az2 * this.m1;
  97013. this.l2x2 = this.ax2 * this.m2;
  97014. this.l2y2 = this.ay2 * this.m2;
  97015. this.l2z2 = this.az2 * this.m2;
  97016. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97017. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97018. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97019. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97020. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97021. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97022. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97023. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97024. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97025. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97026. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97027. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97028. this.l1x3 = this.ax3 * this.m1;
  97029. this.l1y3 = this.ay3 * this.m1;
  97030. this.l1z3 = this.az3 * this.m1;
  97031. this.l2x3 = this.ax3 * this.m2;
  97032. this.l2y3 = this.ay3 * this.m2;
  97033. this.l2z3 = this.az3 * this.m2;
  97034. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97035. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97036. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97037. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97038. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97039. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97040. // build an impulse matrix
  97041. var m12 = this.m1 + this.m2;
  97042. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97043. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97044. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97045. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97046. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97047. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97048. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97049. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97050. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97051. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97052. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97053. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97054. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97055. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97056. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97057. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97058. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97059. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97060. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97061. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97062. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97063. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97064. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97065. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97066. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97067. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97068. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97069. this.kv00 = this.k00;
  97070. this.kv11 = this.k11;
  97071. this.kv22 = this.k22;
  97072. this.dv00 = 1 / this.kv00;
  97073. this.dv11 = 1 / this.kv11;
  97074. this.dv22 = 1 / this.kv22;
  97075. if (enableSpring1 && this.limitState1 != 2) {
  97076. var omega = 6.2831853 * frequency1;
  97077. var k = omega * omega * timeStep;
  97078. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97079. this.cfm1 = this.kv00 * dmp;
  97080. this.limitVelocity1 *= k * dmp;
  97081. } else {
  97082. this.cfm1 = 0;
  97083. this.limitVelocity1 *= invTimeStep * 0.05;
  97084. }
  97085. if (enableSpring2 && this.limitState2 != 2) {
  97086. omega = 6.2831853 * frequency2;
  97087. k = omega * omega * timeStep;
  97088. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97089. this.cfm2 = this.kv11 * dmp;
  97090. this.limitVelocity2 *= k * dmp;
  97091. } else {
  97092. this.cfm2 = 0;
  97093. this.limitVelocity2 *= invTimeStep * 0.05;
  97094. }
  97095. if (enableSpring3 && this.limitState3 != 2) {
  97096. omega = 6.2831853 * frequency3;
  97097. k = omega * omega * timeStep;
  97098. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97099. this.cfm3 = this.kv22 * dmp;
  97100. this.limitVelocity3 *= k * dmp;
  97101. } else {
  97102. this.cfm3 = 0;
  97103. this.limitVelocity3 *= invTimeStep * 0.05;
  97104. }
  97105. this.k00 += this.cfm1;
  97106. this.k11 += this.cfm2;
  97107. this.k22 += this.cfm3;
  97108. var inv = 1 / (
  97109. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97110. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97111. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97112. );
  97113. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97114. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97115. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97116. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97117. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97118. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97119. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97120. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97121. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97122. // warm starting
  97123. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97124. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97125. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97126. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97127. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97128. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97129. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97130. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97131. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97132. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97133. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97134. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97135. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97136. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97137. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97138. },
  97139. solve: function () {
  97140. 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;
  97141. 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;
  97142. 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;
  97143. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97144. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97145. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97146. var oldMotorImpulse1 = this.motorImpulse1;
  97147. var oldMotorImpulse2 = this.motorImpulse2;
  97148. var oldMotorImpulse3 = this.motorImpulse3;
  97149. var dMotorImpulse1 = 0;
  97150. var dMotorImpulse2 = 0;
  97151. var dMotorImpulse3 = 0;
  97152. if (this.enableMotor1) {
  97153. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97154. this.motorImpulse1 += dMotorImpulse1;
  97155. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97156. this.motorImpulse1 = this.maxMotorImpulse1;
  97157. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97158. this.motorImpulse1 = -this.maxMotorImpulse1;
  97159. }
  97160. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97161. }
  97162. if (this.enableMotor2) {
  97163. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97164. this.motorImpulse2 += dMotorImpulse2;
  97165. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97166. this.motorImpulse2 = this.maxMotorImpulse2;
  97167. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97168. this.motorImpulse2 = -this.maxMotorImpulse2;
  97169. }
  97170. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97171. }
  97172. if (this.enableMotor3) {
  97173. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97174. this.motorImpulse3 += dMotorImpulse3;
  97175. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97176. this.motorImpulse3 = this.maxMotorImpulse3;
  97177. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97178. this.motorImpulse3 = -this.maxMotorImpulse3;
  97179. }
  97180. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97181. }
  97182. // apply motor impulse to relative velocity
  97183. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97184. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97185. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97186. // subtract target velocity and applied impulse
  97187. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97188. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97189. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97190. var oldLimitImpulse1 = this.limitImpulse1;
  97191. var oldLimitImpulse2 = this.limitImpulse2;
  97192. var oldLimitImpulse3 = this.limitImpulse3;
  97193. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97194. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97195. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97196. this.limitImpulse1 += dLimitImpulse1;
  97197. this.limitImpulse2 += dLimitImpulse2;
  97198. this.limitImpulse3 += dLimitImpulse3;
  97199. // clamp
  97200. var clampState = 0;
  97201. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97202. dLimitImpulse1 = -oldLimitImpulse1;
  97203. rvn2 += dLimitImpulse1 * this.k10;
  97204. rvn3 += dLimitImpulse1 * this.k20;
  97205. clampState |= 1;
  97206. }
  97207. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97208. dLimitImpulse2 = -oldLimitImpulse2;
  97209. rvn1 += dLimitImpulse2 * this.k01;
  97210. rvn3 += dLimitImpulse2 * this.k21;
  97211. clampState |= 2;
  97212. }
  97213. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97214. dLimitImpulse3 = -oldLimitImpulse3;
  97215. rvn1 += dLimitImpulse3 * this.k02;
  97216. rvn2 += dLimitImpulse3 * this.k12;
  97217. clampState |= 4;
  97218. }
  97219. // update un-clamped impulse
  97220. // TODO: isolate division
  97221. var det;
  97222. switch (clampState) {
  97223. case 1:// update 2 3
  97224. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97225. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97226. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97227. break;
  97228. case 2:// update 1 3
  97229. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97230. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97231. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97232. break;
  97233. case 3:// update 3
  97234. dLimitImpulse3 = rvn3 / this.k22;
  97235. break;
  97236. case 4:// update 1 2
  97237. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97238. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97239. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97240. break;
  97241. case 5:// update 2
  97242. dLimitImpulse2 = rvn2 / this.k11;
  97243. break;
  97244. case 6:// update 1
  97245. dLimitImpulse1 = rvn1 / this.k00;
  97246. break;
  97247. }
  97248. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97249. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97250. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97251. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97252. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97253. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97254. // apply impulse
  97255. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97256. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97257. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97258. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97259. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97260. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97261. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97262. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97263. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97264. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97265. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97266. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97267. }
  97268. }
  97269. /**
  97270. * A translational constraint for various joints.
  97271. * @author saharan
  97272. */
  97273. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97274. this.cfm = NaN;
  97275. this.m1 = NaN;
  97276. this.m2 = NaN;
  97277. this.i1e00 = NaN;
  97278. this.i1e01 = NaN;
  97279. this.i1e02 = NaN;
  97280. this.i1e10 = NaN;
  97281. this.i1e11 = NaN;
  97282. this.i1e12 = NaN;
  97283. this.i1e20 = NaN;
  97284. this.i1e21 = NaN;
  97285. this.i1e22 = NaN;
  97286. this.i2e00 = NaN;
  97287. this.i2e01 = NaN;
  97288. this.i2e02 = NaN;
  97289. this.i2e10 = NaN;
  97290. this.i2e11 = NaN;
  97291. this.i2e12 = NaN;
  97292. this.i2e20 = NaN;
  97293. this.i2e21 = NaN;
  97294. this.i2e22 = NaN;
  97295. this.motorDenom = NaN;
  97296. this.invMotorDenom = NaN;
  97297. this.invDenom = NaN;
  97298. this.ax = NaN;
  97299. this.ay = NaN;
  97300. this.az = NaN;
  97301. this.r1x = NaN;
  97302. this.r1y = NaN;
  97303. this.r1z = NaN;
  97304. this.r2x = NaN;
  97305. this.r2y = NaN;
  97306. this.r2z = NaN;
  97307. this.t1x = NaN;
  97308. this.t1y = NaN;
  97309. this.t1z = NaN;
  97310. this.t2x = NaN;
  97311. this.t2y = NaN;
  97312. this.t2z = NaN;
  97313. this.l1x = NaN;
  97314. this.l1y = NaN;
  97315. this.l1z = NaN;
  97316. this.l2x = NaN;
  97317. this.l2y = NaN;
  97318. this.l2z = NaN;
  97319. this.a1x = NaN;
  97320. this.a1y = NaN;
  97321. this.a1z = NaN;
  97322. this.a2x = NaN;
  97323. this.a2y = NaN;
  97324. this.a2z = NaN;
  97325. this.lowerLimit = NaN;
  97326. this.upperLimit = NaN;
  97327. this.limitVelocity = NaN;
  97328. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97329. this.enableMotor = false;
  97330. this.motorSpeed = NaN;
  97331. this.maxMotorForce = NaN;
  97332. this.maxMotorImpulse = NaN;
  97333. this.limitMotor = limitMotor;
  97334. this.b1 = joint.body1;
  97335. this.b2 = joint.body2;
  97336. this.p1 = joint.anchorPoint1;
  97337. this.p2 = joint.anchorPoint2;
  97338. this.r1 = joint.relativeAnchorPoint1;
  97339. this.r2 = joint.relativeAnchorPoint2;
  97340. this.l1 = this.b1.linearVelocity;
  97341. this.l2 = this.b2.linearVelocity;
  97342. this.a1 = this.b1.angularVelocity;
  97343. this.a2 = this.b2.angularVelocity;
  97344. this.i1 = this.b1.inverseInertia;
  97345. this.i2 = this.b2.inverseInertia;
  97346. this.limitImpulse = 0;
  97347. this.motorImpulse = 0;
  97348. }
  97349. OIMO.TranslationalConstraint.prototype = {
  97350. constructor: OIMO.TranslationalConstraint,
  97351. preSolve: function (timeStep, invTimeStep) {
  97352. this.ax = this.limitMotor.axis.x;
  97353. this.ay = this.limitMotor.axis.y;
  97354. this.az = this.limitMotor.axis.z;
  97355. this.lowerLimit = this.limitMotor.lowerLimit;
  97356. this.upperLimit = this.limitMotor.upperLimit;
  97357. this.motorSpeed = this.limitMotor.motorSpeed;
  97358. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97359. this.enableMotor = this.maxMotorForce > 0;
  97360. this.m1 = this.b1.inverseMass;
  97361. this.m2 = this.b2.inverseMass;
  97362. var ti1 = this.i1.elements;
  97363. var ti2 = this.i2.elements;
  97364. this.i1e00 = ti1[0];
  97365. this.i1e01 = ti1[1];
  97366. this.i1e02 = ti1[2];
  97367. this.i1e10 = ti1[3];
  97368. this.i1e11 = ti1[4];
  97369. this.i1e12 = ti1[5];
  97370. this.i1e20 = ti1[6];
  97371. this.i1e21 = ti1[7];
  97372. this.i1e22 = ti1[8];
  97373. this.i2e00 = ti2[0];
  97374. this.i2e01 = ti2[1];
  97375. this.i2e02 = ti2[2];
  97376. this.i2e10 = ti2[3];
  97377. this.i2e11 = ti2[4];
  97378. this.i2e12 = ti2[5];
  97379. this.i2e20 = ti2[6];
  97380. this.i2e21 = ti2[7];
  97381. this.i2e22 = ti2[8];
  97382. var dx = this.p2.x - this.p1.x;
  97383. var dy = this.p2.y - this.p1.y;
  97384. var dz = this.p2.z - this.p1.z;
  97385. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97386. var frequency = this.limitMotor.frequency;
  97387. var enableSpring = frequency > 0;
  97388. var enableLimit = this.lowerLimit <= this.upperLimit;
  97389. if (enableSpring && d > 20 || d < -20) {
  97390. enableSpring = false;
  97391. }
  97392. if (enableLimit) {
  97393. if (this.lowerLimit == this.upperLimit) {
  97394. if (this.limitState != 0) {
  97395. this.limitState = 0;
  97396. this.limitImpulse = 0;
  97397. }
  97398. this.limitVelocity = this.lowerLimit - d;
  97399. if (!enableSpring) d = this.lowerLimit;
  97400. } else if (d < this.lowerLimit) {
  97401. if (this.limitState != -1) {
  97402. this.limitState = -1;
  97403. this.limitImpulse = 0;
  97404. }
  97405. this.limitVelocity = this.lowerLimit - d;
  97406. if (!enableSpring) d = this.lowerLimit;
  97407. } else if (d > this.upperLimit) {
  97408. if (this.limitState != 1) {
  97409. this.limitState = 1;
  97410. this.limitImpulse = 0;
  97411. }
  97412. this.limitVelocity = this.upperLimit - d;
  97413. if (!enableSpring) d = this.upperLimit;
  97414. } else {
  97415. this.limitState = 2;
  97416. this.limitImpulse = 0;
  97417. this.limitVelocity = 0;
  97418. }
  97419. if (!enableSpring) {
  97420. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97421. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97422. else this.limitVelocity = 0;
  97423. }
  97424. } else {
  97425. this.limitState = 2;
  97426. this.limitImpulse = 0;
  97427. }
  97428. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97429. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97430. } else {
  97431. this.motorImpulse = 0;
  97432. this.maxMotorImpulse = 0;
  97433. }
  97434. var rdx = d * this.ax;
  97435. var rdy = d * this.ay;
  97436. var rdz = d * this.az;
  97437. var w1 = this.m1 / (this.m1 + this.m2);
  97438. var w2 = 1 - w1;
  97439. this.r1x = this.r1.x + rdx * w1;
  97440. this.r1y = this.r1.y + rdy * w1;
  97441. this.r1z = this.r1.z + rdz * w1;
  97442. this.r2x = this.r2.x - rdx * w2;
  97443. this.r2y = this.r2.y - rdy * w2;
  97444. this.r2z = this.r2.z - rdz * w2;
  97445. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97446. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97447. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97448. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97449. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97450. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97451. this.l1x = this.ax * this.m1;
  97452. this.l1y = this.ay * this.m1;
  97453. this.l1z = this.az * this.m1;
  97454. this.l2x = this.ax * this.m2;
  97455. this.l2y = this.ay * this.m2;
  97456. this.l2z = this.az * this.m2;
  97457. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97458. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97459. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97460. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97461. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97462. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97463. this.motorDenom =
  97464. this.m1 + this.m2 +
  97465. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97466. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97467. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97468. this.invMotorDenom = 1 / this.motorDenom;
  97469. if (enableSpring && this.limitState != 2) {
  97470. var omega = 6.2831853 * frequency;
  97471. var k = omega * omega * timeStep;
  97472. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97473. this.cfm = this.motorDenom * dmp;
  97474. this.limitVelocity *= k * dmp;
  97475. } else {
  97476. this.cfm = 0;
  97477. this.limitVelocity *= invTimeStep * 0.05;
  97478. }
  97479. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97480. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97481. this.l1.x += totalImpulse * this.l1x;
  97482. this.l1.y += totalImpulse * this.l1y;
  97483. this.l1.z += totalImpulse * this.l1z;
  97484. this.a1.x += totalImpulse * this.a1x;
  97485. this.a1.y += totalImpulse * this.a1y;
  97486. this.a1.z += totalImpulse * this.a1z;
  97487. this.l2.x -= totalImpulse * this.l2x;
  97488. this.l2.y -= totalImpulse * this.l2y;
  97489. this.l2.z -= totalImpulse * this.l2z;
  97490. this.a2.x -= totalImpulse * this.a2x;
  97491. this.a2.y -= totalImpulse * this.a2y;
  97492. this.a2.z -= totalImpulse * this.a2z;
  97493. },
  97494. solve: function () {
  97495. var rvn =
  97496. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97497. 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;
  97498. // motor part
  97499. var newMotorImpulse;
  97500. if (this.enableMotor) {
  97501. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97502. var oldMotorImpulse = this.motorImpulse;
  97503. this.motorImpulse += newMotorImpulse;
  97504. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97505. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97506. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97507. rvn -= newMotorImpulse * this.motorDenom;
  97508. } else newMotorImpulse = 0;
  97509. // limit part
  97510. var newLimitImpulse;
  97511. if (this.limitState != 2) {
  97512. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97513. var oldLimitImpulse = this.limitImpulse;
  97514. this.limitImpulse += newLimitImpulse;
  97515. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97516. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97517. } else newLimitImpulse = 0;
  97518. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97519. this.l1.x += totalImpulse * this.l1x;
  97520. this.l1.y += totalImpulse * this.l1y;
  97521. this.l1.z += totalImpulse * this.l1z;
  97522. this.a1.x += totalImpulse * this.a1x;
  97523. this.a1.y += totalImpulse * this.a1y;
  97524. this.a1.z += totalImpulse * this.a1z;
  97525. this.l2.x -= totalImpulse * this.l2x;
  97526. this.l2.y -= totalImpulse * this.l2y;
  97527. this.l2.z -= totalImpulse * this.l2z;
  97528. this.a2.x -= totalImpulse * this.a2x;
  97529. this.a2.y -= totalImpulse * this.a2y;
  97530. this.a2.z -= totalImpulse * this.a2z;
  97531. }
  97532. }
  97533. /**
  97534. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97535. * @author saharan
  97536. */
  97537. OIMO.Contact = function () {
  97538. // The first shape.
  97539. this.shape1 = null;
  97540. // The second shape.
  97541. this.shape2 = null;
  97542. // The first rigid body.
  97543. this.body1 = null;
  97544. // The second rigid body.
  97545. this.body2 = null;
  97546. // The previous contact in the world.
  97547. this.prev = null;
  97548. // The next contact in the world.
  97549. this.next = null;
  97550. // Internal
  97551. this.persisting = false;
  97552. // Whether both the rigid bodies are sleeping or not.
  97553. this.sleeping = false;
  97554. // The collision detector between two shapes.
  97555. this.detector = null;
  97556. // The contact constraint of the contact.
  97557. this.constraint = null;
  97558. // Whether the shapes are touching or not.
  97559. this.touching = false;
  97560. this.b1Link = new OIMO.ContactLink(this);
  97561. this.b2Link = new OIMO.ContactLink(this);
  97562. this.s1Link = new OIMO.ContactLink(this);
  97563. this.s2Link = new OIMO.ContactLink(this);
  97564. // The contact manifold of the contact.
  97565. this.manifold = new OIMO.ContactManifold();
  97566. this.buffer = [];// vector 4
  97567. this.buffer.length = 4;
  97568. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97569. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97570. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97571. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97572. this.points = this.manifold.points;
  97573. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97574. }
  97575. OIMO.Contact.prototype = {
  97576. constructor: OIMO.Contact,
  97577. mixRestitution: function (restitution1, restitution2) {
  97578. return OIMO.sqrt(restitution1 * restitution2);
  97579. },
  97580. mixFriction: function (friction1, friction2) {
  97581. return OIMO.sqrt(friction1 * friction2);
  97582. },
  97583. /**
  97584. * Update the contact manifold.
  97585. */
  97586. updateManifold: function () {
  97587. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97588. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97589. var numBuffers = this.manifold.numPoints;
  97590. var i = numBuffers;
  97591. while (i--) {
  97592. //for(var i=0;i<numBuffers;i++){
  97593. var b = this.buffer[i];
  97594. var p = this.points[i];
  97595. b.lp1X = p.localPoint1.x;
  97596. b.lp1Y = p.localPoint1.y;
  97597. b.lp1Z = p.localPoint1.z;
  97598. b.lp2X = p.localPoint2.x;
  97599. b.lp2Y = p.localPoint2.y;
  97600. b.lp2Z = p.localPoint2.z;
  97601. b.impulse = p.normalImpulse;
  97602. }
  97603. this.manifold.numPoints = 0;
  97604. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97605. var num = this.manifold.numPoints;
  97606. if (num == 0) {
  97607. this.touching = false;
  97608. return;
  97609. }
  97610. this.touching = true;
  97611. i = num;
  97612. while (i--) {
  97613. //for(i=0; i<num; i++){
  97614. p = this.points[i];
  97615. var lp1x = p.localPoint1.x;
  97616. var lp1y = p.localPoint1.y;
  97617. var lp1z = p.localPoint1.z;
  97618. var lp2x = p.localPoint2.x;
  97619. var lp2y = p.localPoint2.y;
  97620. var lp2z = p.localPoint2.z;
  97621. var index = -1;
  97622. var minDistance = 0.0004;
  97623. var j = numBuffers;
  97624. while (j--) {
  97625. //for(var j=0;j<numBuffers;j++){
  97626. b = this.buffer[j];
  97627. var dx = b.lp1X - lp1x;
  97628. var dy = b.lp1Y - lp1y;
  97629. var dz = b.lp1Z - lp1z;
  97630. var distance1 = dx * dx + dy * dy + dz * dz;
  97631. dx = b.lp2X - lp2x;
  97632. dy = b.lp2Y - lp2y;
  97633. dz = b.lp2Z - lp2z;
  97634. var distance2 = dx * dx + dy * dy + dz * dz;
  97635. if (distance1 < distance2) {
  97636. if (distance1 < minDistance) {
  97637. minDistance = distance1;
  97638. index = j;
  97639. }
  97640. } else {
  97641. if (distance2 < minDistance) {
  97642. minDistance = distance2;
  97643. index = j;
  97644. }
  97645. }
  97646. }
  97647. if (index != -1) {
  97648. var tmp = this.buffer[index];
  97649. this.buffer[index] = this.buffer[--numBuffers];
  97650. this.buffer[numBuffers] = tmp;
  97651. p.normalImpulse = tmp.impulse;
  97652. p.warmStarted = true;
  97653. } else {
  97654. p.normalImpulse = 0;
  97655. p.warmStarted = false;
  97656. }
  97657. }
  97658. },
  97659. /**
  97660. * Attach the contact to the shapes.
  97661. * @param shape1
  97662. * @param shape2
  97663. */
  97664. attach: function (shape1, shape2) {
  97665. this.shape1 = shape1;
  97666. this.shape2 = shape2;
  97667. this.body1 = shape1.parent;
  97668. this.body2 = shape2.parent;
  97669. this.manifold.body1 = this.body1;
  97670. this.manifold.body2 = this.body2;
  97671. this.constraint.body1 = this.body1;
  97672. this.constraint.body2 = this.body2;
  97673. this.constraint.attach();
  97674. this.s1Link.shape = shape2;
  97675. this.s1Link.body = this.body2;
  97676. this.s2Link.shape = shape1;
  97677. this.s2Link.body = this.body1;
  97678. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97679. else this.s1Link.next = null;
  97680. shape1.contactLink = this.s1Link;
  97681. shape1.numContacts++;
  97682. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97683. else this.s2Link.next = null;
  97684. shape2.contactLink = this.s2Link;
  97685. shape2.numContacts++;
  97686. this.b1Link.shape = shape2;
  97687. this.b1Link.body = this.body2;
  97688. this.b2Link.shape = shape1;
  97689. this.b2Link.body = this.body1;
  97690. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97691. else this.b1Link.next = null;
  97692. this.body1.contactLink = this.b1Link;
  97693. this.body1.numContacts++;
  97694. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97695. else this.b2Link.next = null;
  97696. this.body2.contactLink = this.b2Link;
  97697. this.body2.numContacts++;
  97698. this.prev = null;
  97699. this.next = null;
  97700. this.persisting = true;
  97701. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97702. this.manifold.numPoints = 0;
  97703. },
  97704. /**
  97705. * Detach the contact from the shapes.
  97706. */
  97707. detach: function () {
  97708. var prev = this.s1Link.prev;
  97709. var next = this.s1Link.next;
  97710. if (prev !== null) prev.next = next;
  97711. if (next !== null) next.prev = prev;
  97712. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97713. this.s1Link.prev = null;
  97714. this.s1Link.next = null;
  97715. this.s1Link.shape = null;
  97716. this.s1Link.body = null;
  97717. this.shape1.numContacts--;
  97718. prev = this.s2Link.prev;
  97719. next = this.s2Link.next;
  97720. if (prev !== null) prev.next = next;
  97721. if (next !== null) next.prev = prev;
  97722. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  97723. this.s2Link.prev = null;
  97724. this.s2Link.next = null;
  97725. this.s2Link.shape = null;
  97726. this.s2Link.body = null;
  97727. this.shape2.numContacts--;
  97728. prev = this.b1Link.prev;
  97729. next = this.b1Link.next;
  97730. if (prev !== null) prev.next = next;
  97731. if (next !== null) next.prev = prev;
  97732. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  97733. this.b1Link.prev = null;
  97734. this.b1Link.next = null;
  97735. this.b1Link.shape = null;
  97736. this.b1Link.body = null;
  97737. this.body1.numContacts--;
  97738. prev = this.b2Link.prev;
  97739. next = this.b2Link.next;
  97740. if (prev !== null) prev.next = next;
  97741. if (next !== null) next.prev = prev;
  97742. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  97743. this.b2Link.prev = null;
  97744. this.b2Link.next = null;
  97745. this.b2Link.shape = null;
  97746. this.b2Link.body = null;
  97747. this.body2.numContacts--;
  97748. this.manifold.body1 = null;
  97749. this.manifold.body2 = null;
  97750. this.constraint.body1 = null;
  97751. this.constraint.body2 = null;
  97752. this.constraint.detach();
  97753. this.shape1 = null;
  97754. this.shape2 = null;
  97755. this.body1 = null;
  97756. this.body2 = null;
  97757. }
  97758. }
  97759. /**
  97760. * ...
  97761. * @author saharan
  97762. */
  97763. OIMO.ContactConstraint = function (manifold) {
  97764. OIMO.Constraint.call(this);
  97765. // The contact manifold of the constraint.
  97766. this.manifold = manifold;
  97767. // The coefficient of restitution of the constraint.
  97768. this.restitution = NaN;
  97769. // The coefficient of friction of the constraint.
  97770. this.friction = NaN;
  97771. this.p1 = null;
  97772. this.p2 = null;
  97773. this.lv1 = null;
  97774. this.lv2 = null;
  97775. this.av1 = null;
  97776. this.av2 = null;
  97777. this.i1 = null;
  97778. this.i2 = null;
  97779. this.ii1 = null;
  97780. this.ii2 = null;
  97781. this.m1 = NaN;
  97782. this.m2 = NaN;
  97783. this.num = 0;
  97784. this.ps = manifold.points;
  97785. this.cs = new OIMO.ContactPointDataBuffer();
  97786. this.cs.next = new OIMO.ContactPointDataBuffer();
  97787. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  97788. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  97789. }
  97790. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  97791. /**
  97792. * Attach the constraint to the bodies.
  97793. */
  97794. OIMO.ContactConstraint.prototype.attach = function () {
  97795. this.p1 = this.body1.position;
  97796. this.p2 = this.body2.position;
  97797. this.lv1 = this.body1.linearVelocity;
  97798. this.av1 = this.body1.angularVelocity;
  97799. this.lv2 = this.body2.linearVelocity;
  97800. this.av2 = this.body2.angularVelocity;
  97801. this.i1 = this.body1.inverseInertia;
  97802. this.i2 = this.body2.inverseInertia;
  97803. }
  97804. /**
  97805. * Detach the constraint from the bodies.
  97806. */
  97807. OIMO.ContactConstraint.prototype.detach = function () {
  97808. this.p1 = null;
  97809. this.p2 = null;
  97810. this.lv1 = null;
  97811. this.lv2 = null;
  97812. this.av1 = null;
  97813. this.av2 = null;
  97814. this.i1 = null;
  97815. this.i2 = null;
  97816. }
  97817. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  97818. this.m1 = this.body1.inverseMass;
  97819. this.m2 = this.body2.inverseMass;
  97820. this.ii1 = this.i1.clone();
  97821. this.ii2 = this.i2.clone();
  97822. var ii1 = this.ii1.elements;
  97823. var ii2 = this.ii2.elements;
  97824. var p1x = this.p1.x;
  97825. var p1y = this.p1.y;
  97826. var p1z = this.p1.z;
  97827. var p2x = this.p2.x;
  97828. var p2y = this.p2.y;
  97829. var p2z = this.p2.z;
  97830. var m1m2 = this.m1 + this.m2;
  97831. this.num = this.manifold.numPoints;
  97832. var c = this.cs;
  97833. for (var i = 0; i < this.num; i++) {
  97834. var p = this.ps[i];
  97835. var tmp1X;
  97836. var tmp1Y;
  97837. var tmp1Z;
  97838. var tmp2X;
  97839. var tmp2Y;
  97840. var tmp2Z;
  97841. tmp1X = p.position.x;
  97842. tmp1Y = p.position.y;
  97843. tmp1Z = p.position.z;
  97844. var rp1X = tmp1X - p1x;
  97845. var rp1Y = tmp1Y - p1y;
  97846. var rp1Z = tmp1Z - p1z;
  97847. var rp2X = tmp1X - p2x;
  97848. var rp2Y = tmp1Y - p2y;
  97849. var rp2Z = tmp1Z - p2z;
  97850. c.rp1X = rp1X;
  97851. c.rp1Y = rp1Y;
  97852. c.rp1Z = rp1Z;
  97853. c.rp2X = rp2X;
  97854. c.rp2Y = rp2Y;
  97855. c.rp2Z = rp2Z;
  97856. c.norImp = p.normalImpulse;
  97857. c.tanImp = p.tangentImpulse;
  97858. c.binImp = p.binormalImpulse;
  97859. var norX = p.normal.x;
  97860. var norY = p.normal.y;
  97861. var norZ = p.normal.z;
  97862. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  97863. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  97864. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  97865. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  97866. var tanX = rvX - rvn * norX;
  97867. var tanY = rvY - rvn * norY;
  97868. var tanZ = rvZ - rvn * norZ;
  97869. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  97870. if (len > 0.04) {
  97871. len = 1 / OIMO.sqrt(len);
  97872. } else {
  97873. tanX = norY * norX - norZ * norZ;
  97874. tanY = -norZ * norY - norX * norX;
  97875. tanZ = norX * norZ + norY * norY;
  97876. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  97877. }
  97878. tanX *= len;
  97879. tanY *= len;
  97880. tanZ *= len;
  97881. var binX = norY * tanZ - norZ * tanY;
  97882. var binY = norZ * tanX - norX * tanZ;
  97883. var binZ = norX * tanY - norY * tanX;
  97884. c.norX = norX;
  97885. c.norY = norY;
  97886. c.norZ = norZ;
  97887. c.tanX = tanX;
  97888. c.tanY = tanY;
  97889. c.tanZ = tanZ;
  97890. c.binX = binX;
  97891. c.binY = binY;
  97892. c.binZ = binZ;
  97893. c.norU1X = norX * this.m1;
  97894. c.norU1Y = norY * this.m1;
  97895. c.norU1Z = norZ * this.m1;
  97896. c.norU2X = norX * this.m2;
  97897. c.norU2Y = norY * this.m2;
  97898. c.norU2Z = norZ * this.m2;
  97899. c.tanU1X = tanX * this.m1;
  97900. c.tanU1Y = tanY * this.m1;
  97901. c.tanU1Z = tanZ * this.m1;
  97902. c.tanU2X = tanX * this.m2;
  97903. c.tanU2Y = tanY * this.m2;
  97904. c.tanU2Z = tanZ * this.m2;
  97905. c.binU1X = binX * this.m1;
  97906. c.binU1Y = binY * this.m1;
  97907. c.binU1Z = binZ * this.m1;
  97908. c.binU2X = binX * this.m2;
  97909. c.binU2Y = binY * this.m2;
  97910. c.binU2Z = binZ * this.m2;
  97911. var norT1X = rp1Y * norZ - rp1Z * norY;
  97912. var norT1Y = rp1Z * norX - rp1X * norZ;
  97913. var norT1Z = rp1X * norY - rp1Y * norX;
  97914. var norT2X = rp2Y * norZ - rp2Z * norY;
  97915. var norT2Y = rp2Z * norX - rp2X * norZ;
  97916. var norT2Z = rp2X * norY - rp2Y * norX;
  97917. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  97918. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  97919. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  97920. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  97921. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  97922. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  97923. var binT1X = rp1Y * binZ - rp1Z * binY;
  97924. var binT1Y = rp1Z * binX - rp1X * binZ;
  97925. var binT1Z = rp1X * binY - rp1Y * binX;
  97926. var binT2X = rp2Y * binZ - rp2Z * binY;
  97927. var binT2Y = rp2Z * binX - rp2X * binZ;
  97928. var binT2Z = rp2X * binY - rp2Y * binX;
  97929. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97930. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97931. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97932. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97933. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97934. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97935. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97936. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97937. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97938. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97939. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97940. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97941. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97942. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97943. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97944. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97945. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97946. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97947. c.norT1X = norT1X;
  97948. c.norT1Y = norT1Y;
  97949. c.norT1Z = norT1Z;
  97950. c.tanT1X = tanT1X;
  97951. c.tanT1Y = tanT1Y;
  97952. c.tanT1Z = tanT1Z;
  97953. c.binT1X = binT1X;
  97954. c.binT1Y = binT1Y;
  97955. c.binT1Z = binT1Z;
  97956. c.norT2X = norT2X;
  97957. c.norT2Y = norT2Y;
  97958. c.norT2Z = norT2Z;
  97959. c.tanT2X = tanT2X;
  97960. c.tanT2Y = tanT2Y;
  97961. c.tanT2Z = tanT2Z;
  97962. c.binT2X = binT2X;
  97963. c.binT2Y = binT2Y;
  97964. c.binT2Z = binT2Z;
  97965. c.norTU1X = norTU1X;
  97966. c.norTU1Y = norTU1Y;
  97967. c.norTU1Z = norTU1Z;
  97968. c.tanTU1X = tanTU1X;
  97969. c.tanTU1Y = tanTU1Y;
  97970. c.tanTU1Z = tanTU1Z;
  97971. c.binTU1X = binTU1X;
  97972. c.binTU1Y = binTU1Y;
  97973. c.binTU1Z = binTU1Z;
  97974. c.norTU2X = norTU2X;
  97975. c.norTU2Y = norTU2Y;
  97976. c.norTU2Z = norTU2Z;
  97977. c.tanTU2X = tanTU2X;
  97978. c.tanTU2Y = tanTU2Y;
  97979. c.tanTU2Z = tanTU2Z;
  97980. c.binTU2X = binTU2X;
  97981. c.binTU2Y = binTU2Y;
  97982. c.binTU2Z = binTU2Z;
  97983. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97984. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97985. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97986. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97987. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97988. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97989. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97990. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97991. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97992. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97993. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97994. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97995. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  97996. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97997. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97998. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97999. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98000. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98001. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98002. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98003. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98004. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98005. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98006. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98007. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98008. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98009. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98010. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98011. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98012. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98013. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98014. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98015. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98016. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98017. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98018. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98019. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98020. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98021. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98022. c.norDen = norDen;
  98023. c.tanDen = tanDen;
  98024. c.binDen = binDen;
  98025. if (p.warmStarted) {
  98026. var norImp = p.normalImpulse;
  98027. this.lv1.x += c.norU1X * norImp;
  98028. this.lv1.y += c.norU1Y * norImp;
  98029. this.lv1.z += c.norU1Z * norImp;
  98030. this.av1.x += norTU1X * norImp;
  98031. this.av1.y += norTU1Y * norImp;
  98032. this.av1.z += norTU1Z * norImp;
  98033. this.lv2.x -= c.norU2X * norImp;
  98034. this.lv2.y -= c.norU2Y * norImp;
  98035. this.lv2.z -= c.norU2Z * norImp;
  98036. this.av2.x -= norTU2X * norImp;
  98037. this.av2.y -= norTU2Y * norImp;
  98038. this.av2.z -= norTU2Z * norImp;
  98039. c.norImp = norImp;
  98040. c.tanImp = 0;
  98041. c.binImp = 0;
  98042. rvn = 0; // disable bouncing
  98043. } else {
  98044. c.norImp = 0;
  98045. c.tanImp = 0;
  98046. c.binImp = 0;
  98047. }
  98048. if (rvn > -1) {
  98049. rvn = 0; // disable bouncing
  98050. }
  98051. var norTar = this.restitution * -rvn;
  98052. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98053. if (norTar < sepV) norTar = sepV;
  98054. c.norTar = norTar;
  98055. c.last = i == this.num - 1;
  98056. c = c.next;
  98057. }
  98058. }
  98059. OIMO.ContactConstraint.prototype.solve = function () {
  98060. var lv1x = this.lv1.x;
  98061. var lv1y = this.lv1.y;
  98062. var lv1z = this.lv1.z;
  98063. var lv2x = this.lv2.x;
  98064. var lv2y = this.lv2.y;
  98065. var lv2z = this.lv2.z;
  98066. var av1x = this.av1.x;
  98067. var av1y = this.av1.y;
  98068. var av1z = this.av1.z;
  98069. var av2x = this.av2.x;
  98070. var av2y = this.av2.y;
  98071. var av2z = this.av2.z;
  98072. var c = this.cs;
  98073. while (true) {
  98074. var oldImp1;
  98075. var newImp1;
  98076. var oldImp2;
  98077. var newImp2;
  98078. var rvn;
  98079. var norImp = c.norImp;
  98080. var tanImp = c.tanImp;
  98081. var binImp = c.binImp;
  98082. var max = -norImp * this.friction;
  98083. var rvX = lv2x - lv1x;
  98084. var rvY = lv2y - lv1y;
  98085. var rvZ = lv2z - lv1z;
  98086. rvn =
  98087. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98088. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98089. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98090. ;
  98091. oldImp1 = tanImp;
  98092. newImp1 = rvn * c.tanDen;
  98093. tanImp += newImp1;
  98094. rvn =
  98095. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98096. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98097. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98098. ;
  98099. oldImp2 = binImp;
  98100. newImp2 = rvn * c.binDen;
  98101. binImp += newImp2;
  98102. // cone friction clamp
  98103. var len = tanImp * tanImp + binImp * binImp;
  98104. if (len > max * max) {
  98105. len = max / OIMO.sqrt(len);
  98106. tanImp *= len;
  98107. binImp *= len;
  98108. }
  98109. newImp1 = tanImp - oldImp1;
  98110. newImp2 = binImp - oldImp2;
  98111. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98112. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98113. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98114. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98115. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98116. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98117. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98118. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98119. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98120. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98121. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98122. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98123. // restitution part
  98124. rvn =
  98125. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98126. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98127. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98128. oldImp1 = norImp;
  98129. newImp1 = (rvn - c.norTar) * c.norDen;
  98130. norImp += newImp1;
  98131. if (norImp > 0) norImp = 0;
  98132. newImp1 = norImp - oldImp1;
  98133. lv1x += c.norU1X * newImp1;
  98134. lv1y += c.norU1Y * newImp1;
  98135. lv1z += c.norU1Z * newImp1;
  98136. av1x += c.norTU1X * newImp1;
  98137. av1y += c.norTU1Y * newImp1;
  98138. av1z += c.norTU1Z * newImp1;
  98139. lv2x -= c.norU2X * newImp1;
  98140. lv2y -= c.norU2Y * newImp1;
  98141. lv2z -= c.norU2Z * newImp1;
  98142. av2x -= c.norTU2X * newImp1;
  98143. av2y -= c.norTU2Y * newImp1;
  98144. av2z -= c.norTU2Z * newImp1;
  98145. c.norImp = norImp;
  98146. c.tanImp = tanImp;
  98147. c.binImp = binImp;
  98148. if (c.last) break;
  98149. c = c.next;
  98150. }
  98151. this.lv1.x = lv1x;
  98152. this.lv1.y = lv1y;
  98153. this.lv1.z = lv1z;
  98154. this.lv2.x = lv2x;
  98155. this.lv2.y = lv2y;
  98156. this.lv2.z = lv2z;
  98157. this.av1.x = av1x;
  98158. this.av1.y = av1y;
  98159. this.av1.z = av1z;
  98160. this.av2.x = av2x;
  98161. this.av2.y = av2y;
  98162. this.av2.z = av2z;
  98163. }
  98164. OIMO.ContactConstraint.prototype.postSolve = function () {
  98165. var c = this.cs;
  98166. var i = this.num;
  98167. while (i--) {
  98168. //for(var i=0;i<this.num;i++){
  98169. var p = this.ps[i];
  98170. p.normal.x = c.norX;
  98171. p.normal.y = c.norY;
  98172. p.normal.z = c.norZ;
  98173. p.tangent.x = c.tanX;
  98174. p.tangent.y = c.tanY;
  98175. p.tangent.z = c.tanZ;
  98176. p.binormal.x = c.binX;
  98177. p.binormal.y = c.binY;
  98178. p.binormal.z = c.binZ;
  98179. p.normalImpulse = c.norImp;
  98180. p.tangentImpulse = c.tanImp;
  98181. p.binormalImpulse = c.binImp;
  98182. p.normalDenominator = c.norDen;
  98183. p.tangentDenominator = c.tanDen;
  98184. p.binormalDenominator = c.binDen;
  98185. c = c.next;
  98186. }
  98187. }
  98188. /**
  98189. * A link list of contacts.
  98190. * @author saharan
  98191. */
  98192. OIMO.ContactLink = function (contact) {
  98193. // The previous contact link.
  98194. this.prev = null;
  98195. // The next contact link.
  98196. this.next = null;
  98197. // The shape of the contact.
  98198. this.shape = null;
  98199. // The other rigid body.
  98200. this.body = null;
  98201. // The contact of the link.
  98202. this.contact = contact;
  98203. }
  98204. /**
  98205. * A contact manifold between two shapes.
  98206. * @author saharan
  98207. */
  98208. OIMO.ContactManifold = function () {
  98209. // The first rigid body.
  98210. this.body1 = null;
  98211. // The second rigid body.
  98212. this.body2 = null;
  98213. // The number of manifold points.
  98214. this.numPoints = 0;
  98215. // The manifold points.
  98216. this.points = [];
  98217. this.points.length = 4;
  98218. this.points[0] = new OIMO.ManifoldPoint();
  98219. this.points[1] = new OIMO.ManifoldPoint();
  98220. this.points[2] = new OIMO.ManifoldPoint();
  98221. this.points[3] = new OIMO.ManifoldPoint();
  98222. }
  98223. OIMO.ContactManifold.prototype = {
  98224. constructor: OIMO.ContactManifold,
  98225. /**
  98226. * Reset the manifold.
  98227. * @param shape1
  98228. * @param shape2
  98229. */
  98230. reset: function (shape1, shape2) {
  98231. this.body1 = shape1.parent;
  98232. this.body2 = shape2.parent;
  98233. this.numPoints = 0;
  98234. },
  98235. /**
  98236. * Add a point into this manifold.
  98237. * @param x
  98238. * @param y
  98239. * @param z
  98240. * @param normalX
  98241. * @param normalY
  98242. * @param normalZ
  98243. * @param penetration
  98244. * @param flip
  98245. */
  98246. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98247. var p = this.points[this.numPoints++];
  98248. p.position.x = x;
  98249. p.position.y = y;
  98250. p.position.z = z;
  98251. var r = this.body1.rotation;
  98252. var rx = x - this.body1.position.x;
  98253. var ry = y - this.body1.position.y;
  98254. var rz = z - this.body1.position.z;
  98255. var tr = r.elements;
  98256. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98257. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98258. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98259. r = this.body2.rotation;
  98260. rx = x - this.body2.position.x;
  98261. ry = y - this.body2.position.y;
  98262. rz = z - this.body2.position.z;
  98263. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98264. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98265. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98266. p.normalImpulse = 0;
  98267. if (flip) {
  98268. p.normal.x = -normalX;
  98269. p.normal.y = -normalY;
  98270. p.normal.z = -normalZ;
  98271. } else {
  98272. p.normal.x = normalX;
  98273. p.normal.y = normalY;
  98274. p.normal.z = normalZ;
  98275. }
  98276. p.penetration = penetration;
  98277. p.warmStarted = false;
  98278. }
  98279. }
  98280. OIMO.ContactPointDataBuffer = function () {
  98281. this.norX = NaN;
  98282. this.norY = NaN;
  98283. this.norZ = NaN;
  98284. this.tanX = NaN;
  98285. this.tanY = NaN;
  98286. this.tanZ = NaN;
  98287. this.binX = NaN;
  98288. this.binY = NaN;
  98289. this.binZ = NaN;
  98290. this.rp1X = NaN;
  98291. this.rp1Y = NaN;
  98292. this.rp1Z = NaN;
  98293. this.rp2X = NaN;
  98294. this.rp2Y = NaN;
  98295. this.rp2Z = NaN;
  98296. this.norU1X = NaN;
  98297. this.norU1Y = NaN;
  98298. this.norU1Z = NaN;
  98299. this.norU2X = NaN;
  98300. this.norU2Y = NaN;
  98301. this.norU2Z = NaN;
  98302. this.tanU1X = NaN;
  98303. this.tanU1Y = NaN;
  98304. this.tanU1Z = NaN;
  98305. this.tanU2X = NaN;
  98306. this.tanU2Y = NaN;
  98307. this.tanU2Z = NaN;
  98308. this.binU1X = NaN;
  98309. this.binU1Y = NaN;
  98310. this.binU1Z = NaN;
  98311. this.binU2X = NaN;
  98312. this.binU2Y = NaN;
  98313. this.binU2Z = NaN;
  98314. this.norT1X = NaN;
  98315. this.norT1Y = NaN;
  98316. this.norT1Z = NaN;
  98317. this.norT2X = NaN;
  98318. this.norT2Y = NaN;
  98319. this.norT2Z = NaN;
  98320. this.tanT1X = NaN;
  98321. this.tanT1Y = NaN;
  98322. this.tanT1Z = NaN;
  98323. this.tanT2X = NaN;
  98324. this.tanT2Y = NaN;
  98325. this.tanT2Z = NaN;
  98326. this.binT1X = NaN;
  98327. this.binT1Y = NaN;
  98328. this.binT1Z = NaN;
  98329. this.binT2X = NaN;
  98330. this.binT2Y = NaN;
  98331. this.binT2Z = NaN;
  98332. this.norTU1X = NaN;
  98333. this.norTU1Y = NaN;
  98334. this.norTU1Z = NaN;
  98335. this.norTU2X = NaN;
  98336. this.norTU2Y = NaN;
  98337. this.norTU2Z = NaN;
  98338. this.tanTU1X = NaN;
  98339. this.tanTU1Y = NaN;
  98340. this.tanTU1Z = NaN;
  98341. this.tanTU2X = NaN;
  98342. this.tanTU2Y = NaN;
  98343. this.tanTU2Z = NaN;
  98344. this.binTU1X = NaN;
  98345. this.binTU1Y = NaN;
  98346. this.binTU1Z = NaN;
  98347. this.binTU2X = NaN;
  98348. this.binTU2Y = NaN;
  98349. this.binTU2Z = NaN;
  98350. this.norImp = NaN;
  98351. this.tanImp = NaN;
  98352. this.binImp = NaN;
  98353. this.norDen = NaN;
  98354. this.tanDen = NaN;
  98355. this.binDen = NaN;
  98356. this.norTar = NaN;
  98357. this.next = null;
  98358. this.last = false;
  98359. }
  98360. OIMO.ImpulseDataBuffer = function () {
  98361. this.lp1X = NaN;
  98362. this.lp1Y = NaN;
  98363. this.lp1Z = NaN;
  98364. this.lp2X = NaN;
  98365. this.lp2Y = NaN;
  98366. this.lp2Z = NaN;
  98367. this.impulse = NaN;
  98368. }
  98369. /**
  98370. * The class holds details of the contact point.
  98371. * @author saharan
  98372. */
  98373. OIMO.ManifoldPoint = function () {
  98374. // Whether this manifold point is persisting or not.
  98375. this.warmStarted = false;
  98376. // The position of this manifold point.
  98377. this.position = new OIMO.Vec3();
  98378. // The position in the first shape's coordinate.
  98379. this.localPoint1 = new OIMO.Vec3();
  98380. // The position in the second shape's coordinate.
  98381. this.localPoint2 = new OIMO.Vec3();
  98382. // The normal vector of this manifold point.
  98383. this.normal = new OIMO.Vec3();
  98384. // The tangent vector of this manifold point.
  98385. this.tangent = new OIMO.Vec3();
  98386. // The binormal vector of this manifold point.
  98387. this.binormal = new OIMO.Vec3();
  98388. // The impulse in normal direction.
  98389. this.normalImpulse = 0;
  98390. // The impulse in tangent direction.
  98391. this.tangentImpulse = 0;
  98392. // The impulse in binormal direction.
  98393. this.binormalImpulse = 0;
  98394. // The denominator in normal direction.
  98395. this.normalDenominator = 0;
  98396. // The denominator in tangent direction.
  98397. this.tangentDenominator = 0;
  98398. // The denominator in binormal direction.
  98399. this.binormalDenominator = 0;
  98400. // The depth of penetration.
  98401. this.penetration = 0;
  98402. }
  98403. /**
  98404. * This class holds mass information of a shape.
  98405. * @author saharan
  98406. */
  98407. OIMO.MassInfo = function () {
  98408. // Mass of the shape.
  98409. this.mass = 0;
  98410. // The moment inertia of the shape.
  98411. this.inertia = new OIMO.Mat33();
  98412. };
  98413. /**
  98414. * A shape is used to detect collisions of rigid bodies.
  98415. * @author saharan
  98416. * @author lo-th
  98417. */
  98418. OIMO.Shape = function (config) {
  98419. this.type = OIMO.SHAPE_NULL;
  98420. // The global identification of the shape should be unique to the shape.
  98421. this.id = OIMO.nextID++;
  98422. // The previous shape in parent rigid body.
  98423. this.prev = null;
  98424. // The next shape in parent rigid body.
  98425. this.next = null;
  98426. // The proxy of the shape used for broad-phase collision detection.
  98427. this.proxy = null;
  98428. // The parent rigid body of the shape.
  98429. this.parent = null;
  98430. // The linked list of the contacts with the shape.
  98431. this.contactLink = null;
  98432. // The number of the contacts with the shape.
  98433. this.numContacts = 0;
  98434. // The center of gravity of the shape in world coordinate system.
  98435. this.position = new OIMO.Vec3();
  98436. // The rotation matrix of the shape in world coordinate system
  98437. this.rotation = new OIMO.Mat33();
  98438. // The position of the shape in parent's coordinate system.
  98439. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98440. // The rotation matrix of the shape in parent's coordinate system.
  98441. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98442. // The axis-aligned bounding box of the shape.
  98443. this.aabb = new OIMO.AABB();
  98444. // The density of the shape.
  98445. this.density = config.density;
  98446. // The coefficient of friction of the shape.
  98447. this.friction = config.friction;
  98448. // The coefficient of restitution of the shape.
  98449. this.restitution = config.restitution;
  98450. // The bits of the collision groups to which the shape belongs.
  98451. this.belongsTo = config.belongsTo;
  98452. // The bits of the collision groups with which the shape collides.
  98453. this.collidesWith = config.collidesWith;
  98454. };
  98455. OIMO.Shape.prototype = {
  98456. constructor: OIMO.Shape,
  98457. // Calculate the mass information of the shape.
  98458. calculateMassInfo: function (out) {
  98459. OIMO.Error("Shape", "Inheritance error.");
  98460. },
  98461. // Update the proxy of the shape.
  98462. updateProxy: function () {
  98463. OIMO.Error("Shape", "Inheritance error.");
  98464. }
  98465. };
  98466. /**
  98467. * A shape configuration holds common configuration data for constructing a shape.
  98468. * Shape configurations can be reused safely.
  98469. * @author saharan
  98470. */
  98471. OIMO.ShapeConfig = function () {
  98472. // The position of the shape in parent's coordinate system.
  98473. this.relativePosition = new OIMO.Vec3();
  98474. // The rotation matrix of the shape in parent's coordinate system.
  98475. this.relativeRotation = new OIMO.Mat33();
  98476. // The coefficient of friction of the shape.
  98477. this.friction = 0.4;
  98478. // The coefficient of restitution of the shape.
  98479. this.restitution = 0.2;
  98480. // The density of the shape.
  98481. this.density = 1;
  98482. // The bits of the collision groups to which the shape belongs.
  98483. this.belongsTo = 1;
  98484. // The bits of the collision groups with which the shape collides.
  98485. this.collidesWith = 0xffffffff;
  98486. };
  98487. /**
  98488. * A box shape.
  98489. * @author saharan
  98490. * @author lo-th
  98491. */
  98492. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98493. OIMO.Shape.call(this, config);
  98494. this.type = OIMO.SHAPE_BOX;
  98495. // The width of the box.
  98496. this.width = Width;
  98497. // The height of the box.
  98498. this.height = Height;
  98499. // The depth of the box.
  98500. this.depth = Depth;
  98501. // The half-width of the box.
  98502. this.halfWidth = Width * 0.5;
  98503. // The half-height of the box.
  98504. this.halfHeight = Height * 0.5;
  98505. // The half-depth of the box.
  98506. this.halfDepth = Depth * 0.5;
  98507. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98508. this.elements = new OIMO_ARRAY_TYPE(24);
  98509. };
  98510. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98511. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98512. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98513. var mass = this.width * this.height * this.depth * this.density;
  98514. var divid = 1 / 12;
  98515. out.mass = mass;
  98516. out.inertia.set(
  98517. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98518. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98519. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98520. );
  98521. };
  98522. OIMO.BoxShape.prototype.updateProxy = function () {
  98523. var te = this.rotation.elements;
  98524. var di = this.dimentions;
  98525. // Width
  98526. di[0] = te[0];
  98527. di[1] = te[3];
  98528. di[2] = te[6];
  98529. // Height
  98530. di[3] = te[1];
  98531. di[4] = te[4];
  98532. di[5] = te[7];
  98533. // Depth
  98534. di[6] = te[2];
  98535. di[7] = te[5];
  98536. di[8] = te[8];
  98537. // halp Width
  98538. di[9] = te[0] * this.halfWidth;
  98539. di[10] = te[3] * this.halfWidth;
  98540. di[11] = te[6] * this.halfWidth;
  98541. // halp Height
  98542. di[12] = te[1] * this.halfHeight;
  98543. di[13] = te[4] * this.halfHeight;
  98544. di[14] = te[7] * this.halfHeight;
  98545. // halp Depth
  98546. di[15] = te[2] * this.halfDepth;
  98547. di[16] = te[5] * this.halfDepth;
  98548. di[17] = te[8] * this.halfDepth;
  98549. var wx = di[9];
  98550. var wy = di[10];
  98551. var wz = di[11];
  98552. var hx = di[12];
  98553. var hy = di[13];
  98554. var hz = di[14];
  98555. var dx = di[15];
  98556. var dy = di[16];
  98557. var dz = di[17];
  98558. var x = this.position.x;
  98559. var y = this.position.y;
  98560. var z = this.position.z;
  98561. var v = this.elements;
  98562. //v1
  98563. v[0] = x + wx + hx + dx;
  98564. v[1] = y + wy + hy + dy;
  98565. v[2] = z + wz + hz + dz;
  98566. //v2
  98567. v[3] = x + wx + hx - dx;
  98568. v[4] = y + wy + hy - dy;
  98569. v[5] = z + wz + hz - dz;
  98570. //v3
  98571. v[6] = x + wx - hx + dx;
  98572. v[7] = y + wy - hy + dy;
  98573. v[8] = z + wz - hz + dz;
  98574. //v4
  98575. v[9] = x + wx - hx - dx;
  98576. v[10] = y + wy - hy - dy;
  98577. v[11] = z + wz - hz - dz;
  98578. //v5
  98579. v[12] = x - wx + hx + dx;
  98580. v[13] = y - wy + hy + dy;
  98581. v[14] = z - wz + hz + dz;
  98582. //v6
  98583. v[15] = x - wx + hx - dx;
  98584. v[16] = y - wy + hy - dy;
  98585. v[17] = z - wz + hz - dz;
  98586. //v7
  98587. v[18] = x - wx - hx + dx;
  98588. v[19] = y - wy - hy + dy;
  98589. v[20] = z - wz - hz + dz;
  98590. //v8
  98591. v[21] = x - wx - hx - dx;
  98592. v[22] = y - wy - hy - dy;
  98593. v[23] = z - wz - hz - dz;
  98594. var w = di[9] < 0 ? -di[9] : di[9];
  98595. var h = di[10] < 0 ? -di[10] : di[10];
  98596. var d = di[11] < 0 ? -di[11] : di[11];
  98597. w = di[12] < 0 ? w - di[12] : w + di[12];
  98598. h = di[13] < 0 ? h - di[13] : h + di[13];
  98599. d = di[14] < 0 ? d - di[14] : d + di[14];
  98600. w = di[15] < 0 ? w - di[15] : w + di[15];
  98601. h = di[16] < 0 ? h - di[16] : h + di[16];
  98602. d = di[17] < 0 ? d - di[17] : d + di[17];
  98603. var p = OIMO.AABB_PROX;
  98604. this.aabb.set(
  98605. this.position.x - w - p, this.position.x + w + p,
  98606. this.position.y - h - p, this.position.y + h + p,
  98607. this.position.z - d - p, this.position.z + d + p
  98608. );
  98609. if (this.proxy != null) this.proxy.update();
  98610. };
  98611. /**
  98612. * A sphere shape.
  98613. * @author saharan
  98614. * @author lo-th
  98615. */
  98616. OIMO.SphereShape = function (config, radius) {
  98617. OIMO.Shape.call(this, config);
  98618. this.type = OIMO.SHAPE_SPHERE;
  98619. // The radius of the shape.
  98620. this.radius = radius;
  98621. };
  98622. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98623. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98624. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98625. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98626. out.mass = mass;
  98627. var inertia = mass * this.radius * this.radius * 0.4;
  98628. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98629. };
  98630. OIMO.SphereShape.prototype.updateProxy = function () {
  98631. var p = OIMO.AABB_PROX;
  98632. this.aabb.set(
  98633. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98634. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98635. this.position.z - this.radius - p, this.position.z + this.radius + p
  98636. );
  98637. if (this.proxy != null) this.proxy.update();
  98638. };
  98639. /**
  98640. * A cylinder shap.
  98641. * @author saharan
  98642. * @author lo-th
  98643. */
  98644. OIMO.CylinderShape = function (config, radius, height) {
  98645. OIMO.Shape.call(this, config);
  98646. this.type = OIMO.SHAPE_CYLINDER;
  98647. this.radius = radius;
  98648. this.height = height;
  98649. this.halfHeight = height * 0.5;
  98650. this.normalDirection = new OIMO.Vec3();
  98651. this.halfDirection = new OIMO.Vec3();
  98652. };
  98653. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98654. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98655. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98656. var rsq = this.radius * this.radius;
  98657. var mass = OIMO.PI * rsq * this.height * this.density;
  98658. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98659. var inertiaY = 0.5 * rsq;
  98660. out.mass = mass;
  98661. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98662. };
  98663. OIMO.CylinderShape.prototype.updateProxy = function () {
  98664. var te = this.rotation.elements;
  98665. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98666. xx = te[1] * te[1];
  98667. yy = te[4] * te[4];
  98668. zz = te[7] * te[7];
  98669. this.normalDirection.set(te[1], te[4], te[7]);
  98670. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98671. wx = 1 - xx;
  98672. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98673. if (len > 0) len = this.radius / len;
  98674. wx *= len;
  98675. hy = 1 - yy;
  98676. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98677. if (len > 0) len = this.radius / len;
  98678. hy *= len;
  98679. dz = 1 - zz;
  98680. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98681. if (len > 0) len = this.radius / len;
  98682. dz *= len;
  98683. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98684. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98685. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98686. w = wx < 0 ? w - wx : w + wx;
  98687. h = hy < 0 ? h - hy : h + hy;
  98688. d = dz < 0 ? d - dz : d + dz;
  98689. p = OIMO.AABB_PROX;
  98690. this.aabb.set(
  98691. this.position.x - w - p, this.position.x + w + p,
  98692. this.position.y - h - p, this.position.y + h + p,
  98693. this.position.z - d - p, this.position.z + d + p
  98694. );
  98695. if (this.proxy != null) this.proxy.update();
  98696. };
  98697. /**
  98698. * A tetra shape.
  98699. * @author xprogram
  98700. */
  98701. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98702. OIMO.Shape.call(this, config);
  98703. this.type = OIMO.SHAPE_TETRA;
  98704. // Vertices and faces of tetra
  98705. this.verts = [p1, p2, p3, p4];
  98706. this.faces = [
  98707. mtri(0, 1, 2),
  98708. mtri(1, 2, 3),
  98709. mtri(2, 3, 4),
  98710. mtri(4, 0, 1),
  98711. ];
  98712. };
  98713. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98714. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98715. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98716. // I guess you could calculate box mass and split it
  98717. // in half for the tetra...
  98718. };
  98719. OIMO.TetraShape.prototype.updateProxy = function () {
  98720. this.aabb.setFromPoints(this.verts);
  98721. if (this.proxy !== null)
  98722. this.proxy.update();
  98723. };
  98724. function mtri(a, b, c) {
  98725. return { a: a, b: b, c: c };
  98726. }
  98727. OIMO.CollisionDetector = function () {
  98728. this.flip = false;
  98729. };
  98730. OIMO.CollisionDetector.prototype = {
  98731. constructor: OIMO.CollisionDetector,
  98732. detectCollision: function (shape1, shape2, manifold) {
  98733. OIMO.Error("CollisionDetector", "Inheritance error.");
  98734. }
  98735. };
  98736. /**
  98737. * A collision detector which detects collisions between two boxes.
  98738. * @author saharan
  98739. */
  98740. OIMO.BoxBoxCollisionDetector = function () {
  98741. OIMO.CollisionDetector.call(this);
  98742. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  98743. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  98744. this.used = new OIMO_ARRAY_TYPE(8);
  98745. this.INF = 1 / 0;
  98746. };
  98747. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98748. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  98749. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98750. // What you are doing
  98751. // · I to prepare a separate axis of the fifteen
  98752. //-Six in each of three normal vectors of the xyz direction of the box both
  98753. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  98754. // · Calculate the depth to the separation axis
  98755. // Calculates the distance using the inner product and put the amount of embedment
  98756. // · However a vertical separation axis and side to weight a little to avoid vibration
  98757. // And end when there is a separate axis that is remote even one
  98758. // · I look for separation axis with little to dent most
  98759. // Men and if separation axis of the first six - end collision
  98760. // Heng If it separate axis of nine other - side collision
  98761. // Heng - case of a side collision
  98762. // · Find points of two sides on which you made ​​the separation axis
  98763. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  98764. //-Surface - the case of the plane crash
  98765. //-Box A, box B and the other a box of better made ​​a separate axis
  98766. // • 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
  98767. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  98768. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  98769. // • If more than one candidate 5 exists, scraping up to four
  98770. // For potential collision points of all, to examine the distance between the surface A
  98771. // • If you were on the inside surface of A, and the collision point
  98772. var b1;
  98773. var b2;
  98774. if (shape1.id < shape2.id) {
  98775. b1 = (shape1);
  98776. b2 = (shape2);
  98777. } else {
  98778. b1 = (shape2);
  98779. b2 = (shape1);
  98780. }
  98781. var V1 = b1.elements;
  98782. var V2 = b2.elements;
  98783. var D1 = b1.dimentions;
  98784. var D2 = b2.dimentions;
  98785. var p1 = b1.position;
  98786. var p2 = b2.position;
  98787. var p1x = p1.x;
  98788. var p1y = p1.y;
  98789. var p1z = p1.z;
  98790. var p2x = p2.x;
  98791. var p2y = p2.y;
  98792. var p2z = p2.z;
  98793. // diff
  98794. var dx = p2x - p1x;
  98795. var dy = p2y - p1y;
  98796. var dz = p2z - p1z;
  98797. // distance
  98798. var w1 = b1.halfWidth;
  98799. var h1 = b1.halfHeight;
  98800. var d1 = b1.halfDepth;
  98801. var w2 = b2.halfWidth;
  98802. var h2 = b2.halfHeight;
  98803. var d2 = b2.halfDepth;
  98804. // direction
  98805. // ----------------------------
  98806. // 15 separating axes
  98807. // 1~6: face
  98808. // 7~f: edge
  98809. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  98810. // ----------------------------
  98811. var a1x = D1[0];
  98812. var a1y = D1[1];
  98813. var a1z = D1[2];
  98814. var a2x = D1[3];
  98815. var a2y = D1[4];
  98816. var a2z = D1[5];
  98817. var a3x = D1[6];
  98818. var a3y = D1[7];
  98819. var a3z = D1[8];
  98820. var d1x = D1[9];
  98821. var d1y = D1[10];
  98822. var d1z = D1[11];
  98823. var d2x = D1[12];
  98824. var d2y = D1[13];
  98825. var d2z = D1[14];
  98826. var d3x = D1[15];
  98827. var d3y = D1[16];
  98828. var d3z = D1[17];
  98829. var a4x = D2[0];
  98830. var a4y = D2[1];
  98831. var a4z = D2[2];
  98832. var a5x = D2[3];
  98833. var a5y = D2[4];
  98834. var a5z = D2[5];
  98835. var a6x = D2[6];
  98836. var a6y = D2[7];
  98837. var a6z = D2[8];
  98838. var d4x = D2[9];
  98839. var d4y = D2[10];
  98840. var d4z = D2[11];
  98841. var d5x = D2[12];
  98842. var d5y = D2[13];
  98843. var d5z = D2[14];
  98844. var d6x = D2[15];
  98845. var d6y = D2[16];
  98846. var d6z = D2[17];
  98847. var a7x = a1y * a4z - a1z * a4y;
  98848. var a7y = a1z * a4x - a1x * a4z;
  98849. var a7z = a1x * a4y - a1y * a4x;
  98850. var a8x = a1y * a5z - a1z * a5y;
  98851. var a8y = a1z * a5x - a1x * a5z;
  98852. var a8z = a1x * a5y - a1y * a5x;
  98853. var a9x = a1y * a6z - a1z * a6y;
  98854. var a9y = a1z * a6x - a1x * a6z;
  98855. var a9z = a1x * a6y - a1y * a6x;
  98856. var aax = a2y * a4z - a2z * a4y;
  98857. var aay = a2z * a4x - a2x * a4z;
  98858. var aaz = a2x * a4y - a2y * a4x;
  98859. var abx = a2y * a5z - a2z * a5y;
  98860. var aby = a2z * a5x - a2x * a5z;
  98861. var abz = a2x * a5y - a2y * a5x;
  98862. var acx = a2y * a6z - a2z * a6y;
  98863. var acy = a2z * a6x - a2x * a6z;
  98864. var acz = a2x * a6y - a2y * a6x;
  98865. var adx = a3y * a4z - a3z * a4y;
  98866. var ady = a3z * a4x - a3x * a4z;
  98867. var adz = a3x * a4y - a3y * a4x;
  98868. var aex = a3y * a5z - a3z * a5y;
  98869. var aey = a3z * a5x - a3x * a5z;
  98870. var aez = a3x * a5y - a3y * a5x;
  98871. var afx = a3y * a6z - a3z * a6y;
  98872. var afy = a3z * a6x - a3x * a6z;
  98873. var afz = a3x * a6y - a3y * a6x;
  98874. // right or left flags
  98875. var right1;
  98876. var right2;
  98877. var right3;
  98878. var right4;
  98879. var right5;
  98880. var right6;
  98881. var right7;
  98882. var right8;
  98883. var right9;
  98884. var righta;
  98885. var rightb;
  98886. var rightc;
  98887. var rightd;
  98888. var righte;
  98889. var rightf;
  98890. // overlapping distances
  98891. var overlap1;
  98892. var overlap2;
  98893. var overlap3;
  98894. var overlap4;
  98895. var overlap5;
  98896. var overlap6;
  98897. var overlap7;
  98898. var overlap8;
  98899. var overlap9;
  98900. var overlapa;
  98901. var overlapb;
  98902. var overlapc;
  98903. var overlapd;
  98904. var overlape;
  98905. var overlapf;
  98906. // invalid flags
  98907. var invalid7 = false;
  98908. var invalid8 = false;
  98909. var invalid9 = false;
  98910. var invalida = false;
  98911. var invalidb = false;
  98912. var invalidc = false;
  98913. var invalidd = false;
  98914. var invalide = false;
  98915. var invalidf = false;
  98916. // temporary variables
  98917. var len;
  98918. var len1;
  98919. var len2;
  98920. var dot1;
  98921. var dot2;
  98922. var dot3;
  98923. // try axis 1
  98924. len = a1x * dx + a1y * dy + a1z * dz;
  98925. right1 = len > 0;
  98926. if (!right1) len = -len;
  98927. len1 = w1;
  98928. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  98929. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  98930. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  98931. if (dot1 < 0) dot1 = -dot1;
  98932. if (dot2 < 0) dot2 = -dot2;
  98933. if (dot3 < 0) dot3 = -dot3;
  98934. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98935. overlap1 = len - len1 - len2;
  98936. if (overlap1 > 0) return;
  98937. // try axis 2
  98938. len = a2x * dx + a2y * dy + a2z * dz;
  98939. right2 = len > 0;
  98940. if (!right2) len = -len;
  98941. len1 = h1;
  98942. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  98943. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  98944. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  98945. if (dot1 < 0) dot1 = -dot1;
  98946. if (dot2 < 0) dot2 = -dot2;
  98947. if (dot3 < 0) dot3 = -dot3;
  98948. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98949. overlap2 = len - len1 - len2;
  98950. if (overlap2 > 0) return;
  98951. // try axis 3
  98952. len = a3x * dx + a3y * dy + a3z * dz;
  98953. right3 = len > 0;
  98954. if (!right3) len = -len;
  98955. len1 = d1;
  98956. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  98957. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  98958. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  98959. if (dot1 < 0) dot1 = -dot1;
  98960. if (dot2 < 0) dot2 = -dot2;
  98961. if (dot3 < 0) dot3 = -dot3;
  98962. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98963. overlap3 = len - len1 - len2;
  98964. if (overlap3 > 0) return;
  98965. // try axis 4
  98966. len = a4x * dx + a4y * dy + a4z * dz;
  98967. right4 = len > 0;
  98968. if (!right4) len = -len;
  98969. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  98970. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  98971. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  98972. if (dot1 < 0) dot1 = -dot1;
  98973. if (dot2 < 0) dot2 = -dot2;
  98974. if (dot3 < 0) dot3 = -dot3;
  98975. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98976. len2 = w2;
  98977. overlap4 = (len - len1 - len2) * 1.0;
  98978. if (overlap4 > 0) return;
  98979. // try axis 5
  98980. len = a5x * dx + a5y * dy + a5z * dz;
  98981. right5 = len > 0;
  98982. if (!right5) len = -len;
  98983. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  98984. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  98985. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  98986. if (dot1 < 0) dot1 = -dot1;
  98987. if (dot2 < 0) dot2 = -dot2;
  98988. if (dot3 < 0) dot3 = -dot3;
  98989. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98990. len2 = h2;
  98991. overlap5 = (len - len1 - len2) * 1.0;
  98992. if (overlap5 > 0) return;
  98993. // try axis 6
  98994. len = a6x * dx + a6y * dy + a6z * dz;
  98995. right6 = len > 0;
  98996. if (!right6) len = -len;
  98997. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  98998. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  98999. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99000. if (dot1 < 0) dot1 = -dot1;
  99001. if (dot2 < 0) dot2 = -dot2;
  99002. if (dot3 < 0) dot3 = -dot3;
  99003. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99004. len2 = d2;
  99005. overlap6 = (len - len1 - len2) * 1.0;
  99006. if (overlap6 > 0) return;
  99007. // try axis 7
  99008. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99009. if (len > 1e-5) {
  99010. len = 1 / OIMO.sqrt(len);
  99011. a7x *= len;
  99012. a7y *= len;
  99013. a7z *= len;
  99014. len = a7x * dx + a7y * dy + a7z * dz;
  99015. right7 = len > 0;
  99016. if (!right7) len = -len;
  99017. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99018. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99019. if (dot1 < 0) dot1 = -dot1;
  99020. if (dot2 < 0) dot2 = -dot2;
  99021. len1 = dot1 * h1 + dot2 * d1;
  99022. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99023. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99024. if (dot1 < 0) dot1 = -dot1;
  99025. if (dot2 < 0) dot2 = -dot2;
  99026. len2 = dot1 * h2 + dot2 * d2;
  99027. overlap7 = len - len1 - len2;
  99028. if (overlap7 > 0) return;
  99029. } else {
  99030. right7 = false;
  99031. overlap7 = 0;
  99032. invalid7 = true;
  99033. }
  99034. // try axis 8
  99035. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99036. if (len > 1e-5) {
  99037. len = 1 / OIMO.sqrt(len);
  99038. a8x *= len;
  99039. a8y *= len;
  99040. a8z *= len;
  99041. len = a8x * dx + a8y * dy + a8z * dz;
  99042. right8 = len > 0;
  99043. if (!right8) len = -len;
  99044. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99045. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99046. if (dot1 < 0) dot1 = -dot1;
  99047. if (dot2 < 0) dot2 = -dot2;
  99048. len1 = dot1 * h1 + dot2 * d1;
  99049. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99050. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99051. if (dot1 < 0) dot1 = -dot1;
  99052. if (dot2 < 0) dot2 = -dot2;
  99053. len2 = dot1 * w2 + dot2 * d2;
  99054. overlap8 = len - len1 - len2;
  99055. if (overlap8 > 0) return;
  99056. } else {
  99057. right8 = false;
  99058. overlap8 = 0;
  99059. invalid8 = true;
  99060. }
  99061. // try axis 9
  99062. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99063. if (len > 1e-5) {
  99064. len = 1 / OIMO.sqrt(len);
  99065. a9x *= len;
  99066. a9y *= len;
  99067. a9z *= len;
  99068. len = a9x * dx + a9y * dy + a9z * dz;
  99069. right9 = len > 0;
  99070. if (!right9) len = -len;
  99071. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99072. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99073. if (dot1 < 0) dot1 = -dot1;
  99074. if (dot2 < 0) dot2 = -dot2;
  99075. len1 = dot1 * h1 + dot2 * d1;
  99076. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99077. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99078. if (dot1 < 0) dot1 = -dot1;
  99079. if (dot2 < 0) dot2 = -dot2;
  99080. len2 = dot1 * w2 + dot2 * h2;
  99081. overlap9 = len - len1 - len2;
  99082. if (overlap9 > 0) return;
  99083. } else {
  99084. right9 = false;
  99085. overlap9 = 0;
  99086. invalid9 = true;
  99087. }
  99088. // try axis 10
  99089. len = aax * aax + aay * aay + aaz * aaz;
  99090. if (len > 1e-5) {
  99091. len = 1 / OIMO.sqrt(len);
  99092. aax *= len;
  99093. aay *= len;
  99094. aaz *= len;
  99095. len = aax * dx + aay * dy + aaz * dz;
  99096. righta = len > 0;
  99097. if (!righta) len = -len;
  99098. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99099. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99100. if (dot1 < 0) dot1 = -dot1;
  99101. if (dot2 < 0) dot2 = -dot2;
  99102. len1 = dot1 * w1 + dot2 * d1;
  99103. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99104. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99105. if (dot1 < 0) dot1 = -dot1;
  99106. if (dot2 < 0) dot2 = -dot2;
  99107. len2 = dot1 * h2 + dot2 * d2;
  99108. overlapa = len - len1 - len2;
  99109. if (overlapa > 0) return;
  99110. } else {
  99111. righta = false;
  99112. overlapa = 0;
  99113. invalida = true;
  99114. }
  99115. // try axis 11
  99116. len = abx * abx + aby * aby + abz * abz;
  99117. if (len > 1e-5) {
  99118. len = 1 / OIMO.sqrt(len);
  99119. abx *= len;
  99120. aby *= len;
  99121. abz *= len;
  99122. len = abx * dx + aby * dy + abz * dz;
  99123. rightb = len > 0;
  99124. if (!rightb) len = -len;
  99125. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99126. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99127. if (dot1 < 0) dot1 = -dot1;
  99128. if (dot2 < 0) dot2 = -dot2;
  99129. len1 = dot1 * w1 + dot2 * d1;
  99130. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99131. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99132. if (dot1 < 0) dot1 = -dot1;
  99133. if (dot2 < 0) dot2 = -dot2;
  99134. len2 = dot1 * w2 + dot2 * d2;
  99135. overlapb = len - len1 - len2;
  99136. if (overlapb > 0) return;
  99137. } else {
  99138. rightb = false;
  99139. overlapb = 0;
  99140. invalidb = true;
  99141. }
  99142. // try axis 12
  99143. len = acx * acx + acy * acy + acz * acz;
  99144. if (len > 1e-5) {
  99145. len = 1 / OIMO.sqrt(len);
  99146. acx *= len;
  99147. acy *= len;
  99148. acz *= len;
  99149. len = acx * dx + acy * dy + acz * dz;
  99150. rightc = len > 0;
  99151. if (!rightc) len = -len;
  99152. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99153. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99154. if (dot1 < 0) dot1 = -dot1;
  99155. if (dot2 < 0) dot2 = -dot2;
  99156. len1 = dot1 * w1 + dot2 * d1;
  99157. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99158. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99159. if (dot1 < 0) dot1 = -dot1;
  99160. if (dot2 < 0) dot2 = -dot2;
  99161. len2 = dot1 * w2 + dot2 * h2;
  99162. overlapc = len - len1 - len2;
  99163. if (overlapc > 0) return;
  99164. } else {
  99165. rightc = false;
  99166. overlapc = 0;
  99167. invalidc = true;
  99168. }
  99169. // try axis 13
  99170. len = adx * adx + ady * ady + adz * adz;
  99171. if (len > 1e-5) {
  99172. len = 1 / OIMO.sqrt(len);
  99173. adx *= len;
  99174. ady *= len;
  99175. adz *= len;
  99176. len = adx * dx + ady * dy + adz * dz;
  99177. rightd = len > 0;
  99178. if (!rightd) len = -len;
  99179. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99180. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99181. if (dot1 < 0) dot1 = -dot1;
  99182. if (dot2 < 0) dot2 = -dot2;
  99183. len1 = dot1 * w1 + dot2 * h1;
  99184. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99185. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99186. if (dot1 < 0) dot1 = -dot1;
  99187. if (dot2 < 0) dot2 = -dot2;
  99188. len2 = dot1 * h2 + dot2 * d2;
  99189. overlapd = len - len1 - len2;
  99190. if (overlapd > 0) return;
  99191. } else {
  99192. rightd = false;
  99193. overlapd = 0;
  99194. invalidd = true;
  99195. }
  99196. // try axis 14
  99197. len = aex * aex + aey * aey + aez * aez;
  99198. if (len > 1e-5) {
  99199. len = 1 / OIMO.sqrt(len);
  99200. aex *= len;
  99201. aey *= len;
  99202. aez *= len;
  99203. len = aex * dx + aey * dy + aez * dz;
  99204. righte = len > 0;
  99205. if (!righte) len = -len;
  99206. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99207. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99208. if (dot1 < 0) dot1 = -dot1;
  99209. if (dot2 < 0) dot2 = -dot2;
  99210. len1 = dot1 * w1 + dot2 * h1;
  99211. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99212. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99213. if (dot1 < 0) dot1 = -dot1;
  99214. if (dot2 < 0) dot2 = -dot2;
  99215. len2 = dot1 * w2 + dot2 * d2;
  99216. overlape = len - len1 - len2;
  99217. if (overlape > 0) return;
  99218. } else {
  99219. righte = false;
  99220. overlape = 0;
  99221. invalide = true;
  99222. }
  99223. // try axis 15
  99224. len = afx * afx + afy * afy + afz * afz;
  99225. if (len > 1e-5) {
  99226. len = 1 / OIMO.sqrt(len);
  99227. afx *= len;
  99228. afy *= len;
  99229. afz *= len;
  99230. len = afx * dx + afy * dy + afz * dz;
  99231. rightf = len > 0;
  99232. if (!rightf) len = -len;
  99233. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99234. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99235. if (dot1 < 0) dot1 = -dot1;
  99236. if (dot2 < 0) dot2 = -dot2;
  99237. len1 = dot1 * w1 + dot2 * h1;
  99238. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99239. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99240. if (dot1 < 0) dot1 = -dot1;
  99241. if (dot2 < 0) dot2 = -dot2;
  99242. len2 = dot1 * w2 + dot2 * h2;
  99243. overlapf = len - len1 - len2;
  99244. if (overlapf > 0) return;
  99245. } else {
  99246. rightf = false;
  99247. overlapf = 0;
  99248. invalidf = true;
  99249. }
  99250. // boxes are overlapping
  99251. var depth = overlap1;
  99252. var depth2 = overlap1;
  99253. var minIndex = 0;
  99254. var right = right1;
  99255. if (overlap2 > depth2) {
  99256. depth = overlap2;
  99257. depth2 = overlap2;
  99258. minIndex = 1;
  99259. right = right2;
  99260. }
  99261. if (overlap3 > depth2) {
  99262. depth = overlap3;
  99263. depth2 = overlap3;
  99264. minIndex = 2;
  99265. right = right3;
  99266. }
  99267. if (overlap4 > depth2) {
  99268. depth = overlap4;
  99269. depth2 = overlap4;
  99270. minIndex = 3;
  99271. right = right4;
  99272. }
  99273. if (overlap5 > depth2) {
  99274. depth = overlap5;
  99275. depth2 = overlap5;
  99276. minIndex = 4;
  99277. right = right5;
  99278. }
  99279. if (overlap6 > depth2) {
  99280. depth = overlap6;
  99281. depth2 = overlap6;
  99282. minIndex = 5;
  99283. right = right6;
  99284. }
  99285. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99286. depth = overlap7;
  99287. depth2 = overlap7 - 0.01;
  99288. minIndex = 6;
  99289. right = right7;
  99290. }
  99291. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99292. depth = overlap8;
  99293. depth2 = overlap8 - 0.01;
  99294. minIndex = 7;
  99295. right = right8;
  99296. }
  99297. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99298. depth = overlap9;
  99299. depth2 = overlap9 - 0.01;
  99300. minIndex = 8;
  99301. right = right9;
  99302. }
  99303. if (overlapa - 0.01 > depth2 && !invalida) {
  99304. depth = overlapa;
  99305. depth2 = overlapa - 0.01;
  99306. minIndex = 9;
  99307. right = righta;
  99308. }
  99309. if (overlapb - 0.01 > depth2 && !invalidb) {
  99310. depth = overlapb;
  99311. depth2 = overlapb - 0.01;
  99312. minIndex = 10;
  99313. right = rightb;
  99314. }
  99315. if (overlapc - 0.01 > depth2 && !invalidc) {
  99316. depth = overlapc;
  99317. depth2 = overlapc - 0.01;
  99318. minIndex = 11;
  99319. right = rightc;
  99320. }
  99321. if (overlapd - 0.01 > depth2 && !invalidd) {
  99322. depth = overlapd;
  99323. depth2 = overlapd - 0.01;
  99324. minIndex = 12;
  99325. right = rightd;
  99326. }
  99327. if (overlape - 0.01 > depth2 && !invalide) {
  99328. depth = overlape;
  99329. depth2 = overlape - 0.01;
  99330. minIndex = 13;
  99331. right = righte;
  99332. }
  99333. if (overlapf - 0.01 > depth2 && !invalidf) {
  99334. depth = overlapf;
  99335. minIndex = 14;
  99336. right = rightf;
  99337. }
  99338. // normal
  99339. var nx = 0;
  99340. var ny = 0;
  99341. var nz = 0;
  99342. // edge line or face side normal
  99343. var n1x = 0;
  99344. var n1y = 0;
  99345. var n1z = 0;
  99346. var n2x = 0;
  99347. var n2y = 0;
  99348. var n2z = 0;
  99349. // center of current face
  99350. var cx = 0;
  99351. var cy = 0;
  99352. var cz = 0;
  99353. // face side
  99354. var s1x = 0;
  99355. var s1y = 0;
  99356. var s1z = 0;
  99357. var s2x = 0;
  99358. var s2y = 0;
  99359. var s2z = 0;
  99360. // swap b1 b2
  99361. var swap = false;
  99362. //_______________________________________
  99363. if (minIndex == 0) {// b1.x * b2
  99364. if (right) {
  99365. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99366. nx = a1x; ny = a1y; nz = a1z;
  99367. } else {
  99368. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99369. nx = -a1x; ny = -a1y; nz = -a1z;
  99370. }
  99371. s1x = d2x; s1y = d2y; s1z = d2z;
  99372. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99373. s2x = d3x; s2y = d3y; s2z = d3z;
  99374. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99375. }
  99376. else if (minIndex == 1) {// b1.y * b2
  99377. if (right) {
  99378. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99379. nx = a2x; ny = a2y; nz = a2z;
  99380. } else {
  99381. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99382. nx = -a2x; ny = -a2y; nz = -a2z;
  99383. }
  99384. s1x = d1x; s1y = d1y; s1z = d1z;
  99385. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99386. s2x = d3x; s2y = d3y; s2z = d3z;
  99387. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99388. }
  99389. else if (minIndex == 2) {// b1.z * b2
  99390. if (right) {
  99391. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99392. nx = a3x; ny = a3y; nz = a3z;
  99393. } else {
  99394. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99395. nx = -a3x; ny = -a3y; nz = -a3z;
  99396. }
  99397. s1x = d1x; s1y = d1y; s1z = d1z;
  99398. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99399. s2x = d2x; s2y = d2y; s2z = d2z;
  99400. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99401. }
  99402. else if (minIndex == 3) {// b2.x * b1
  99403. swap = true;
  99404. if (!right) {
  99405. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99406. nx = a4x; ny = a4y; nz = a4z;
  99407. } else {
  99408. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99409. nx = -a4x; ny = -a4y; nz = -a4z;
  99410. }
  99411. s1x = d5x; s1y = d5y; s1z = d5z;
  99412. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99413. s2x = d6x; s2y = d6y; s2z = d6z;
  99414. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99415. }
  99416. else if (minIndex == 4) {// b2.y * b1
  99417. swap = true;
  99418. if (!right) {
  99419. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99420. nx = a5x; ny = a5y; nz = a5z;
  99421. } else {
  99422. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99423. nx = -a5x; ny = -a5y; nz = -a5z;
  99424. }
  99425. s1x = d4x; s1y = d4y; s1z = d4z;
  99426. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99427. s2x = d6x; s2y = d6y; s2z = d6z;
  99428. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99429. }
  99430. else if (minIndex == 5) {// b2.z * b1
  99431. swap = true;
  99432. if (!right) {
  99433. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99434. nx = a6x; ny = a6y; nz = a6z;
  99435. } else {
  99436. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99437. nx = -a6x; ny = -a6y; nz = -a6z;
  99438. }
  99439. s1x = d4x; s1y = d4y; s1z = d4z;
  99440. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99441. s2x = d5x; s2y = d5y; s2z = d5z;
  99442. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99443. }
  99444. else if (minIndex == 6) {// b1.x * b2.x
  99445. nx = a7x; ny = a7y; nz = a7z;
  99446. n1x = a1x; n1y = a1y; n1z = a1z;
  99447. n2x = a4x; n2y = a4y; n2z = a4z;
  99448. }
  99449. else if (minIndex == 7) {// b1.x * b2.y
  99450. nx = a8x; ny = a8y; nz = a8z;
  99451. n1x = a1x; n1y = a1y; n1z = a1z;
  99452. n2x = a5x; n2y = a5y; n2z = a5z;
  99453. }
  99454. else if (minIndex == 8) {// b1.x * b2.z
  99455. nx = a9x; ny = a9y; nz = a9z;
  99456. n1x = a1x; n1y = a1y; n1z = a1z;
  99457. n2x = a6x; n2y = a6y; n2z = a6z;
  99458. }
  99459. else if (minIndex == 9) {// b1.y * b2.x
  99460. nx = aax; ny = aay; nz = aaz;
  99461. n1x = a2x; n1y = a2y; n1z = a2z;
  99462. n2x = a4x; n2y = a4y; n2z = a4z
  99463. }
  99464. else if (minIndex == 10) {// b1.y * b2.y
  99465. nx = abx; ny = aby; nz = abz;
  99466. n1x = a2x; n1y = a2y; n1z = a2z;
  99467. n2x = a5x; n2y = a5y; n2z = a5z;
  99468. }
  99469. else if (minIndex == 11) {// b1.y * b2.z
  99470. nx = acx; ny = acy; nz = acz;
  99471. n1x = a2x; n1y = a2y; n1z = a2z;
  99472. n2x = a6x; n2y = a6y; n2z = a6z;
  99473. }
  99474. else if (minIndex == 12) {// b1.z * b2.x
  99475. nx = adx; ny = ady; nz = adz;
  99476. n1x = a3x; n1y = a3y; n1z = a3z;
  99477. n2x = a4x; n2y = a4y; n2z = a4z;
  99478. }
  99479. else if (minIndex == 13) {// b1.z * b2.y
  99480. nx = aex; ny = aey; nz = aez;
  99481. n1x = a3x; n1y = a3y; n1z = a3z;
  99482. n2x = a5x; n2y = a5y; n2z = a5z;
  99483. }
  99484. else if (minIndex == 14) {// b1.z * b2.z
  99485. nx = afx; ny = afy; nz = afz;
  99486. n1x = a3x; n1y = a3y; n1z = a3z;
  99487. n2x = a6x; n2y = a6y; n2z = a6z;
  99488. }
  99489. //__________________________________________
  99490. var v;
  99491. if (minIndex > 5) {
  99492. if (!right) {
  99493. nx = -nx; ny = -ny; nz = -nz;
  99494. }
  99495. var distance;
  99496. var maxDistance;
  99497. var vx;
  99498. var vy;
  99499. var vz;
  99500. var v1x;
  99501. var v1y;
  99502. var v1z;
  99503. var v2x;
  99504. var v2y;
  99505. var v2z;
  99506. //vertex1;
  99507. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99508. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99509. //vertex2;
  99510. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99511. distance = nx * vx + ny * vy + nz * vz;
  99512. if (distance > maxDistance) {
  99513. maxDistance = distance;
  99514. v1x = vx; v1y = vy; v1z = vz;
  99515. }
  99516. //vertex3;
  99517. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99518. distance = nx * vx + ny * vy + nz * vz;
  99519. if (distance > maxDistance) {
  99520. maxDistance = distance;
  99521. v1x = vx; v1y = vy; v1z = vz;
  99522. }
  99523. //vertex4;
  99524. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99525. distance = nx * vx + ny * vy + nz * vz;
  99526. if (distance > maxDistance) {
  99527. maxDistance = distance;
  99528. v1x = vx; v1y = vy; v1z = vz;
  99529. }
  99530. //vertex5;
  99531. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99532. distance = nx * vx + ny * vy + nz * vz;
  99533. if (distance > maxDistance) {
  99534. maxDistance = distance;
  99535. v1x = vx; v1y = vy; v1z = vz;
  99536. }
  99537. //vertex6;
  99538. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99539. distance = nx * vx + ny * vy + nz * vz;
  99540. if (distance > maxDistance) {
  99541. maxDistance = distance;
  99542. v1x = vx; v1y = vy; v1z = vz;
  99543. }
  99544. //vertex7;
  99545. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99546. distance = nx * vx + ny * vy + nz * vz;
  99547. if (distance > maxDistance) {
  99548. maxDistance = distance;
  99549. v1x = vx; v1y = vy; v1z = vz;
  99550. }
  99551. //vertex8;
  99552. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99553. distance = nx * vx + ny * vy + nz * vz;
  99554. if (distance > maxDistance) {
  99555. maxDistance = distance;
  99556. v1x = vx; v1y = vy; v1z = vz;
  99557. }
  99558. //vertex1;
  99559. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99560. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99561. //vertex2;
  99562. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99563. distance = nx * vx + ny * vy + nz * vz;
  99564. if (distance < maxDistance) {
  99565. maxDistance = distance;
  99566. v2x = vx; v2y = vy; v2z = vz;
  99567. }
  99568. //vertex3;
  99569. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99570. distance = nx * vx + ny * vy + nz * vz;
  99571. if (distance < maxDistance) {
  99572. maxDistance = distance;
  99573. v2x = vx; v2y = vy; v2z = vz;
  99574. }
  99575. //vertex4;
  99576. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99577. distance = nx * vx + ny * vy + nz * vz;
  99578. if (distance < maxDistance) {
  99579. maxDistance = distance;
  99580. v2x = vx; v2y = vy; v2z = vz;
  99581. }
  99582. //vertex5;
  99583. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99584. distance = nx * vx + ny * vy + nz * vz;
  99585. if (distance < maxDistance) {
  99586. maxDistance = distance;
  99587. v2x = vx; v2y = vy; v2z = vz;
  99588. }
  99589. //vertex6;
  99590. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99591. distance = nx * vx + ny * vy + nz * vz;
  99592. if (distance < maxDistance) {
  99593. maxDistance = distance;
  99594. v2x = vx; v2y = vy; v2z = vz;
  99595. }
  99596. //vertex7;
  99597. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99598. distance = nx * vx + ny * vy + nz * vz;
  99599. if (distance < maxDistance) {
  99600. maxDistance = distance;
  99601. v2x = vx; v2y = vy; v2z = vz;
  99602. }
  99603. //vertex8;
  99604. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99605. distance = nx * vx + ny * vy + nz * vz;
  99606. if (distance < maxDistance) {
  99607. maxDistance = distance;
  99608. v2x = vx; v2y = vy; v2z = vz;
  99609. }
  99610. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99611. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99612. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99613. 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);
  99614. return;
  99615. }
  99616. // now detect face-face collision...
  99617. // target quad
  99618. var q1x;
  99619. var q1y;
  99620. var q1z;
  99621. var q2x;
  99622. var q2y;
  99623. var q2z;
  99624. var q3x;
  99625. var q3y;
  99626. var q3z;
  99627. var q4x;
  99628. var q4y;
  99629. var q4z;
  99630. // search support face and vertex
  99631. var minDot = 1;
  99632. var dot = 0;
  99633. var minDotIndex = 0;
  99634. if (swap) {
  99635. dot = a1x * nx + a1y * ny + a1z * nz;
  99636. if (dot < minDot) {
  99637. minDot = dot;
  99638. minDotIndex = 0;
  99639. }
  99640. if (-dot < minDot) {
  99641. minDot = -dot;
  99642. minDotIndex = 1;
  99643. }
  99644. dot = a2x * nx + a2y * ny + a2z * nz;
  99645. if (dot < minDot) {
  99646. minDot = dot;
  99647. minDotIndex = 2;
  99648. }
  99649. if (-dot < minDot) {
  99650. minDot = -dot;
  99651. minDotIndex = 3;
  99652. }
  99653. dot = a3x * nx + a3y * ny + a3z * nz;
  99654. if (dot < minDot) {
  99655. minDot = dot;
  99656. minDotIndex = 4;
  99657. }
  99658. if (-dot < minDot) {
  99659. minDot = -dot;
  99660. minDotIndex = 5;
  99661. }
  99662. if (minDotIndex == 0) {// x+ face
  99663. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99664. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99665. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99666. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99667. }
  99668. else if (minDotIndex == 1) {// x- face
  99669. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99670. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99671. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99672. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99673. }
  99674. else if (minDotIndex == 2) {// y+ face
  99675. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99676. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99677. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99678. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99679. }
  99680. else if (minDotIndex == 3) {// y- face
  99681. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99682. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99683. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99684. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99685. }
  99686. else if (minDotIndex == 4) {// z+ face
  99687. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99688. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99689. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99690. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99691. }
  99692. else if (minDotIndex == 5) {// z- face
  99693. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99694. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99695. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99696. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99697. }
  99698. } else {
  99699. dot = a4x * nx + a4y * ny + a4z * nz;
  99700. if (dot < minDot) {
  99701. minDot = dot;
  99702. minDotIndex = 0;
  99703. }
  99704. if (-dot < minDot) {
  99705. minDot = -dot;
  99706. minDotIndex = 1;
  99707. }
  99708. dot = a5x * nx + a5y * ny + a5z * nz;
  99709. if (dot < minDot) {
  99710. minDot = dot;
  99711. minDotIndex = 2;
  99712. }
  99713. if (-dot < minDot) {
  99714. minDot = -dot;
  99715. minDotIndex = 3;
  99716. }
  99717. dot = a6x * nx + a6y * ny + a6z * nz;
  99718. if (dot < minDot) {
  99719. minDot = dot;
  99720. minDotIndex = 4;
  99721. }
  99722. if (-dot < minDot) {
  99723. minDot = -dot;
  99724. minDotIndex = 5;
  99725. }
  99726. //______________________________________________________
  99727. if (minDotIndex == 0) {// x+ face
  99728. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  99729. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  99730. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  99731. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  99732. }
  99733. else if (minDotIndex == 1) {// x- face
  99734. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  99735. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  99736. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  99737. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  99738. }
  99739. else if (minDotIndex == 2) {// y+ face
  99740. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99741. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  99742. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  99743. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99744. }
  99745. else if (minDotIndex == 3) {// y- face
  99746. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  99747. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99748. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99749. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  99750. }
  99751. else if (minDotIndex == 4) {// z+ face
  99752. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99753. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  99754. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99755. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  99756. }
  99757. else if (minDotIndex == 5) {// z- face
  99758. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  99759. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99760. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  99761. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99762. }
  99763. }
  99764. // clip vertices
  99765. var numClipVertices;
  99766. var numAddedClipVertices;
  99767. var index;
  99768. var x1;
  99769. var y1;
  99770. var z1;
  99771. var x2;
  99772. var y2;
  99773. var z2;
  99774. this.clipVertices1[0] = q1x;
  99775. this.clipVertices1[1] = q1y;
  99776. this.clipVertices1[2] = q1z;
  99777. this.clipVertices1[3] = q2x;
  99778. this.clipVertices1[4] = q2y;
  99779. this.clipVertices1[5] = q2z;
  99780. this.clipVertices1[6] = q3x;
  99781. this.clipVertices1[7] = q3y;
  99782. this.clipVertices1[8] = q3z;
  99783. this.clipVertices1[9] = q4x;
  99784. this.clipVertices1[10] = q4y;
  99785. this.clipVertices1[11] = q4z;
  99786. numAddedClipVertices = 0;
  99787. x1 = this.clipVertices1[9];
  99788. y1 = this.clipVertices1[10];
  99789. z1 = this.clipVertices1[11];
  99790. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  99791. //var i = 4;
  99792. //while(i--){
  99793. for (var i = 0; i < 4; i++) {
  99794. index = i * 3;
  99795. x2 = this.clipVertices1[index];
  99796. y2 = this.clipVertices1[index + 1];
  99797. z2 = this.clipVertices1[index + 2];
  99798. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  99799. if (dot1 > 0) {
  99800. if (dot2 > 0) {
  99801. index = numAddedClipVertices * 3;
  99802. numAddedClipVertices++;
  99803. this.clipVertices2[index] = x2;
  99804. this.clipVertices2[index + 1] = y2;
  99805. this.clipVertices2[index + 2] = z2;
  99806. } else {
  99807. index = numAddedClipVertices * 3;
  99808. numAddedClipVertices++;
  99809. t = dot1 / (dot1 - dot2);
  99810. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99811. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99812. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99813. }
  99814. } else {
  99815. if (dot2 > 0) {
  99816. index = numAddedClipVertices * 3;
  99817. numAddedClipVertices++;
  99818. t = dot1 / (dot1 - dot2);
  99819. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99820. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99821. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99822. index = numAddedClipVertices * 3;
  99823. numAddedClipVertices++;
  99824. this.clipVertices2[index] = x2;
  99825. this.clipVertices2[index + 1] = y2;
  99826. this.clipVertices2[index + 2] = z2;
  99827. }
  99828. }
  99829. x1 = x2;
  99830. y1 = y2;
  99831. z1 = z2;
  99832. dot1 = dot2;
  99833. }
  99834. numClipVertices = numAddedClipVertices;
  99835. if (numClipVertices == 0) return;
  99836. numAddedClipVertices = 0;
  99837. index = (numClipVertices - 1) * 3;
  99838. x1 = this.clipVertices2[index];
  99839. y1 = this.clipVertices2[index + 1];
  99840. z1 = this.clipVertices2[index + 2];
  99841. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  99842. //i = numClipVertices;
  99843. //while(i--){
  99844. for (i = 0; i < numClipVertices; i++) {
  99845. index = i * 3;
  99846. x2 = this.clipVertices2[index];
  99847. y2 = this.clipVertices2[index + 1];
  99848. z2 = this.clipVertices2[index + 2];
  99849. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  99850. if (dot1 > 0) {
  99851. if (dot2 > 0) {
  99852. index = numAddedClipVertices * 3;
  99853. numAddedClipVertices++;
  99854. this.clipVertices1[index] = x2;
  99855. this.clipVertices1[index + 1] = y2;
  99856. this.clipVertices1[index + 2] = z2;
  99857. } else {
  99858. index = numAddedClipVertices * 3;
  99859. numAddedClipVertices++;
  99860. t = dot1 / (dot1 - dot2);
  99861. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99862. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99863. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99864. }
  99865. } else {
  99866. if (dot2 > 0) {
  99867. index = numAddedClipVertices * 3;
  99868. numAddedClipVertices++;
  99869. t = dot1 / (dot1 - dot2);
  99870. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99871. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99872. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99873. index = numAddedClipVertices * 3;
  99874. numAddedClipVertices++;
  99875. this.clipVertices1[index] = x2;
  99876. this.clipVertices1[index + 1] = y2;
  99877. this.clipVertices1[index + 2] = z2;
  99878. }
  99879. }
  99880. x1 = x2;
  99881. y1 = y2;
  99882. z1 = z2;
  99883. dot1 = dot2;
  99884. }
  99885. numClipVertices = numAddedClipVertices;
  99886. if (numClipVertices == 0) return;
  99887. numAddedClipVertices = 0;
  99888. index = (numClipVertices - 1) * 3;
  99889. x1 = this.clipVertices1[index];
  99890. y1 = this.clipVertices1[index + 1];
  99891. z1 = this.clipVertices1[index + 2];
  99892. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  99893. //i = numClipVertices;
  99894. //while(i--){
  99895. for (i = 0; i < numClipVertices; i++) {
  99896. index = i * 3;
  99897. x2 = this.clipVertices1[index];
  99898. y2 = this.clipVertices1[index + 1];
  99899. z2 = this.clipVertices1[index + 2];
  99900. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  99901. if (dot1 > 0) {
  99902. if (dot2 > 0) {
  99903. index = numAddedClipVertices * 3;
  99904. numAddedClipVertices++;
  99905. this.clipVertices2[index] = x2;
  99906. this.clipVertices2[index + 1] = y2;
  99907. this.clipVertices2[index + 2] = z2;
  99908. } else {
  99909. index = numAddedClipVertices * 3;
  99910. numAddedClipVertices++;
  99911. t = dot1 / (dot1 - dot2);
  99912. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99913. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99914. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99915. }
  99916. } else {
  99917. if (dot2 > 0) {
  99918. index = numAddedClipVertices * 3;
  99919. numAddedClipVertices++;
  99920. t = dot1 / (dot1 - dot2);
  99921. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99922. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99923. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99924. index = numAddedClipVertices * 3;
  99925. numAddedClipVertices++;
  99926. this.clipVertices2[index] = x2;
  99927. this.clipVertices2[index + 1] = y2;
  99928. this.clipVertices2[index + 2] = z2;
  99929. }
  99930. }
  99931. x1 = x2;
  99932. y1 = y2;
  99933. z1 = z2;
  99934. dot1 = dot2;
  99935. }
  99936. numClipVertices = numAddedClipVertices;
  99937. if (numClipVertices == 0) return;
  99938. numAddedClipVertices = 0;
  99939. index = (numClipVertices - 1) * 3;
  99940. x1 = this.clipVertices2[index];
  99941. y1 = this.clipVertices2[index + 1];
  99942. z1 = this.clipVertices2[index + 2];
  99943. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  99944. //i = numClipVertices;
  99945. //while(i--){
  99946. for (i = 0; i < numClipVertices; i++) {
  99947. index = i * 3;
  99948. x2 = this.clipVertices2[index];
  99949. y2 = this.clipVertices2[index + 1];
  99950. z2 = this.clipVertices2[index + 2];
  99951. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  99952. if (dot1 > 0) {
  99953. if (dot2 > 0) {
  99954. index = numAddedClipVertices * 3;
  99955. numAddedClipVertices++;
  99956. this.clipVertices1[index] = x2;
  99957. this.clipVertices1[index + 1] = y2;
  99958. this.clipVertices1[index + 2] = z2;
  99959. } else {
  99960. index = numAddedClipVertices * 3;
  99961. numAddedClipVertices++;
  99962. t = dot1 / (dot1 - dot2);
  99963. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99964. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99965. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99966. }
  99967. } else {
  99968. if (dot2 > 0) {
  99969. index = numAddedClipVertices * 3;
  99970. numAddedClipVertices++;
  99971. t = dot1 / (dot1 - dot2);
  99972. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99973. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99974. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99975. index = numAddedClipVertices * 3;
  99976. numAddedClipVertices++;
  99977. this.clipVertices1[index] = x2;
  99978. this.clipVertices1[index + 1] = y2;
  99979. this.clipVertices1[index + 2] = z2;
  99980. }
  99981. }
  99982. x1 = x2;
  99983. y1 = y2;
  99984. z1 = z2;
  99985. dot1 = dot2;
  99986. }
  99987. numClipVertices = numAddedClipVertices;
  99988. if (swap) {
  99989. var tb = b1;
  99990. b1 = b2;
  99991. b2 = tb;
  99992. }
  99993. if (numClipVertices == 0) return;
  99994. var flipped = b1 != shape1;
  99995. if (numClipVertices > 4) {
  99996. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  99997. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  99998. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  99999. n1x = q1x - x1;
  100000. n1y = q1y - y1;
  100001. n1z = q1z - z1;
  100002. n2x = q2x - x1;
  100003. n2y = q2y - y1;
  100004. n2z = q2z - z1;
  100005. var index1 = 0;
  100006. var index2 = 0;
  100007. var index3 = 0;
  100008. var index4 = 0;
  100009. var maxDot = -this.INF;
  100010. minDot = this.INF;
  100011. //i = numClipVertices;
  100012. //while(i--){
  100013. for (i = 0; i < numClipVertices; i++) {
  100014. this.used[i] = false;
  100015. index = i * 3;
  100016. x1 = this.clipVertices1[index];
  100017. y1 = this.clipVertices1[index + 1];
  100018. z1 = this.clipVertices1[index + 2];
  100019. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100020. if (dot < minDot) {
  100021. minDot = dot;
  100022. index1 = i;
  100023. }
  100024. if (dot > maxDot) {
  100025. maxDot = dot;
  100026. index3 = i;
  100027. }
  100028. }
  100029. this.used[index1] = true;
  100030. this.used[index3] = true;
  100031. maxDot = -this.INF;
  100032. minDot = this.INF;
  100033. //i = numClipVertices;
  100034. //while(i--){
  100035. for (i = 0; i < numClipVertices; i++) {
  100036. if (this.used[i]) continue;
  100037. index = i * 3;
  100038. x1 = this.clipVertices1[index];
  100039. y1 = this.clipVertices1[index + 1];
  100040. z1 = this.clipVertices1[index + 2];
  100041. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100042. if (dot < minDot) {
  100043. minDot = dot;
  100044. index2 = i;
  100045. }
  100046. if (dot > maxDot) {
  100047. maxDot = dot;
  100048. index4 = i;
  100049. }
  100050. }
  100051. index = index1 * 3;
  100052. x1 = this.clipVertices1[index];
  100053. y1 = this.clipVertices1[index + 1];
  100054. z1 = this.clipVertices1[index + 2];
  100055. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100056. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100057. index = index2 * 3;
  100058. x1 = this.clipVertices1[index];
  100059. y1 = this.clipVertices1[index + 1];
  100060. z1 = this.clipVertices1[index + 2];
  100061. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100062. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100063. index = index3 * 3;
  100064. x1 = this.clipVertices1[index];
  100065. y1 = this.clipVertices1[index + 1];
  100066. z1 = this.clipVertices1[index + 2];
  100067. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100068. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100069. index = index4 * 3;
  100070. x1 = this.clipVertices1[index];
  100071. y1 = this.clipVertices1[index + 1];
  100072. z1 = this.clipVertices1[index + 2];
  100073. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100074. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100075. } else {
  100076. //i = numClipVertices;
  100077. //while(i--){
  100078. for (i = 0; i < numClipVertices; i++) {
  100079. index = i * 3;
  100080. x1 = this.clipVertices1[index];
  100081. y1 = this.clipVertices1[index + 1];
  100082. z1 = this.clipVertices1[index + 2];
  100083. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100084. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100085. }
  100086. }
  100087. };
  100088. /**
  100089. * A collision detector which detects collisions between sphere and box.
  100090. * @author saharan
  100091. */
  100092. OIMO.SphereBoxCollisionDetector = function (flip) {
  100093. OIMO.CollisionDetector.call(this);
  100094. this.flip = flip;
  100095. };
  100096. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100097. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100098. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100099. var s;
  100100. var b;
  100101. if (this.flip) {
  100102. s = (shape2);
  100103. b = (shape1);
  100104. } else {
  100105. s = (shape1);
  100106. b = (shape2);
  100107. }
  100108. var D = b.dimentions;
  100109. var ps = s.position;
  100110. var psx = ps.x;
  100111. var psy = ps.y;
  100112. var psz = ps.z;
  100113. var pb = b.position;
  100114. var pbx = pb.x;
  100115. var pby = pb.y;
  100116. var pbz = pb.z;
  100117. var rad = s.radius;
  100118. var hw = b.halfWidth;
  100119. var hh = b.halfHeight;
  100120. var hd = b.halfDepth;
  100121. var dx = psx - pbx;
  100122. var dy = psy - pby;
  100123. var dz = psz - pbz;
  100124. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100125. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100126. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100127. var cx;
  100128. var cy;
  100129. var cz;
  100130. var len;
  100131. var invLen;
  100132. var overlap = 0;
  100133. if (sx > hw) {
  100134. sx = hw;
  100135. } else if (sx < -hw) {
  100136. sx = -hw;
  100137. } else {
  100138. overlap = 1;
  100139. }
  100140. if (sy > hh) {
  100141. sy = hh;
  100142. } else if (sy < -hh) {
  100143. sy = -hh;
  100144. } else {
  100145. overlap |= 2;
  100146. }
  100147. if (sz > hd) {
  100148. sz = hd;
  100149. } else if (sz < -hd) {
  100150. sz = -hd;
  100151. } else {
  100152. overlap |= 4;
  100153. }
  100154. if (overlap == 7) {
  100155. // center of sphere is in the box
  100156. if (sx < 0) {
  100157. dx = hw + sx;
  100158. } else {
  100159. dx = hw - sx;
  100160. }
  100161. if (sy < 0) {
  100162. dy = hh + sy;
  100163. } else {
  100164. dy = hh - sy;
  100165. }
  100166. if (sz < 0) {
  100167. dz = hd + sz;
  100168. } else {
  100169. dz = hd - sz;
  100170. }
  100171. if (dx < dy) {
  100172. if (dx < dz) {
  100173. len = dx - hw;
  100174. if (sx < 0) {
  100175. sx = -hw;
  100176. dx = D[0];
  100177. dy = D[1];
  100178. dz = D[2];
  100179. } else {
  100180. sx = hw;
  100181. dx = -D[0];
  100182. dy = -D[1];
  100183. dz = -D[2];
  100184. }
  100185. } else {
  100186. len = dz - hd;
  100187. if (sz < 0) {
  100188. sz = -hd;
  100189. dx = D[6];
  100190. dy = D[7];
  100191. dz = D[8];
  100192. } else {
  100193. sz = hd;
  100194. dx = -D[6];
  100195. dy = -D[7];
  100196. dz = -D[8];
  100197. }
  100198. }
  100199. } else {
  100200. if (dy < dz) {
  100201. len = dy - hh;
  100202. if (sy < 0) {
  100203. sy = -hh;
  100204. dx = D[3];
  100205. dy = D[4];
  100206. dz = D[5];
  100207. } else {
  100208. sy = hh;
  100209. dx = -D[3];
  100210. dy = -D[4];
  100211. dz = -D[5];
  100212. }
  100213. } else {
  100214. len = dz - hd;
  100215. if (sz < 0) {
  100216. sz = -hd;
  100217. dx = D[6];
  100218. dy = D[7];
  100219. dz = D[8];
  100220. } else {
  100221. sz = hd;
  100222. dx = -D[6];
  100223. dy = -D[7];
  100224. dz = -D[8];
  100225. }
  100226. }
  100227. }
  100228. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100229. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100230. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100231. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100232. } else {
  100233. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100234. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100235. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100236. dx = cx - ps.x;
  100237. dy = cy - ps.y;
  100238. dz = cz - ps.z;
  100239. len = dx * dx + dy * dy + dz * dz;
  100240. if (len > 0 && len < rad * rad) {
  100241. len = OIMO.sqrt(len);
  100242. invLen = 1 / len;
  100243. dx *= invLen;
  100244. dy *= invLen;
  100245. dz *= invLen;
  100246. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100247. }
  100248. }
  100249. };
  100250. /**
  100251. * A collision detector which detects collisions between two spheres.
  100252. * @author saharan
  100253. */
  100254. OIMO.SphereSphereCollisionDetector = function () {
  100255. OIMO.CollisionDetector.call(this);
  100256. };
  100257. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100258. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100259. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100260. var s1 = shape1;
  100261. var s2 = shape2;
  100262. var p1 = s1.position;
  100263. var p2 = s2.position;
  100264. var dx = p2.x - p1.x;
  100265. var dy = p2.y - p1.y;
  100266. var dz = p2.z - p1.z;
  100267. var len = dx * dx + dy * dy + dz * dz;
  100268. var r1 = s1.radius;
  100269. var r2 = s2.radius;
  100270. var rad = r1 + r2;
  100271. if (len > 0 && len < rad * rad) {
  100272. len = OIMO.sqrt(len);
  100273. var invLen = 1 / len;
  100274. dx *= invLen;
  100275. dy *= invLen;
  100276. dz *= invLen;
  100277. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100278. }
  100279. };
  100280. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100281. OIMO.CollisionDetector.call(this);
  100282. this.flip = flip;
  100283. };
  100284. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100285. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100286. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100287. var t1x;
  100288. var t1y;
  100289. var t1z;
  100290. var t2x;
  100291. var t2y;
  100292. var t2z;
  100293. var sup = new OIMO.Vec3();
  100294. var len;
  100295. var p1x;
  100296. var p1y;
  100297. var p1z;
  100298. var p2x;
  100299. var p2y;
  100300. var p2z;
  100301. var v01x = c1.position.x;
  100302. var v01y = c1.position.y;
  100303. var v01z = c1.position.z;
  100304. var v02x = c2.position.x;
  100305. var v02y = c2.position.y;
  100306. var v02z = c2.position.z;
  100307. var v0x = v02x - v01x;
  100308. var v0y = v02y - v01y;
  100309. var v0z = v02z - v01z;
  100310. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100311. var nx = -v0x;
  100312. var ny = -v0y;
  100313. var nz = -v0z;
  100314. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100315. var v11x = sup.x;
  100316. var v11y = sup.y;
  100317. var v11z = sup.z;
  100318. this.supportPointC(c2, nx, ny, nz, sup);
  100319. var v12x = sup.x;
  100320. var v12y = sup.y;
  100321. var v12z = sup.z;
  100322. var v1x = v12x - v11x;
  100323. var v1y = v12y - v11y;
  100324. var v1z = v12z - v11z;
  100325. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100326. return false;
  100327. }
  100328. nx = v1y * v0z - v1z * v0y;
  100329. ny = v1z * v0x - v1x * v0z;
  100330. nz = v1x * v0y - v1y * v0x;
  100331. if (nx * nx + ny * ny + nz * nz == 0) {
  100332. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100333. sep.normalize(sep);
  100334. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100335. return true;
  100336. }
  100337. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100338. var v21x = sup.x;
  100339. var v21y = sup.y;
  100340. var v21z = sup.z;
  100341. this.supportPointC(c2, nx, ny, nz, sup);
  100342. var v22x = sup.x;
  100343. var v22y = sup.y;
  100344. var v22z = sup.z;
  100345. var v2x = v22x - v21x;
  100346. var v2y = v22y - v21y;
  100347. var v2z = v22z - v21z;
  100348. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100349. return false;
  100350. }
  100351. t1x = v1x - v0x;
  100352. t1y = v1y - v0y;
  100353. t1z = v1z - v0z;
  100354. t2x = v2x - v0x;
  100355. t2y = v2y - v0y;
  100356. t2z = v2z - v0z;
  100357. nx = t1y * t2z - t1z * t2y;
  100358. ny = t1z * t2x - t1x * t2z;
  100359. nz = t1x * t2y - t1y * t2x;
  100360. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100361. t1x = v1x;
  100362. t1y = v1y;
  100363. t1z = v1z;
  100364. v1x = v2x;
  100365. v1y = v2y;
  100366. v1z = v2z;
  100367. v2x = t1x;
  100368. v2y = t1y;
  100369. v2z = t1z;
  100370. t1x = v11x;
  100371. t1y = v11y;
  100372. t1z = v11z;
  100373. v11x = v21x;
  100374. v11y = v21y;
  100375. v11z = v21z;
  100376. v21x = t1x;
  100377. v21y = t1y;
  100378. v21z = t1z;
  100379. t1x = v12x;
  100380. t1y = v12y;
  100381. t1z = v12z;
  100382. v12x = v22x;
  100383. v12y = v22y;
  100384. v12z = v22z;
  100385. v22x = t1x;
  100386. v22y = t1y;
  100387. v22z = t1z;
  100388. nx = -nx;
  100389. ny = -ny;
  100390. nz = -nz;
  100391. }
  100392. var iterations = 0;
  100393. while (true) {
  100394. if (++iterations > 100) {
  100395. return false;
  100396. }
  100397. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100398. var v31x = sup.x;
  100399. var v31y = sup.y;
  100400. var v31z = sup.z;
  100401. this.supportPointC(c2, nx, ny, nz, sup);
  100402. var v32x = sup.x;
  100403. var v32y = sup.y;
  100404. var v32z = sup.z;
  100405. var v3x = v32x - v31x;
  100406. var v3y = v32y - v31y;
  100407. var v3z = v32z - v31z;
  100408. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100409. return false;
  100410. }
  100411. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100412. v2x = v3x;
  100413. v2y = v3y;
  100414. v2z = v3z;
  100415. v21x = v31x;
  100416. v21y = v31y;
  100417. v21z = v31z;
  100418. v22x = v32x;
  100419. v22y = v32y;
  100420. v22z = v32z;
  100421. t1x = v1x - v0x;
  100422. t1y = v1y - v0y;
  100423. t1z = v1z - v0z;
  100424. t2x = v3x - v0x;
  100425. t2y = v3y - v0y;
  100426. t2z = v3z - v0z;
  100427. nx = t1y * t2z - t1z * t2y;
  100428. ny = t1z * t2x - t1x * t2z;
  100429. nz = t1x * t2y - t1y * t2x;
  100430. continue;
  100431. }
  100432. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100433. v1x = v3x;
  100434. v1y = v3y;
  100435. v1z = v3z;
  100436. v11x = v31x;
  100437. v11y = v31y;
  100438. v11z = v31z;
  100439. v12x = v32x;
  100440. v12y = v32y;
  100441. v12z = v32z;
  100442. t1x = v3x - v0x;
  100443. t1y = v3y - v0y;
  100444. t1z = v3z - v0z;
  100445. t2x = v2x - v0x;
  100446. t2y = v2y - v0y;
  100447. t2z = v2z - v0z;
  100448. nx = t1y * t2z - t1z * t2y;
  100449. ny = t1z * t2x - t1x * t2z;
  100450. nz = t1x * t2y - t1y * t2x;
  100451. continue;
  100452. }
  100453. var hit = false;
  100454. while (true) {
  100455. t1x = v2x - v1x;
  100456. t1y = v2y - v1y;
  100457. t1z = v2z - v1z;
  100458. t2x = v3x - v1x;
  100459. t2y = v3y - v1y;
  100460. t2z = v3z - v1z;
  100461. nx = t1y * t2z - t1z * t2y;
  100462. ny = t1z * t2x - t1x * t2z;
  100463. nz = t1x * t2y - t1y * t2x;
  100464. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100465. nx *= len;
  100466. ny *= len;
  100467. nz *= len;
  100468. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100469. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100470. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100471. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100472. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100473. var sum = b0 + b1 + b2 + b3;
  100474. if (sum <= 0) {
  100475. b0 = 0;
  100476. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100477. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100478. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100479. sum = b1 + b2 + b3;
  100480. }
  100481. var inv = 1 / sum;
  100482. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100483. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100484. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100485. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100486. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100487. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100488. hit = true;
  100489. }
  100490. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100491. var v41x = sup.x;
  100492. var v41y = sup.y;
  100493. var v41z = sup.z;
  100494. this.supportPointC(c2, nx, ny, nz, sup);
  100495. var v42x = sup.x;
  100496. var v42y = sup.y;
  100497. var v42z = sup.z;
  100498. var v4x = v42x - v41x;
  100499. var v4y = v42y - v41y;
  100500. var v4z = v42z - v41z;
  100501. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100502. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100503. if (hit) {
  100504. sep.init(-nx, -ny, -nz);
  100505. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100506. dep.x = separation;
  100507. return true;
  100508. }
  100509. return false;
  100510. }
  100511. if (
  100512. (v4y * v1z - v4z * v1y) * v0x +
  100513. (v4z * v1x - v4x * v1z) * v0y +
  100514. (v4x * v1y - v4y * v1x) * v0z < 0
  100515. ) {
  100516. if (
  100517. (v4y * v2z - v4z * v2y) * v0x +
  100518. (v4z * v2x - v4x * v2z) * v0y +
  100519. (v4x * v2y - v4y * v2x) * v0z < 0
  100520. ) {
  100521. v1x = v4x;
  100522. v1y = v4y;
  100523. v1z = v4z;
  100524. v11x = v41x;
  100525. v11y = v41y;
  100526. v11z = v41z;
  100527. v12x = v42x;
  100528. v12y = v42y;
  100529. v12z = v42z;
  100530. } else {
  100531. v3x = v4x;
  100532. v3y = v4y;
  100533. v3z = v4z;
  100534. v31x = v41x;
  100535. v31y = v41y;
  100536. v31z = v41z;
  100537. v32x = v42x;
  100538. v32y = v42y;
  100539. v32z = v42z;
  100540. }
  100541. } else {
  100542. if (
  100543. (v4y * v3z - v4z * v3y) * v0x +
  100544. (v4z * v3x - v4x * v3z) * v0y +
  100545. (v4x * v3y - v4y * v3x) * v0z < 0
  100546. ) {
  100547. v2x = v4x;
  100548. v2y = v4y;
  100549. v2z = v4z;
  100550. v21x = v41x;
  100551. v21y = v41y;
  100552. v21z = v41z;
  100553. v22x = v42x;
  100554. v22y = v42y;
  100555. v22z = v42z;
  100556. } else {
  100557. v1x = v4x;
  100558. v1y = v4y;
  100559. v1z = v4z;
  100560. v11x = v41x;
  100561. v11y = v41y;
  100562. v11z = v41z;
  100563. v12x = v42x;
  100564. v12y = v42y;
  100565. v12z = v42z;
  100566. }
  100567. }
  100568. }
  100569. }
  100570. //return false;
  100571. };
  100572. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100573. var rot = c.rotation.elements;
  100574. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100575. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100576. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100577. var w = c.halfWidth;
  100578. var h = c.halfHeight;
  100579. var d = c.halfDepth;
  100580. var ox;
  100581. var oy;
  100582. var oz;
  100583. if (ldx < 0) ox = -w;
  100584. else ox = w;
  100585. if (ldy < 0) oy = -h;
  100586. else oy = h;
  100587. if (ldz < 0) oz = -d;
  100588. else oz = d;
  100589. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100590. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100591. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100592. out.init(ldx, ldy, ldz);
  100593. };
  100594. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100595. var rot = c.rotation.elements;
  100596. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100597. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100598. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100599. var radx = ldx;
  100600. var radz = ldz;
  100601. var len = radx * radx + radz * radz;
  100602. var rad = c.radius;
  100603. var hh = c.halfHeight;
  100604. var ox;
  100605. var oy;
  100606. var oz;
  100607. if (len == 0) {
  100608. if (ldy < 0) {
  100609. ox = rad;
  100610. oy = -hh;
  100611. oz = 0;
  100612. } else {
  100613. ox = rad;
  100614. oy = hh;
  100615. oz = 0;
  100616. }
  100617. } else {
  100618. len = c.radius / OIMO.sqrt(len);
  100619. if (ldy < 0) {
  100620. ox = radx * len;
  100621. oy = -hh;
  100622. oz = radz * len;
  100623. } else {
  100624. ox = radx * len;
  100625. oy = hh;
  100626. oz = radz * len;
  100627. }
  100628. }
  100629. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100630. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100631. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100632. out.init(ldx, ldy, ldz);
  100633. };
  100634. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100635. var b;
  100636. var c;
  100637. if (this.flip) {
  100638. b = shape2;
  100639. c = shape1;
  100640. } else {
  100641. b = shape1;
  100642. c = shape2;
  100643. }
  100644. var sep = new OIMO.Vec3();
  100645. var pos = new OIMO.Vec3();
  100646. var dep = new OIMO.Vec3();
  100647. var co;
  100648. if (!this.getSep(b, c, sep, pos, dep)) return;
  100649. var pbx = b.position.x;
  100650. var pby = b.position.y;
  100651. var pbz = b.position.z;
  100652. var pcx = c.position.x;
  100653. var pcy = c.position.y;
  100654. var pcz = c.position.z;
  100655. var bw = b.halfWidth;
  100656. var bh = b.halfHeight;
  100657. var bd = b.halfDepth;
  100658. var ch = c.halfHeight;
  100659. var r = c.radius;
  100660. var D = b.dimentions;
  100661. var nwx = D[0];//b.normalDirectionWidth.x;
  100662. var nwy = D[1];//b.normalDirectionWidth.y;
  100663. var nwz = D[2];//b.normalDirectionWidth.z;
  100664. var nhx = D[3];//b.normalDirectionHeight.x;
  100665. var nhy = D[4];//b.normalDirectionHeight.y;
  100666. var nhz = D[5];//b.normalDirectionHeight.z;
  100667. var ndx = D[6];//b.normalDirectionDepth.x;
  100668. var ndy = D[7];//b.normalDirectionDepth.y;
  100669. var ndz = D[8];//b.normalDirectionDepth.z;
  100670. var dwx = D[9];//b.halfDirectionWidth.x;
  100671. var dwy = D[10];//b.halfDirectionWidth.y;
  100672. var dwz = D[11];//b.halfDirectionWidth.z;
  100673. var dhx = D[12];//b.halfDirectionHeight.x;
  100674. var dhy = D[13];//b.halfDirectionHeight.y;
  100675. var dhz = D[14];//b.halfDirectionHeight.z;
  100676. var ddx = D[15];//b.halfDirectionDepth.x;
  100677. var ddy = D[16];//b.halfDirectionDepth.y;
  100678. var ddz = D[17];//b.halfDirectionDepth.z;
  100679. var ncx = c.normalDirection.x;
  100680. var ncy = c.normalDirection.y;
  100681. var ncz = c.normalDirection.z;
  100682. var dcx = c.halfDirection.x;
  100683. var dcy = c.halfDirection.y;
  100684. var dcz = c.halfDirection.z;
  100685. var nx = sep.x;
  100686. var ny = sep.y;
  100687. var nz = sep.z;
  100688. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100689. var doth = nx * nhx + ny * nhy + nz * nhz;
  100690. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100691. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100692. var right1 = dotw > 0;
  100693. var right2 = doth > 0;
  100694. var right3 = dotd > 0;
  100695. var right4 = dotc > 0;
  100696. if (!right1) dotw = -dotw;
  100697. if (!right2) doth = -doth;
  100698. if (!right3) dotd = -dotd;
  100699. if (!right4) dotc = -dotc;
  100700. var state = 0;
  100701. if (dotc > 0.999) {
  100702. if (dotw > 0.999) {
  100703. if (dotw > dotc) state = 1;
  100704. else state = 4;
  100705. } else if (doth > 0.999) {
  100706. if (doth > dotc) state = 2;
  100707. else state = 4;
  100708. } else if (dotd > 0.999) {
  100709. if (dotd > dotc) state = 3;
  100710. else state = 4;
  100711. } else state = 4;
  100712. } else {
  100713. if (dotw > 0.999) state = 1;
  100714. else if (doth > 0.999) state = 2;
  100715. else if (dotd > 0.999) state = 3;
  100716. }
  100717. var cbx;
  100718. var cby;
  100719. var cbz;
  100720. var ccx;
  100721. var ccy;
  100722. var ccz;
  100723. var r00;
  100724. var r01;
  100725. var r02;
  100726. var r10;
  100727. var r11;
  100728. var r12;
  100729. var r20;
  100730. var r21;
  100731. var r22;
  100732. var px;
  100733. var py;
  100734. var pz;
  100735. var pd;
  100736. var dot;
  100737. var len;
  100738. var tx;
  100739. var ty;
  100740. var tz;
  100741. var td;
  100742. var dx;
  100743. var dy;
  100744. var dz;
  100745. var d1x;
  100746. var d1y;
  100747. var d1z;
  100748. var d2x;
  100749. var d2y;
  100750. var d2z;
  100751. var sx;
  100752. var sy;
  100753. var sz;
  100754. var sd;
  100755. var ex;
  100756. var ey;
  100757. var ez;
  100758. var ed;
  100759. var dot1;
  100760. var dot2;
  100761. var t1;
  100762. var t2;
  100763. var dir1x;
  100764. var dir1y;
  100765. var dir1z;
  100766. var dir2x;
  100767. var dir2y;
  100768. var dir2z;
  100769. var dir1l;
  100770. var dir2l;
  100771. if (state == 0) {
  100772. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  100773. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  100774. } else if (state == 4) {
  100775. if (right4) {
  100776. ccx = pcx - dcx;
  100777. ccy = pcy - dcy;
  100778. ccz = pcz - dcz;
  100779. nx = -ncx;
  100780. ny = -ncy;
  100781. nz = -ncz;
  100782. } else {
  100783. ccx = pcx + dcx;
  100784. ccy = pcy + dcy;
  100785. ccz = pcz + dcz;
  100786. nx = ncx;
  100787. ny = ncy;
  100788. nz = ncz;
  100789. }
  100790. var v1x;
  100791. var v1y;
  100792. var v1z;
  100793. var v2x;
  100794. var v2y;
  100795. var v2z;
  100796. var v3x;
  100797. var v3y;
  100798. var v3z;
  100799. var v4x;
  100800. var v4y;
  100801. var v4z;
  100802. dot = 1;
  100803. state = 0;
  100804. dot1 = nwx * nx + nwy * ny + nwz * nz;
  100805. if (dot1 < dot) {
  100806. dot = dot1;
  100807. state = 0;
  100808. }
  100809. if (-dot1 < dot) {
  100810. dot = -dot1;
  100811. state = 1;
  100812. }
  100813. dot1 = nhx * nx + nhy * ny + nhz * nz;
  100814. if (dot1 < dot) {
  100815. dot = dot1;
  100816. state = 2;
  100817. }
  100818. if (-dot1 < dot) {
  100819. dot = -dot1;
  100820. state = 3;
  100821. }
  100822. dot1 = ndx * nx + ndy * ny + ndz * nz;
  100823. if (dot1 < dot) {
  100824. dot = dot1;
  100825. state = 4;
  100826. }
  100827. if (-dot1 < dot) {
  100828. dot = -dot1;
  100829. state = 5;
  100830. }
  100831. var v = b.elements;
  100832. switch (state) {
  100833. case 0:
  100834. //v=b.vertex1;
  100835. v1x = v[0];//v.x;
  100836. v1y = v[1];//v.y;
  100837. v1z = v[2];//v.z;
  100838. //v=b.vertex3;
  100839. v2x = v[6];//v.x;
  100840. v2y = v[7];//v.y;
  100841. v2z = v[8];//v.z;
  100842. //v=b.vertex4;
  100843. v3x = v[9];//v.x;
  100844. v3y = v[10];//v.y;
  100845. v3z = v[11];//v.z;
  100846. //v=b.vertex2;
  100847. v4x = v[3];//v.x;
  100848. v4y = v[4];//v.y;
  100849. v4z = v[5];//v.z;
  100850. break;
  100851. case 1:
  100852. //v=b.vertex6;
  100853. v1x = v[15];//v.x;
  100854. v1y = v[16];//v.y;
  100855. v1z = v[17];//v.z;
  100856. //v=b.vertex8;
  100857. v2x = v[21];//v.x;
  100858. v2y = v[22];//v.y;
  100859. v2z = v[23];//v.z;
  100860. //v=b.vertex7;
  100861. v3x = v[18];//v.x;
  100862. v3y = v[19];//v.y;
  100863. v3z = v[20];//v.z;
  100864. //v=b.vertex5;
  100865. v4x = v[12];//v.x;
  100866. v4y = v[13];//v.y;
  100867. v4z = v[14];//v.z;
  100868. break;
  100869. case 2:
  100870. //v=b.vertex5;
  100871. v1x = v[12];//v.x;
  100872. v1y = v[13];//v.y;
  100873. v1z = v[14];//v.z;
  100874. //v=b.vertex1;
  100875. v2x = v[0];//v.x;
  100876. v2y = v[1];//v.y;
  100877. v2z = v[2];//v.z;
  100878. //v=b.vertex2;
  100879. v3x = v[3];//v.x;
  100880. v3y = v[4];//v.y;
  100881. v3z = v[5];//v.z;
  100882. //v=b.vertex6;
  100883. v4x = v[15];//v.x;
  100884. v4y = v[16];//v.y;
  100885. v4z = v[17];//v.z;
  100886. break;
  100887. case 3:
  100888. //v=b.vertex8;
  100889. v1x = v[21];//v.x;
  100890. v1y = v[22];//v.y;
  100891. v1z = v[23];//v.z;
  100892. //v=b.vertex4;
  100893. v2x = v[9];//v.x;
  100894. v2y = v[10];//v.y;
  100895. v2z = v[11];//v.z;
  100896. //v=b.vertex3;
  100897. v3x = v[6];//v.x;
  100898. v3y = v[7];//v.y;
  100899. v3z = v[8];//v.z;
  100900. //v=b.vertex7;
  100901. v4x = v[18];//v.x;
  100902. v4y = v[19];//v.y;
  100903. v4z = v[20];//v.z;
  100904. break;
  100905. case 4:
  100906. //v=b.vertex5;
  100907. v1x = v[12];//v.x;
  100908. v1y = v[13];//v.y;
  100909. v1z = v[14];//v.z;
  100910. //v=b.vertex7;
  100911. v2x = v[18];//v.x;
  100912. v2y = v[19];//v.y;
  100913. v2z = v[20];//v.z;
  100914. //v=b.vertex3;
  100915. v3x = v[6];//v.x;
  100916. v3y = v[7];//v.y;
  100917. v3z = v[8];//v.z;
  100918. //v=b.vertex1;
  100919. v4x = v[0];//v.x;
  100920. v4y = v[1];//v.y;
  100921. v4z = v[2];//v.z;
  100922. break;
  100923. case 5:
  100924. //v=b.vertex2;
  100925. v1x = v[3];//v.x;
  100926. v1y = v[4];//v.y;
  100927. v1z = v[5];//v.z;
  100928. //v=b.vertex4;
  100929. v2x = v[9];//v.x;
  100930. v2y = v[10];//v.y;
  100931. v2z = v[11];//v.z;
  100932. //v=b.vertex8;
  100933. v3x = v[21];//v.x;
  100934. v3y = v[22];//v.y;
  100935. v3z = v[23];//v.z;
  100936. //v=b.vertex6;
  100937. v4x = v[15];//v.x;
  100938. v4y = v[16];//v.y;
  100939. v4z = v[17];//v.z;
  100940. break;
  100941. }
  100942. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  100943. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  100944. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  100945. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  100946. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  100947. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  100948. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  100949. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  100950. } else {
  100951. switch (state) {
  100952. case 1:
  100953. if (right1) {
  100954. cbx = pbx + dwx;
  100955. cby = pby + dwy;
  100956. cbz = pbz + dwz;
  100957. nx = nwx;
  100958. ny = nwy;
  100959. nz = nwz;
  100960. } else {
  100961. cbx = pbx - dwx;
  100962. cby = pby - dwy;
  100963. cbz = pbz - dwz;
  100964. nx = -nwx;
  100965. ny = -nwy;
  100966. nz = -nwz;
  100967. }
  100968. dir1x = nhx;
  100969. dir1y = nhy;
  100970. dir1z = nhz;
  100971. dir1l = bh;
  100972. dir2x = ndx;
  100973. dir2y = ndy;
  100974. dir2z = ndz;
  100975. dir2l = bd;
  100976. break;
  100977. case 2:
  100978. if (right2) {
  100979. cbx = pbx + dhx;
  100980. cby = pby + dhy;
  100981. cbz = pbz + dhz;
  100982. nx = nhx;
  100983. ny = nhy;
  100984. nz = nhz;
  100985. } else {
  100986. cbx = pbx - dhx;
  100987. cby = pby - dhy;
  100988. cbz = pbz - dhz;
  100989. nx = -nhx;
  100990. ny = -nhy;
  100991. nz = -nhz;
  100992. }
  100993. dir1x = nwx;
  100994. dir1y = nwy;
  100995. dir1z = nwz;
  100996. dir1l = bw;
  100997. dir2x = ndx;
  100998. dir2y = ndy;
  100999. dir2z = ndz;
  101000. dir2l = bd;
  101001. break;
  101002. case 3:
  101003. if (right3) {
  101004. cbx = pbx + ddx;
  101005. cby = pby + ddy;
  101006. cbz = pbz + ddz;
  101007. nx = ndx;
  101008. ny = ndy;
  101009. nz = ndz;
  101010. } else {
  101011. cbx = pbx - ddx;
  101012. cby = pby - ddy;
  101013. cbz = pbz - ddz;
  101014. nx = -ndx;
  101015. ny = -ndy;
  101016. nz = -ndz;
  101017. }
  101018. dir1x = nwx;
  101019. dir1y = nwy;
  101020. dir1z = nwz;
  101021. dir1l = bw;
  101022. dir2x = nhx;
  101023. dir2y = nhy;
  101024. dir2z = nhz;
  101025. dir2l = bh;
  101026. break;
  101027. }
  101028. dot = nx * ncx + ny * ncy + nz * ncz;
  101029. if (dot < 0) len = ch;
  101030. else len = -ch;
  101031. ccx = pcx + len * ncx;
  101032. ccy = pcy + len * ncy;
  101033. ccz = pcz + len * ncz;
  101034. if (dotc >= 0.999999) {
  101035. tx = -ny;
  101036. ty = nz;
  101037. tz = nx;
  101038. } else {
  101039. tx = nx;
  101040. ty = ny;
  101041. tz = nz;
  101042. }
  101043. len = tx * ncx + ty * ncy + tz * ncz;
  101044. dx = len * ncx - tx;
  101045. dy = len * ncy - ty;
  101046. dz = len * ncz - tz;
  101047. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101048. if (len == 0) return;
  101049. len = r / len;
  101050. dx *= len;
  101051. dy *= len;
  101052. dz *= len;
  101053. tx = ccx + dx;
  101054. ty = ccy + dy;
  101055. tz = ccz + dz;
  101056. if (dot < -0.96 || dot > 0.96) {
  101057. r00 = ncx * ncx * 1.5 - 0.5;
  101058. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101059. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101060. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101061. r11 = ncy * ncy * 1.5 - 0.5;
  101062. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101063. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101064. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101065. r22 = ncz * ncz * 1.5 - 0.5;
  101066. px = tx;
  101067. py = ty;
  101068. pz = tz;
  101069. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101070. tx = px - pd * nx - cbx;
  101071. ty = py - pd * ny - cby;
  101072. tz = pz - pd * nz - cbz;
  101073. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101074. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101075. if (sd < -dir1l) sd = -dir1l;
  101076. else if (sd > dir1l) sd = dir1l;
  101077. if (ed < -dir2l) ed = -dir2l;
  101078. else if (ed > dir2l) ed = dir2l;
  101079. tx = sd * dir1x + ed * dir2x;
  101080. ty = sd * dir1y + ed * dir2y;
  101081. tz = sd * dir1z + ed * dir2z;
  101082. px = cbx + tx;
  101083. py = cby + ty;
  101084. pz = cbz + tz;
  101085. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101086. px = dx * r00 + dy * r01 + dz * r02;
  101087. py = dx * r10 + dy * r11 + dz * r12;
  101088. pz = dx * r20 + dy * r21 + dz * r22;
  101089. px = (dx = px) + ccx;
  101090. py = (dy = py) + ccy;
  101091. pz = (dz = pz) + ccz;
  101092. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101093. if (pd <= 0) {
  101094. tx = px - pd * nx - cbx;
  101095. ty = py - pd * ny - cby;
  101096. tz = pz - pd * nz - cbz;
  101097. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101098. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101099. if (sd < -dir1l) sd = -dir1l;
  101100. else if (sd > dir1l) sd = dir1l;
  101101. if (ed < -dir2l) ed = -dir2l;
  101102. else if (ed > dir2l) ed = dir2l;
  101103. tx = sd * dir1x + ed * dir2x;
  101104. ty = sd * dir1y + ed * dir2y;
  101105. tz = sd * dir1z + ed * dir2z;
  101106. px = cbx + tx;
  101107. py = cby + ty;
  101108. pz = cbz + tz;
  101109. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101110. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101111. }
  101112. px = dx * r00 + dy * r01 + dz * r02;
  101113. py = dx * r10 + dy * r11 + dz * r12;
  101114. pz = dx * r20 + dy * r21 + dz * r22;
  101115. px = (dx = px) + ccx;
  101116. py = (dy = py) + ccy;
  101117. pz = (dz = pz) + ccz;
  101118. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101119. if (pd <= 0) {
  101120. tx = px - pd * nx - cbx;
  101121. ty = py - pd * ny - cby;
  101122. tz = pz - pd * nz - cbz;
  101123. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101124. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101125. if (sd < -dir1l) sd = -dir1l;
  101126. else if (sd > dir1l) sd = dir1l;
  101127. if (ed < -dir2l) ed = -dir2l;
  101128. else if (ed > dir2l) ed = dir2l;
  101129. tx = sd * dir1x + ed * dir2x;
  101130. ty = sd * dir1y + ed * dir2y;
  101131. tz = sd * dir1z + ed * dir2z;
  101132. px = cbx + tx;
  101133. py = cby + ty;
  101134. pz = cbz + tz;
  101135. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101136. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101137. }
  101138. } else {
  101139. sx = tx;
  101140. sy = ty;
  101141. sz = tz;
  101142. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101143. sx -= sd * nx;
  101144. sy -= sd * ny;
  101145. sz -= sd * nz;
  101146. if (dot > 0) {
  101147. ex = tx + dcx * 2;
  101148. ey = ty + dcy * 2;
  101149. ez = tz + dcz * 2;
  101150. } else {
  101151. ex = tx - dcx * 2;
  101152. ey = ty - dcy * 2;
  101153. ez = tz - dcz * 2;
  101154. }
  101155. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101156. ex -= ed * nx;
  101157. ey -= ed * ny;
  101158. ez -= ed * nz;
  101159. d1x = sx - cbx;
  101160. d1y = sy - cby;
  101161. d1z = sz - cbz;
  101162. d2x = ex - cbx;
  101163. d2y = ey - cby;
  101164. d2z = ez - cbz;
  101165. tx = ex - sx;
  101166. ty = ey - sy;
  101167. tz = ez - sz;
  101168. td = ed - sd;
  101169. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101170. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101171. dot1 = dotw - dir1l;
  101172. dot2 = doth - dir1l;
  101173. if (dot1 > 0) {
  101174. if (dot2 > 0) return;
  101175. t1 = dot1 / (dot1 - dot2);
  101176. sx = sx + tx * t1;
  101177. sy = sy + ty * t1;
  101178. sz = sz + tz * t1;
  101179. sd = sd + td * t1;
  101180. d1x = sx - cbx;
  101181. d1y = sy - cby;
  101182. d1z = sz - cbz;
  101183. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101184. tx = ex - sx;
  101185. ty = ey - sy;
  101186. tz = ez - sz;
  101187. td = ed - sd;
  101188. } else if (dot2 > 0) {
  101189. t1 = dot1 / (dot1 - dot2);
  101190. ex = sx + tx * t1;
  101191. ey = sy + ty * t1;
  101192. ez = sz + tz * t1;
  101193. ed = sd + td * t1;
  101194. d2x = ex - cbx;
  101195. d2y = ey - cby;
  101196. d2z = ez - cbz;
  101197. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101198. tx = ex - sx;
  101199. ty = ey - sy;
  101200. tz = ez - sz;
  101201. td = ed - sd;
  101202. }
  101203. dot1 = dotw + dir1l;
  101204. dot2 = doth + dir1l;
  101205. if (dot1 < 0) {
  101206. if (dot2 < 0) return;
  101207. t1 = dot1 / (dot1 - dot2);
  101208. sx = sx + tx * t1;
  101209. sy = sy + ty * t1;
  101210. sz = sz + tz * t1;
  101211. sd = sd + td * t1;
  101212. d1x = sx - cbx;
  101213. d1y = sy - cby;
  101214. d1z = sz - cbz;
  101215. tx = ex - sx;
  101216. ty = ey - sy;
  101217. tz = ez - sz;
  101218. td = ed - sd;
  101219. } else if (dot2 < 0) {
  101220. t1 = dot1 / (dot1 - dot2);
  101221. ex = sx + tx * t1;
  101222. ey = sy + ty * t1;
  101223. ez = sz + tz * t1;
  101224. ed = sd + td * t1;
  101225. d2x = ex - cbx;
  101226. d2y = ey - cby;
  101227. d2z = ez - cbz;
  101228. tx = ex - sx;
  101229. ty = ey - sy;
  101230. tz = ez - sz;
  101231. td = ed - sd;
  101232. }
  101233. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101234. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101235. dot1 = dotw - dir2l;
  101236. dot2 = doth - dir2l;
  101237. if (dot1 > 0) {
  101238. if (dot2 > 0) return;
  101239. t1 = dot1 / (dot1 - dot2);
  101240. sx = sx + tx * t1;
  101241. sy = sy + ty * t1;
  101242. sz = sz + tz * t1;
  101243. sd = sd + td * t1;
  101244. d1x = sx - cbx;
  101245. d1y = sy - cby;
  101246. d1z = sz - cbz;
  101247. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101248. tx = ex - sx;
  101249. ty = ey - sy;
  101250. tz = ez - sz;
  101251. td = ed - sd;
  101252. } else if (dot2 > 0) {
  101253. t1 = dot1 / (dot1 - dot2);
  101254. ex = sx + tx * t1;
  101255. ey = sy + ty * t1;
  101256. ez = sz + tz * t1;
  101257. ed = sd + td * t1;
  101258. d2x = ex - cbx;
  101259. d2y = ey - cby;
  101260. d2z = ez - cbz;
  101261. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101262. tx = ex - sx;
  101263. ty = ey - sy;
  101264. tz = ez - sz;
  101265. td = ed - sd;
  101266. }
  101267. dot1 = dotw + dir2l;
  101268. dot2 = doth + dir2l;
  101269. if (dot1 < 0) {
  101270. if (dot2 < 0) return;
  101271. t1 = dot1 / (dot1 - dot2);
  101272. sx = sx + tx * t1;
  101273. sy = sy + ty * t1;
  101274. sz = sz + tz * t1;
  101275. sd = sd + td * t1;
  101276. } else if (dot2 < 0) {
  101277. t1 = dot1 / (dot1 - dot2);
  101278. ex = sx + tx * t1;
  101279. ey = sy + ty * t1;
  101280. ez = sz + tz * t1;
  101281. ed = sd + td * t1;
  101282. }
  101283. if (sd < 0) {
  101284. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101285. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101286. }
  101287. if (ed < 0) {
  101288. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101289. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101290. }
  101291. }
  101292. }
  101293. };
  101294. OIMO.CylinderCylinderCollisionDetector = function () {
  101295. OIMO.CollisionDetector.call(this);
  101296. };
  101297. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101298. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101299. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101300. var t1x;
  101301. var t1y;
  101302. var t1z;
  101303. var t2x;
  101304. var t2y;
  101305. var t2z;
  101306. var sup = new OIMO.Vec3();
  101307. var len;
  101308. var p1x;
  101309. var p1y;
  101310. var p1z;
  101311. var p2x;
  101312. var p2y;
  101313. var p2z;
  101314. var v01x = c1.position.x;
  101315. var v01y = c1.position.y;
  101316. var v01z = c1.position.z;
  101317. var v02x = c2.position.x;
  101318. var v02y = c2.position.y;
  101319. var v02z = c2.position.z;
  101320. var v0x = v02x - v01x;
  101321. var v0y = v02y - v01y;
  101322. var v0z = v02z - v01z;
  101323. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101324. var nx = -v0x;
  101325. var ny = -v0y;
  101326. var nz = -v0z;
  101327. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101328. var v11x = sup.x;
  101329. var v11y = sup.y;
  101330. var v11z = sup.z;
  101331. this.supportPoint(c2, nx, ny, nz, sup);
  101332. var v12x = sup.x;
  101333. var v12y = sup.y;
  101334. var v12z = sup.z;
  101335. var v1x = v12x - v11x;
  101336. var v1y = v12y - v11y;
  101337. var v1z = v12z - v11z;
  101338. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101339. return false;
  101340. }
  101341. nx = v1y * v0z - v1z * v0y;
  101342. ny = v1z * v0x - v1x * v0z;
  101343. nz = v1x * v0y - v1y * v0x;
  101344. if (nx * nx + ny * ny + nz * nz == 0) {
  101345. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101346. sep.normalize(sep);
  101347. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101348. return true;
  101349. }
  101350. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101351. var v21x = sup.x;
  101352. var v21y = sup.y;
  101353. var v21z = sup.z;
  101354. this.supportPoint(c2, nx, ny, nz, sup);
  101355. var v22x = sup.x;
  101356. var v22y = sup.y;
  101357. var v22z = sup.z;
  101358. var v2x = v22x - v21x;
  101359. var v2y = v22y - v21y;
  101360. var v2z = v22z - v21z;
  101361. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101362. return false;
  101363. }
  101364. t1x = v1x - v0x;
  101365. t1y = v1y - v0y;
  101366. t1z = v1z - v0z;
  101367. t2x = v2x - v0x;
  101368. t2y = v2y - v0y;
  101369. t2z = v2z - v0z;
  101370. nx = t1y * t2z - t1z * t2y;
  101371. ny = t1z * t2x - t1x * t2z;
  101372. nz = t1x * t2y - t1y * t2x;
  101373. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101374. t1x = v1x;
  101375. t1y = v1y;
  101376. t1z = v1z;
  101377. v1x = v2x;
  101378. v1y = v2y;
  101379. v1z = v2z;
  101380. v2x = t1x;
  101381. v2y = t1y;
  101382. v2z = t1z;
  101383. t1x = v11x;
  101384. t1y = v11y;
  101385. t1z = v11z;
  101386. v11x = v21x;
  101387. v11y = v21y;
  101388. v11z = v21z;
  101389. v21x = t1x;
  101390. v21y = t1y;
  101391. v21z = t1z;
  101392. t1x = v12x;
  101393. t1y = v12y;
  101394. t1z = v12z;
  101395. v12x = v22x;
  101396. v12y = v22y;
  101397. v12z = v22z;
  101398. v22x = t1x;
  101399. v22y = t1y;
  101400. v22z = t1z;
  101401. nx = -nx;
  101402. ny = -ny;
  101403. nz = -nz;
  101404. }
  101405. var iterations = 0;
  101406. while (true) {
  101407. if (++iterations > 100) {
  101408. return false;
  101409. }
  101410. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101411. var v31x = sup.x;
  101412. var v31y = sup.y;
  101413. var v31z = sup.z;
  101414. this.supportPoint(c2, nx, ny, nz, sup);
  101415. var v32x = sup.x;
  101416. var v32y = sup.y;
  101417. var v32z = sup.z;
  101418. var v3x = v32x - v31x;
  101419. var v3y = v32y - v31y;
  101420. var v3z = v32z - v31z;
  101421. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101422. return false;
  101423. }
  101424. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101425. v2x = v3x;
  101426. v2y = v3y;
  101427. v2z = v3z;
  101428. v21x = v31x;
  101429. v21y = v31y;
  101430. v21z = v31z;
  101431. v22x = v32x;
  101432. v22y = v32y;
  101433. v22z = v32z;
  101434. t1x = v1x - v0x;
  101435. t1y = v1y - v0y;
  101436. t1z = v1z - v0z;
  101437. t2x = v3x - v0x;
  101438. t2y = v3y - v0y;
  101439. t2z = v3z - v0z;
  101440. nx = t1y * t2z - t1z * t2y;
  101441. ny = t1z * t2x - t1x * t2z;
  101442. nz = t1x * t2y - t1y * t2x;
  101443. continue;
  101444. }
  101445. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101446. v1x = v3x;
  101447. v1y = v3y;
  101448. v1z = v3z;
  101449. v11x = v31x;
  101450. v11y = v31y;
  101451. v11z = v31z;
  101452. v12x = v32x;
  101453. v12y = v32y;
  101454. v12z = v32z;
  101455. t1x = v3x - v0x;
  101456. t1y = v3y - v0y;
  101457. t1z = v3z - v0z;
  101458. t2x = v2x - v0x;
  101459. t2y = v2y - v0y;
  101460. t2z = v2z - v0z;
  101461. nx = t1y * t2z - t1z * t2y;
  101462. ny = t1z * t2x - t1x * t2z;
  101463. nz = t1x * t2y - t1y * t2x;
  101464. continue;
  101465. }
  101466. var hit = false;
  101467. while (true) {
  101468. t1x = v2x - v1x;
  101469. t1y = v2y - v1y;
  101470. t1z = v2z - v1z;
  101471. t2x = v3x - v1x;
  101472. t2y = v3y - v1y;
  101473. t2z = v3z - v1z;
  101474. nx = t1y * t2z - t1z * t2y;
  101475. ny = t1z * t2x - t1x * t2z;
  101476. nz = t1x * t2y - t1y * t2x;
  101477. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101478. nx *= len;
  101479. ny *= len;
  101480. nz *= len;
  101481. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101482. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101483. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101484. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101485. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101486. var sum = b0 + b1 + b2 + b3;
  101487. if (sum <= 0) {
  101488. b0 = 0;
  101489. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101490. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101491. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101492. sum = b1 + b2 + b3;
  101493. }
  101494. var inv = 1 / sum;
  101495. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101496. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101497. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101498. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101499. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101500. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101501. hit = true;
  101502. }
  101503. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101504. var v41x = sup.x;
  101505. var v41y = sup.y;
  101506. var v41z = sup.z;
  101507. this.supportPoint(c2, nx, ny, nz, sup);
  101508. var v42x = sup.x;
  101509. var v42y = sup.y;
  101510. var v42z = sup.z;
  101511. var v4x = v42x - v41x;
  101512. var v4y = v42y - v41y;
  101513. var v4z = v42z - v41z;
  101514. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101515. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101516. if (hit) {
  101517. sep.init(-nx, -ny, -nz);
  101518. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101519. dep.x = separation;
  101520. return true;
  101521. }
  101522. return false;
  101523. }
  101524. if (
  101525. (v4y * v1z - v4z * v1y) * v0x +
  101526. (v4z * v1x - v4x * v1z) * v0y +
  101527. (v4x * v1y - v4y * v1x) * v0z < 0
  101528. ) {
  101529. if (
  101530. (v4y * v2z - v4z * v2y) * v0x +
  101531. (v4z * v2x - v4x * v2z) * v0y +
  101532. (v4x * v2y - v4y * v2x) * v0z < 0
  101533. ) {
  101534. v1x = v4x;
  101535. v1y = v4y;
  101536. v1z = v4z;
  101537. v11x = v41x;
  101538. v11y = v41y;
  101539. v11z = v41z;
  101540. v12x = v42x;
  101541. v12y = v42y;
  101542. v12z = v42z;
  101543. } else {
  101544. v3x = v4x;
  101545. v3y = v4y;
  101546. v3z = v4z;
  101547. v31x = v41x;
  101548. v31y = v41y;
  101549. v31z = v41z;
  101550. v32x = v42x;
  101551. v32y = v42y;
  101552. v32z = v42z;
  101553. }
  101554. } else {
  101555. if (
  101556. (v4y * v3z - v4z * v3y) * v0x +
  101557. (v4z * v3x - v4x * v3z) * v0y +
  101558. (v4x * v3y - v4y * v3x) * v0z < 0
  101559. ) {
  101560. v2x = v4x;
  101561. v2y = v4y;
  101562. v2z = v4z;
  101563. v21x = v41x;
  101564. v21y = v41y;
  101565. v21z = v41z;
  101566. v22x = v42x;
  101567. v22y = v42y;
  101568. v22z = v42z;
  101569. } else {
  101570. v1x = v4x;
  101571. v1y = v4y;
  101572. v1z = v4z;
  101573. v11x = v41x;
  101574. v11y = v41y;
  101575. v11z = v41z;
  101576. v12x = v42x;
  101577. v12y = v42y;
  101578. v12z = v42z;
  101579. }
  101580. }
  101581. }
  101582. }
  101583. //return false;
  101584. };
  101585. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101586. var rot = c.rotation.elements;
  101587. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101588. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101589. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101590. var radx = ldx;
  101591. var radz = ldz;
  101592. var len = radx * radx + radz * radz;
  101593. var rad = c.radius;
  101594. var hh = c.halfHeight;
  101595. var ox;
  101596. var oy;
  101597. var oz;
  101598. if (len == 0) {
  101599. if (ldy < 0) {
  101600. ox = rad;
  101601. oy = -hh;
  101602. oz = 0;
  101603. } else {
  101604. ox = rad;
  101605. oy = hh;
  101606. oz = 0;
  101607. }
  101608. } else {
  101609. len = c.radius / OIMO.sqrt(len);
  101610. if (ldy < 0) {
  101611. ox = radx * len;
  101612. oy = -hh;
  101613. oz = radz * len;
  101614. } else {
  101615. ox = radx * len;
  101616. oy = hh;
  101617. oz = radz * len;
  101618. }
  101619. }
  101620. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101621. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101622. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101623. out.init(ldx, ldy, ldz);
  101624. };
  101625. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101626. var c1;
  101627. var c2;
  101628. if (shape1.id < shape2.id) {
  101629. c1 = shape1;
  101630. c2 = shape2;
  101631. } else {
  101632. c1 = shape2;
  101633. c2 = shape1;
  101634. }
  101635. var p1 = c1.position;
  101636. var p2 = c2.position;
  101637. var p1x = p1.x;
  101638. var p1y = p1.y;
  101639. var p1z = p1.z;
  101640. var p2x = p2.x;
  101641. var p2y = p2.y;
  101642. var p2z = p2.z;
  101643. var h1 = c1.halfHeight;
  101644. var h2 = c2.halfHeight;
  101645. var n1 = c1.normalDirection;
  101646. var n2 = c2.normalDirection;
  101647. var d1 = c1.halfDirection;
  101648. var d2 = c2.halfDirection;
  101649. var r1 = c1.radius;
  101650. var r2 = c2.radius;
  101651. var n1x = n1.x;
  101652. var n1y = n1.y;
  101653. var n1z = n1.z;
  101654. var n2x = n2.x;
  101655. var n2y = n2.y;
  101656. var n2z = n2.z;
  101657. var d1x = d1.x;
  101658. var d1y = d1.y;
  101659. var d1z = d1.z;
  101660. var d2x = d2.x;
  101661. var d2y = d2.y;
  101662. var d2z = d2.z;
  101663. var dx = p1x - p2x;
  101664. var dy = p1y - p2y;
  101665. var dz = p1z - p2z;
  101666. var len;
  101667. var len1;
  101668. var len2;
  101669. var c;
  101670. var c1x;
  101671. var c1y;
  101672. var c1z;
  101673. var c2x;
  101674. var c2y;
  101675. var c2z;
  101676. var tx;
  101677. var ty;
  101678. var tz;
  101679. var sx;
  101680. var sy;
  101681. var sz;
  101682. var ex;
  101683. var ey;
  101684. var ez;
  101685. var depth1;
  101686. var depth2;
  101687. var dot;
  101688. var t1;
  101689. var t2;
  101690. var sep = new OIMO.Vec3();
  101691. var pos = new OIMO.Vec3();
  101692. var dep = new OIMO.Vec3();
  101693. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101694. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101695. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101696. var right1 = dot1 > 0;
  101697. var right2 = dot2 > 0;
  101698. if (!right1) dot1 = -dot1;
  101699. if (!right2) dot2 = -dot2;
  101700. var state = 0;
  101701. if (dot1 > 0.999 || dot2 > 0.999) {
  101702. if (dot1 > dot2) state = 1;
  101703. else state = 2;
  101704. }
  101705. var nx;
  101706. var ny;
  101707. var nz;
  101708. var depth = dep.x;
  101709. var r00;
  101710. var r01;
  101711. var r02;
  101712. var r10;
  101713. var r11;
  101714. var r12;
  101715. var r20;
  101716. var r21;
  101717. var r22;
  101718. var px;
  101719. var py;
  101720. var pz;
  101721. var pd;
  101722. var a;
  101723. var b;
  101724. var e;
  101725. var f;
  101726. nx = sep.x;
  101727. ny = sep.y;
  101728. nz = sep.z;
  101729. switch (state) {
  101730. case 0:
  101731. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  101732. break;
  101733. case 1:
  101734. if (right1) {
  101735. c1x = p1x + d1x;
  101736. c1y = p1y + d1y;
  101737. c1z = p1z + d1z;
  101738. nx = n1x;
  101739. ny = n1y;
  101740. nz = n1z;
  101741. } else {
  101742. c1x = p1x - d1x;
  101743. c1y = p1y - d1y;
  101744. c1z = p1z - d1z;
  101745. nx = -n1x;
  101746. ny = -n1y;
  101747. nz = -n1z;
  101748. }
  101749. dot = nx * n2x + ny * n2y + nz * n2z;
  101750. if (dot < 0) len = h2;
  101751. else len = -h2;
  101752. c2x = p2x + len * n2x;
  101753. c2y = p2y + len * n2y;
  101754. c2z = p2z + len * n2z;
  101755. if (dot2 >= 0.999999) {
  101756. tx = -ny;
  101757. ty = nz;
  101758. tz = nx;
  101759. } else {
  101760. tx = nx;
  101761. ty = ny;
  101762. tz = nz;
  101763. }
  101764. len = tx * n2x + ty * n2y + tz * n2z;
  101765. dx = len * n2x - tx;
  101766. dy = len * n2y - ty;
  101767. dz = len * n2z - tz;
  101768. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101769. if (len == 0) break;
  101770. len = r2 / len;
  101771. dx *= len;
  101772. dy *= len;
  101773. dz *= len;
  101774. tx = c2x + dx;
  101775. ty = c2y + dy;
  101776. tz = c2z + dz;
  101777. if (dot < -0.96 || dot > 0.96) {
  101778. r00 = n2x * n2x * 1.5 - 0.5;
  101779. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  101780. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  101781. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  101782. r11 = n2y * n2y * 1.5 - 0.5;
  101783. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  101784. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  101785. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  101786. r22 = n2z * n2z * 1.5 - 0.5;
  101787. px = tx;
  101788. py = ty;
  101789. pz = tz;
  101790. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101791. tx = px - pd * nx - c1x;
  101792. ty = py - pd * ny - c1y;
  101793. tz = pz - pd * nz - c1z;
  101794. len = tx * tx + ty * ty + tz * tz;
  101795. if (len > r1 * r1) {
  101796. len = r1 / OIMO.sqrt(len);
  101797. tx *= len;
  101798. ty *= len;
  101799. tz *= len;
  101800. }
  101801. px = c1x + tx;
  101802. py = c1y + ty;
  101803. pz = c1z + tz;
  101804. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101805. px = dx * r00 + dy * r01 + dz * r02;
  101806. py = dx * r10 + dy * r11 + dz * r12;
  101807. pz = dx * r20 + dy * r21 + dz * r22;
  101808. px = (dx = px) + c2x;
  101809. py = (dy = py) + c2y;
  101810. pz = (dz = pz) + c2z;
  101811. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101812. if (pd <= 0) {
  101813. tx = px - pd * nx - c1x;
  101814. ty = py - pd * ny - c1y;
  101815. tz = pz - pd * nz - c1z;
  101816. len = tx * tx + ty * ty + tz * tz;
  101817. if (len > r1 * r1) {
  101818. len = r1 / OIMO.sqrt(len);
  101819. tx *= len;
  101820. ty *= len;
  101821. tz *= len;
  101822. }
  101823. px = c1x + tx;
  101824. py = c1y + ty;
  101825. pz = c1z + tz;
  101826. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101827. }
  101828. px = dx * r00 + dy * r01 + dz * r02;
  101829. py = dx * r10 + dy * r11 + dz * r12;
  101830. pz = dx * r20 + dy * r21 + dz * r22;
  101831. px = (dx = px) + c2x;
  101832. py = (dy = py) + c2y;
  101833. pz = (dz = pz) + c2z;
  101834. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101835. if (pd <= 0) {
  101836. tx = px - pd * nx - c1x;
  101837. ty = py - pd * ny - c1y;
  101838. tz = pz - pd * nz - c1z;
  101839. len = tx * tx + ty * ty + tz * tz;
  101840. if (len > r1 * r1) {
  101841. len = r1 / OIMO.sqrt(len);
  101842. tx *= len;
  101843. ty *= len;
  101844. tz *= len;
  101845. }
  101846. px = c1x + tx;
  101847. py = c1y + ty;
  101848. pz = c1z + tz;
  101849. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101850. }
  101851. } else {
  101852. sx = tx;
  101853. sy = ty;
  101854. sz = tz;
  101855. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  101856. sx -= depth1 * nx;
  101857. sy -= depth1 * ny;
  101858. sz -= depth1 * nz;
  101859. if (dot > 0) {
  101860. ex = tx + n2x * h2 * 2;
  101861. ey = ty + n2y * h2 * 2;
  101862. ez = tz + n2z * h2 * 2;
  101863. } else {
  101864. ex = tx - n2x * h2 * 2;
  101865. ey = ty - n2y * h2 * 2;
  101866. ez = tz - n2z * h2 * 2;
  101867. }
  101868. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  101869. ex -= depth2 * nx;
  101870. ey -= depth2 * ny;
  101871. ez -= depth2 * nz;
  101872. dx = c1x - sx;
  101873. dy = c1y - sy;
  101874. dz = c1z - sz;
  101875. tx = ex - sx;
  101876. ty = ey - sy;
  101877. tz = ez - sz;
  101878. a = dx * dx + dy * dy + dz * dz;
  101879. b = dx * tx + dy * ty + dz * tz;
  101880. e = tx * tx + ty * ty + tz * tz;
  101881. f = b * b - e * (a - r1 * r1);
  101882. if (f < 0) break;
  101883. f = OIMO.sqrt(f);
  101884. t1 = (b + f) / e;
  101885. t2 = (b - f) / e;
  101886. if (t2 < t1) {
  101887. len = t1;
  101888. t1 = t2;
  101889. t2 = len;
  101890. }
  101891. if (t2 > 1) t2 = 1;
  101892. if (t1 < 0) t1 = 0;
  101893. tx = sx + (ex - sx) * t1;
  101894. ty = sy + (ey - sy) * t1;
  101895. tz = sz + (ez - sz) * t1;
  101896. ex = sx + (ex - sx) * t2;
  101897. ey = sy + (ey - sy) * t2;
  101898. ez = sz + (ez - sz) * t2;
  101899. sx = tx;
  101900. sy = ty;
  101901. sz = tz;
  101902. len = depth1 + (depth2 - depth1) * t1;
  101903. depth2 = depth1 + (depth2 - depth1) * t2;
  101904. depth1 = len;
  101905. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  101906. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  101907. }
  101908. break;
  101909. case 2:
  101910. if (right2) {
  101911. c2x = p2x - d2x;
  101912. c2y = p2y - d2y;
  101913. c2z = p2z - d2z;
  101914. nx = -n2x;
  101915. ny = -n2y;
  101916. nz = -n2z;
  101917. } else {
  101918. c2x = p2x + d2x;
  101919. c2y = p2y + d2y;
  101920. c2z = p2z + d2z;
  101921. nx = n2x;
  101922. ny = n2y;
  101923. nz = n2z;
  101924. }
  101925. dot = nx * n1x + ny * n1y + nz * n1z;
  101926. if (dot < 0) len = h1;
  101927. else len = -h1;
  101928. c1x = p1x + len * n1x;
  101929. c1y = p1y + len * n1y;
  101930. c1z = p1z + len * n1z;
  101931. if (dot1 >= 0.999999) {
  101932. tx = -ny;
  101933. ty = nz;
  101934. tz = nx;
  101935. } else {
  101936. tx = nx;
  101937. ty = ny;
  101938. tz = nz;
  101939. }
  101940. len = tx * n1x + ty * n1y + tz * n1z;
  101941. dx = len * n1x - tx;
  101942. dy = len * n1y - ty;
  101943. dz = len * n1z - tz;
  101944. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101945. if (len == 0) break;
  101946. len = r1 / len;
  101947. dx *= len;
  101948. dy *= len;
  101949. dz *= len;
  101950. tx = c1x + dx;
  101951. ty = c1y + dy;
  101952. tz = c1z + dz;
  101953. if (dot < -0.96 || dot > 0.96) {
  101954. r00 = n1x * n1x * 1.5 - 0.5;
  101955. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  101956. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  101957. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  101958. r11 = n1y * n1y * 1.5 - 0.5;
  101959. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  101960. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  101961. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  101962. r22 = n1z * n1z * 1.5 - 0.5;
  101963. px = tx;
  101964. py = ty;
  101965. pz = tz;
  101966. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101967. tx = px - pd * nx - c2x;
  101968. ty = py - pd * ny - c2y;
  101969. tz = pz - pd * nz - c2z;
  101970. len = tx * tx + ty * ty + tz * tz;
  101971. if (len > r2 * r2) {
  101972. len = r2 / OIMO.sqrt(len);
  101973. tx *= len;
  101974. ty *= len;
  101975. tz *= len;
  101976. }
  101977. px = c2x + tx;
  101978. py = c2y + ty;
  101979. pz = c2z + tz;
  101980. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101981. px = dx * r00 + dy * r01 + dz * r02;
  101982. py = dx * r10 + dy * r11 + dz * r12;
  101983. pz = dx * r20 + dy * r21 + dz * r22;
  101984. px = (dx = px) + c1x;
  101985. py = (dy = py) + c1y;
  101986. pz = (dz = pz) + c1z;
  101987. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101988. if (pd <= 0) {
  101989. tx = px - pd * nx - c2x;
  101990. ty = py - pd * ny - c2y;
  101991. tz = pz - pd * nz - c2z;
  101992. len = tx * tx + ty * ty + tz * tz;
  101993. if (len > r2 * r2) {
  101994. len = r2 / OIMO.sqrt(len);
  101995. tx *= len;
  101996. ty *= len;
  101997. tz *= len;
  101998. }
  101999. px = c2x + tx;
  102000. py = c2y + ty;
  102001. pz = c2z + tz;
  102002. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102003. }
  102004. px = dx * r00 + dy * r01 + dz * r02;
  102005. py = dx * r10 + dy * r11 + dz * r12;
  102006. pz = dx * r20 + dy * r21 + dz * r22;
  102007. px = (dx = px) + c1x;
  102008. py = (dy = py) + c1y;
  102009. pz = (dz = pz) + c1z;
  102010. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102011. if (pd <= 0) {
  102012. tx = px - pd * nx - c2x;
  102013. ty = py - pd * ny - c2y;
  102014. tz = pz - pd * nz - c2z;
  102015. len = tx * tx + ty * ty + tz * tz;
  102016. if (len > r2 * r2) {
  102017. len = r2 / OIMO.sqrt(len);
  102018. tx *= len;
  102019. ty *= len;
  102020. tz *= len;
  102021. }
  102022. px = c2x + tx;
  102023. py = c2y + ty;
  102024. pz = c2z + tz;
  102025. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102026. }
  102027. } else {
  102028. sx = tx;
  102029. sy = ty;
  102030. sz = tz;
  102031. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102032. sx -= depth1 * nx;
  102033. sy -= depth1 * ny;
  102034. sz -= depth1 * nz;
  102035. if (dot > 0) {
  102036. ex = tx + n1x * h1 * 2;
  102037. ey = ty + n1y * h1 * 2;
  102038. ez = tz + n1z * h1 * 2;
  102039. } else {
  102040. ex = tx - n1x * h1 * 2;
  102041. ey = ty - n1y * h1 * 2;
  102042. ez = tz - n1z * h1 * 2;
  102043. }
  102044. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102045. ex -= depth2 * nx;
  102046. ey -= depth2 * ny;
  102047. ez -= depth2 * nz;
  102048. dx = c2x - sx;
  102049. dy = c2y - sy;
  102050. dz = c2z - sz;
  102051. tx = ex - sx;
  102052. ty = ey - sy;
  102053. tz = ez - sz;
  102054. a = dx * dx + dy * dy + dz * dz;
  102055. b = dx * tx + dy * ty + dz * tz;
  102056. e = tx * tx + ty * ty + tz * tz;
  102057. f = b * b - e * (a - r2 * r2);
  102058. if (f < 0) break;
  102059. f = OIMO.sqrt(f);
  102060. t1 = (b + f) / e;
  102061. t2 = (b - f) / e;
  102062. if (t2 < t1) {
  102063. len = t1;
  102064. t1 = t2;
  102065. t2 = len;
  102066. }
  102067. if (t2 > 1) t2 = 1;
  102068. if (t1 < 0) t1 = 0;
  102069. tx = sx + (ex - sx) * t1;
  102070. ty = sy + (ey - sy) * t1;
  102071. tz = sz + (ez - sz) * t1;
  102072. ex = sx + (ex - sx) * t2;
  102073. ey = sy + (ey - sy) * t2;
  102074. ez = sz + (ez - sz) * t2;
  102075. sx = tx;
  102076. sy = ty;
  102077. sz = tz;
  102078. len = depth1 + (depth2 - depth1) * t1;
  102079. depth2 = depth1 + (depth2 - depth1) * t2;
  102080. depth1 = len;
  102081. if (depth1 < 0) {
  102082. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102083. }
  102084. if (depth2 < 0) {
  102085. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102086. }
  102087. }
  102088. break;
  102089. }
  102090. };
  102091. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102092. OIMO.CollisionDetector.call(this);
  102093. this.flip = flip;
  102094. };
  102095. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102096. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102097. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102098. var s;
  102099. var c;
  102100. if (this.flip) {
  102101. s = shape2;
  102102. c = shape1;
  102103. } else {
  102104. s = shape1;
  102105. c = shape2;
  102106. }
  102107. var ps = s.position;
  102108. var psx = ps.x;
  102109. var psy = ps.y;
  102110. var psz = ps.z;
  102111. var pc = c.position;
  102112. var pcx = pc.x;
  102113. var pcy = pc.y;
  102114. var pcz = pc.z;
  102115. var dirx = c.normalDirection.x;
  102116. var diry = c.normalDirection.y;
  102117. var dirz = c.normalDirection.z;
  102118. var rads = s.radius;
  102119. var radc = c.radius;
  102120. var rad2 = rads + radc;
  102121. var halfh = c.halfHeight;
  102122. var dx = psx - pcx;
  102123. var dy = psy - pcy;
  102124. var dz = psz - pcz;
  102125. var dot = dx * dirx + dy * diry + dz * dirz;
  102126. if (dot < -halfh - rads || dot > halfh + rads) return;
  102127. var cx = pcx + dot * dirx;
  102128. var cy = pcy + dot * diry;
  102129. var cz = pcz + dot * dirz;
  102130. var d2x = psx - cx;
  102131. var d2y = psy - cy;
  102132. var d2z = psz - cz;
  102133. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102134. if (len > rad2 * rad2) return;
  102135. if (len > radc * radc) {
  102136. len = radc / OIMO.sqrt(len);
  102137. d2x *= len;
  102138. d2y *= len;
  102139. d2z *= len;
  102140. }
  102141. if (dot < -halfh) dot = -halfh;
  102142. else if (dot > halfh) dot = halfh;
  102143. cx = pcx + dot * dirx + d2x;
  102144. cy = pcy + dot * diry + d2y;
  102145. cz = pcz + dot * dirz + d2z;
  102146. dx = cx - psx;
  102147. dy = cy - psy;
  102148. dz = cz - psz;
  102149. len = dx * dx + dy * dy + dz * dz;
  102150. var invLen;
  102151. if (len > 0 && len < rads * rads) {
  102152. len = OIMO.sqrt(len);
  102153. invLen = 1 / len;
  102154. dx *= invLen;
  102155. dy *= invLen;
  102156. dz *= invLen;
  102157. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102158. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102159. }
  102160. };
  102161. /**
  102162. * Class for checking collisions between 2 tetras,
  102163. * a shape that is made with 4 vertices and 4 faces
  102164. * arranged in triangles. With this algorigthm, soft
  102165. * body physics are possible and easier to implement.
  102166. * @author xprogram
  102167. */
  102168. OIMO.TetraTetraCollisionDetector = function () {
  102169. OIMO.CollisionDetector.call(this);
  102170. };
  102171. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102172. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102173. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102174. /*
  102175. * What we are doing:
  102176. * Each tetra is represented by four 3D triangles. The only
  102177. * quick way of finding if another tetra is within the other
  102178. * tetra is to see if a single vertex is within the triangles
  102179. * of the other tetra. So, for example, a tetra is represented
  102180. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102181. * There is another tetra with a vertex A which was detected for
  102182. * collision by the broadphase. Now, if the point A is between ALL
  102183. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102184. * is valid and we can pass point A to the manifold. Since the only
  102185. * points on the tetra are the 4 vertices, collision detection is
  102186. * not so complex. However, it can be time-consuming because we
  102187. * need to split the 3D triangles into three 2D triangles each for
  102188. * collision detection.
  102189. */
  102190. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102191. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102192. // fs is undeclared
  102193. var fs = fs1;
  102194. for (i = 0; i < 4; i++) {
  102195. vec = vs1[i];
  102196. for (j = 0; j < 4; j++) {
  102197. j1 = vs2[fs[i].a];
  102198. j2 = vs2[fs[i].b];
  102199. j3 = vs2[fs[i].c];
  102200. if (
  102201. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102202. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102203. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102204. )
  102205. ts++;
  102206. if (ts === 4) // Only add point if it is inside all 4 triangles
  102207. manifold.addPoint(vec);
  102208. }
  102209. }
  102210. };
  102211. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102212. function tricheck(p, p0, p1, p2) {
  102213. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102214. var sg = A < 0 ? -1 : 1;
  102215. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102216. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102217. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102218. }
  102219. function pt(x, y) { return { x: x, y: y }; }
  102220. /**
  102221. * An axis-aligned bounding box.
  102222. * @author saharan
  102223. * @author lo-th
  102224. */
  102225. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102226. this.elements = new OIMO_ARRAY_TYPE(6);
  102227. var te = this.elements;
  102228. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102229. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102230. };
  102231. OIMO.AABB.prototype = {
  102232. constructor: OIMO.AABB,
  102233. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102234. var te = this.elements;
  102235. te[0] = minX; te[3] = maxX;
  102236. te[1] = minY; te[4] = maxY;
  102237. te[2] = minZ; te[5] = maxZ;
  102238. return this;
  102239. },
  102240. intersectTest: function (aabb) {
  102241. var te = this.elements;
  102242. var ue = aabb.elements;
  102243. 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];
  102244. },
  102245. intersectTestTwo: function (aabb) {
  102246. var te = this.elements;
  102247. var ue = aabb.elements;
  102248. 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];
  102249. },
  102250. clone: function () {
  102251. return new this.constructor().fromArray(this.elements);
  102252. },
  102253. copy: function (aabb, margin) {
  102254. var m = margin || 0;
  102255. var me = aabb.elements;
  102256. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102257. return this;
  102258. },
  102259. fromArray: function (array) {
  102260. this.elements.set(array);
  102261. return this;
  102262. },
  102263. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102264. combine: function (aabb1, aabb2) {
  102265. var a = aabb1.elements;
  102266. var b = aabb2.elements;
  102267. var te = this.elements;
  102268. te[0] = a[0] < b[0] ? a[0] : b[0];
  102269. te[1] = a[1] < b[1] ? a[1] : b[1];
  102270. te[2] = a[2] < b[2] ? a[2] : b[2];
  102271. te[3] = a[3] > b[3] ? a[3] : b[3];
  102272. te[4] = a[4] > b[4] ? a[4] : b[4];
  102273. te[5] = a[5] > b[5] ? a[5] : b[5];
  102274. return this;
  102275. },
  102276. // Get the surface area.
  102277. surfaceArea: function () {
  102278. var te = this.elements;
  102279. var a = te[3] - te[0];
  102280. var h = te[4] - te[1];
  102281. var d = te[5] - te[2];
  102282. return 2 * (a * (h + d) + h * d);
  102283. },
  102284. // Get whether the AABB intersects with the point or not.
  102285. intersectsWithPoint: function (x, y, z) {
  102286. var te = this.elements;
  102287. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102288. },
  102289. /**
  102290. * Set the AABB from an array
  102291. * of vertices. From THREE.
  102292. * @author mrdoob
  102293. * @author xprogram
  102294. */
  102295. setFromPoints: function (arr) {
  102296. this.makeEmpty();
  102297. for (var i = 0; i < arr.length; i++) {
  102298. this.expandByPoint(arr[i]);
  102299. }
  102300. },
  102301. makeEmpty: function () {
  102302. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102303. },
  102304. expandByPoint: function (pt) {
  102305. var te = this.elements;
  102306. this.set(
  102307. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102308. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102309. );
  102310. }
  102311. };
  102312. /**
  102313. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102314. */
  102315. OIMO.Proxy = function (shape) {
  102316. // The parent shape.
  102317. this.shape = shape;
  102318. // The axis-aligned bounding box.
  102319. this.aabb = shape.aabb;
  102320. };
  102321. OIMO.Proxy.prototype = {
  102322. constructor: OIMO.Proxy,
  102323. // Update the proxy.
  102324. update: function () {
  102325. OIMO.Error("Proxy", "Inheritance error.");
  102326. }
  102327. };
  102328. /**
  102329. * A basic implementation of proxies.
  102330. * @author saharan
  102331. */
  102332. OIMO.BasicProxy = function (shape) {
  102333. OIMO.Proxy.call(this, shape);
  102334. this.id = OIMO.proxyID++;
  102335. };
  102336. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102337. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102338. OIMO.BasicProxy.prototype.update = function () {
  102339. };
  102340. /**
  102341. * The broad-phase is used for collecting all possible pairs for collision.
  102342. */
  102343. OIMO.BroadPhase = function () {
  102344. this.types = OIMO.BR_NULL;
  102345. this.numPairChecks = 0;
  102346. this.numPairs = 0;
  102347. this.pairs = [];
  102348. };
  102349. OIMO.BroadPhase.prototype = {
  102350. constructor: OIMO.BroadPhase,
  102351. /**
  102352. * Create a new proxy.
  102353. * @param shape
  102354. * @return
  102355. */
  102356. createProxy: function (shape) {
  102357. OIMO.Error("BroadPhase", "Inheritance error.");
  102358. },
  102359. /**
  102360. * Add the proxy into the broad-phase.
  102361. * @param proxy
  102362. */
  102363. addProxy: function (proxy) {
  102364. OIMO.Error("BroadPhase", "Inheritance error.");
  102365. },
  102366. /**
  102367. * Remove the proxy from the broad-phase.
  102368. * @param proxy
  102369. */
  102370. removeProxy: function (proxy) {
  102371. OIMO.Error("BroadPhase", "Inheritance error.");
  102372. },
  102373. /**
  102374. * Returns whether the pair is available or not.
  102375. * @param s1
  102376. * @param s2
  102377. * @return
  102378. */
  102379. isAvailablePair: function (s1, s2) {
  102380. var b1 = s1.parent;
  102381. var b2 = s2.parent;
  102382. if (b1 == b2 || // same parents
  102383. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102384. (s1.belongsTo & s2.collidesWith) == 0 ||
  102385. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102386. ) { return false; }
  102387. var js;
  102388. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102389. else js = b2.jointLink;
  102390. while (js !== null) {
  102391. var joint = js.joint;
  102392. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102393. js = js.next;
  102394. }
  102395. return true;
  102396. },
  102397. // Detect overlapping pairs.
  102398. detectPairs: function () {
  102399. // clear old
  102400. this.pairs = [];
  102401. this.numPairs = 0;
  102402. this.numPairChecks = 0;
  102403. this.collectPairs();
  102404. },
  102405. collectPairs: function () {
  102406. OIMO.Error("BroadPhase", "Inheritance error.");
  102407. },
  102408. addPair: function (s1, s2) {
  102409. var pair = new OIMO.Pair(s1, s2);
  102410. this.pairs.push(pair);
  102411. this.numPairs++;
  102412. }
  102413. };
  102414. /**
  102415. * A broad-phase algorithm with brute-force search.
  102416. * This always checks for all possible pairs.
  102417. */
  102418. OIMO.BruteForceBroadPhase = function () {
  102419. OIMO.BroadPhase.call(this);
  102420. this.types = OIMO.BR_BRUTE_FORCE;;
  102421. //this.numProxies=0;
  102422. ///this.maxProxies = 256;
  102423. this.proxies = [];
  102424. //this.proxies.length = 256;
  102425. };
  102426. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102427. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102428. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102429. return new OIMO.BasicProxy(shape);
  102430. };
  102431. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102432. /*if(this.numProxies==this.maxProxies){
  102433. //this.maxProxies<<=1;
  102434. this.maxProxies*=2;
  102435. var newProxies=[];
  102436. newProxies.length = this.maxProxies;
  102437. var i = this.numProxies;
  102438. while(i--){
  102439. //for(var i=0, l=this.numProxies;i<l;i++){
  102440. newProxies[i]=this.proxies[i];
  102441. }
  102442. this.proxies=newProxies;
  102443. }*/
  102444. //this.proxies[this.numProxies++] = proxy;
  102445. this.proxies.push(proxy);
  102446. //this.numProxies++;
  102447. };
  102448. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102449. var n = this.proxies.indexOf(proxy);
  102450. if (n > -1) {
  102451. this.proxies.splice(n, 1);
  102452. //this.numProxies--;
  102453. }
  102454. /*var i = this.numProxies;
  102455. while(i--){
  102456. //for(var i=0, l=this.numProxies;i<l;i++){
  102457. if(this.proxies[i] == proxy){
  102458. this.proxies[i] = this.proxies[--this.numProxies];
  102459. this.proxies[this.numProxies] = null;
  102460. return;
  102461. }
  102462. }*/
  102463. };
  102464. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102465. var i = 0, j, p1, p2;
  102466. var px = this.proxies;
  102467. var l = px.length;//this.numProxies;
  102468. //var ar1 = [];
  102469. //var ar2 = [];
  102470. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102471. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102472. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102473. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102474. this.numPairChecks = l * (l - 1) >> 1;
  102475. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102476. while (i < l) {
  102477. p1 = px[i++];
  102478. j = i + 1;
  102479. while (j < l) {
  102480. p2 = px[j++];
  102481. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102482. this.addPair(p1.shape, p2.shape);
  102483. }
  102484. }
  102485. };
  102486. /**
  102487. * A pair of shapes that may collide.
  102488. * @author saharan
  102489. */
  102490. OIMO.Pair = function (s1, s2) {
  102491. // The first shape.
  102492. this.shape1 = s1 || null;
  102493. // The second shape.
  102494. this.shape2 = s2 || null;
  102495. };
  102496. /**
  102497. * A projection axis for sweep and prune broad-phase.
  102498. * @author saharan
  102499. */
  102500. OIMO.SAPAxis = function () {
  102501. this.numElements = 0;
  102502. this.bufferSize = 256;
  102503. this.elements = [];
  102504. this.elements.length = this.bufferSize;
  102505. this.stack = new OIMO_ARRAY_TYPE(64);
  102506. };
  102507. OIMO.SAPAxis.prototype = {
  102508. constructor: OIMO.SAPAxis,
  102509. addElements: function (min, max) {
  102510. if (this.numElements + 2 >= this.bufferSize) {
  102511. //this.bufferSize<<=1;
  102512. this.bufferSize *= 2;
  102513. var newElements = [];
  102514. var i = this.numElements;
  102515. while (i--) {
  102516. //for(var i=0, l=this.numElements; i<l; i++){
  102517. newElements[i] = this.elements[i];
  102518. }
  102519. }
  102520. this.elements[this.numElements++] = min;
  102521. this.elements[this.numElements++] = max;
  102522. },
  102523. removeElements: function (min, max) {
  102524. var minIndex = -1;
  102525. var maxIndex = -1;
  102526. for (var i = 0, l = this.numElements; i < l; i++) {
  102527. var e = this.elements[i];
  102528. if (e == min || e == max) {
  102529. if (minIndex == -1) {
  102530. minIndex = i;
  102531. } else {
  102532. maxIndex = i;
  102533. break;
  102534. }
  102535. }
  102536. }
  102537. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102538. this.elements[i - 1] = this.elements[i];
  102539. }
  102540. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102541. this.elements[i - 2] = this.elements[i];
  102542. }
  102543. this.elements[--this.numElements] = null;
  102544. this.elements[--this.numElements] = null;
  102545. },
  102546. sort: function () {
  102547. var count = 0;
  102548. var threshold = 1;
  102549. while ((this.numElements >> threshold) != 0) threshold++;
  102550. threshold = threshold * this.numElements >> 2;
  102551. count = 0;
  102552. var giveup = false;
  102553. var elements = this.elements;
  102554. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102555. var tmp = elements[i];
  102556. var pivot = tmp.value;
  102557. var tmp2 = elements[i - 1];
  102558. if (tmp2.value > pivot) {
  102559. var j = i;
  102560. do {
  102561. elements[j] = tmp2;
  102562. if (--j == 0) break;
  102563. tmp2 = elements[j - 1];
  102564. } while (tmp2.value > pivot);
  102565. elements[j] = tmp;
  102566. count += i - j;
  102567. if (count > threshold) {
  102568. giveup = true; // stop and use quick sort
  102569. break;
  102570. }
  102571. }
  102572. }
  102573. if (!giveup) return;
  102574. count = 2; var stack = this.stack;
  102575. stack[0] = 0;
  102576. stack[1] = this.numElements - 1;
  102577. while (count > 0) {
  102578. var right = stack[--count];
  102579. var left = stack[--count];
  102580. var diff = right - left;
  102581. if (diff > 16) { // quick sort
  102582. //var mid=left+(diff>>1);
  102583. var mid = left + (OIMO.floor(diff * 0.5));
  102584. tmp = elements[mid];
  102585. elements[mid] = elements[right];
  102586. elements[right] = tmp;
  102587. pivot = tmp.value;
  102588. i = left - 1;
  102589. j = right;
  102590. while (true) {
  102591. var ei;
  102592. var ej;
  102593. do { ei = elements[++i]; } while (ei.value < pivot);
  102594. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102595. if (i >= j) break;
  102596. elements[i] = ej;
  102597. elements[j] = ei;
  102598. }
  102599. elements[right] = elements[i];
  102600. elements[i] = tmp;
  102601. if (i - left > right - i) {
  102602. stack[count++] = left;
  102603. stack[count++] = i - 1;
  102604. stack[count++] = i + 1;
  102605. stack[count++] = right;
  102606. } else {
  102607. stack[count++] = i + 1;
  102608. stack[count++] = right;
  102609. stack[count++] = left;
  102610. stack[count++] = i - 1;
  102611. }
  102612. } else {
  102613. for (i = left + 1; i <= right; i++) {
  102614. tmp = elements[i];
  102615. pivot = tmp.value;
  102616. tmp2 = elements[i - 1];
  102617. if (tmp2.value > pivot) {
  102618. j = i;
  102619. do {
  102620. elements[j] = tmp2;
  102621. if (--j == 0) break;
  102622. tmp2 = elements[j - 1];
  102623. } while (tmp2.value > pivot);
  102624. elements[j] = tmp;
  102625. }
  102626. }
  102627. }
  102628. }
  102629. },
  102630. calculateTestCount: function () {
  102631. var num = 1;
  102632. var sum = 0;
  102633. for (var i = 1, l = this.numElements; i < l; i++) {
  102634. if (this.elements[i].max) {
  102635. num--;
  102636. } else {
  102637. sum += num;
  102638. num++;
  102639. }
  102640. }
  102641. return sum;
  102642. }
  102643. }
  102644. /**
  102645. * A broad-phase collision detection algorithm using sweep and prune.
  102646. * @author saharan
  102647. * @author lo-th
  102648. */
  102649. OIMO.SAPBroadPhase = function () {
  102650. OIMO.BroadPhase.call(this);
  102651. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102652. this.numElementsD = 0;
  102653. this.numElementsS = 0;
  102654. // dynamic proxies
  102655. this.axesD = [
  102656. new OIMO.SAPAxis(),
  102657. new OIMO.SAPAxis(),
  102658. new OIMO.SAPAxis()
  102659. ];
  102660. // static or sleeping proxies
  102661. this.axesS = [
  102662. new OIMO.SAPAxis(),
  102663. new OIMO.SAPAxis(),
  102664. new OIMO.SAPAxis()
  102665. ];
  102666. this.index1 = 0;
  102667. this.index2 = 1;
  102668. };
  102669. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102670. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102671. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102672. return new OIMO.SAPProxy(this, shape);
  102673. };
  102674. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102675. var p = proxy;
  102676. if (p.isDynamic()) {
  102677. this.axesD[0].addElements(p.min[0], p.max[0]);
  102678. this.axesD[1].addElements(p.min[1], p.max[1]);
  102679. this.axesD[2].addElements(p.min[2], p.max[2]);
  102680. p.belongsTo = 1;
  102681. this.numElementsD += 2;
  102682. } else {
  102683. this.axesS[0].addElements(p.min[0], p.max[0]);
  102684. this.axesS[1].addElements(p.min[1], p.max[1]);
  102685. this.axesS[2].addElements(p.min[2], p.max[2]);
  102686. p.belongsTo = 2;
  102687. this.numElementsS += 2;
  102688. }
  102689. };
  102690. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102691. var p = proxy;
  102692. if (p.belongsTo == 0) return;
  102693. /*else if ( p.belongsTo == 1 ) {
  102694. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102695. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102696. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102697. this.numElementsD -= 2;
  102698. } else if ( p.belongsTo == 2 ) {
  102699. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102700. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102701. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102702. this.numElementsS -= 2;
  102703. }*/
  102704. switch (p.belongsTo) {
  102705. case 1:
  102706. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102707. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102708. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102709. this.numElementsD -= 2;
  102710. break;
  102711. case 2:
  102712. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102713. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102714. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102715. this.numElementsS -= 2;
  102716. break;
  102717. }
  102718. p.belongsTo = 0;
  102719. };
  102720. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102721. if (this.numElementsD == 0) return;
  102722. var axis1 = this.axesD[this.index1];
  102723. var axis2 = this.axesD[this.index2];
  102724. axis1.sort();
  102725. axis2.sort();
  102726. var count1 = axis1.calculateTestCount();
  102727. var count2 = axis2.calculateTestCount();
  102728. var elementsD;
  102729. var elementsS;
  102730. if (count1 <= count2) {// select the best axis
  102731. axis2 = this.axesS[this.index1];
  102732. axis2.sort();
  102733. elementsD = axis1.elements;
  102734. elementsS = axis2.elements;
  102735. } else {
  102736. axis1 = this.axesS[this.index2];
  102737. axis1.sort();
  102738. elementsD = axis2.elements;
  102739. elementsS = axis1.elements;
  102740. this.index1 ^= this.index2;
  102741. this.index2 ^= this.index1;
  102742. this.index1 ^= this.index2;
  102743. }
  102744. var activeD;
  102745. var activeS;
  102746. var p = 0;
  102747. var q = 0;
  102748. while (p < this.numElementsD) {
  102749. var e1;
  102750. var dyn;
  102751. if (q == this.numElementsS) {
  102752. e1 = elementsD[p];
  102753. dyn = true;
  102754. p++;
  102755. } else {
  102756. var d = elementsD[p];
  102757. var s = elementsS[q];
  102758. if (d.value < s.value) {
  102759. e1 = d;
  102760. dyn = true;
  102761. p++;
  102762. } else {
  102763. e1 = s;
  102764. dyn = false;
  102765. q++;
  102766. }
  102767. }
  102768. if (!e1.max) {
  102769. var s1 = e1.proxy.shape;
  102770. var min1 = e1.min1.value;
  102771. var max1 = e1.max1.value;
  102772. var min2 = e1.min2.value;
  102773. var max2 = e1.max2.value;
  102774. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  102775. var s2 = e2.proxy.shape;
  102776. this.numPairChecks++;
  102777. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102778. this.addPair(s1, s2);
  102779. }
  102780. if (dyn) {
  102781. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  102782. s2 = e2.proxy.shape;
  102783. this.numPairChecks++;
  102784. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102785. this.addPair(s1, s2);
  102786. }
  102787. e1.pair = activeD;
  102788. activeD = e1;
  102789. } else {
  102790. e1.pair = activeS;
  102791. activeS = e1;
  102792. }
  102793. } else {
  102794. var min = e1.pair;
  102795. if (dyn) {
  102796. if (min == activeD) {
  102797. activeD = activeD.pair;
  102798. continue;
  102799. } else {
  102800. e1 = activeD;
  102801. }
  102802. } else {
  102803. if (min == activeS) {
  102804. activeS = activeS.pair;
  102805. continue;
  102806. } else {
  102807. e1 = activeS;
  102808. }
  102809. }
  102810. do {
  102811. e2 = e1.pair;
  102812. if (e2 == min) {
  102813. e1.pair = e2.pair;
  102814. break;
  102815. }
  102816. e1 = e2;
  102817. } while (e1 != null);
  102818. }
  102819. }
  102820. this.index2 = (this.index1 | this.index2) ^ 3;
  102821. };
  102822. /**
  102823. * An element of proxies.
  102824. * @author saharan
  102825. */
  102826. OIMO.SAPElement = function (proxy, max) {
  102827. // The parent proxy
  102828. this.proxy = proxy;
  102829. // The pair element.
  102830. this.pair = null;
  102831. // The minimum element on other axis.
  102832. this.min1 = null;
  102833. // The maximum element on other axis.
  102834. this.max1 = null;
  102835. // The minimum element on other axis.
  102836. this.min2 = null;
  102837. // The maximum element on other axis.
  102838. this.max2 = null;
  102839. // Whether the element has maximum value or not.
  102840. this.max = max;
  102841. // The value of the element.
  102842. this.value = 0;
  102843. };
  102844. /**
  102845. * A proxy for sweep and prune broad-phase.
  102846. * @author saharan
  102847. * @author lo-th
  102848. */
  102849. OIMO.SAPProxy = function (sap, shape) {
  102850. OIMO.Proxy.call(this, shape);
  102851. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  102852. this.belongsTo = 0;
  102853. // The maximum elements on each axis.
  102854. this.max = [];
  102855. // The minimum elements on each axis.
  102856. this.min = [];
  102857. this.sap = sap;
  102858. this.min[0] = new OIMO.SAPElement(this, false);
  102859. this.max[0] = new OIMO.SAPElement(this, true);
  102860. this.min[1] = new OIMO.SAPElement(this, false);
  102861. this.max[1] = new OIMO.SAPElement(this, true);
  102862. this.min[2] = new OIMO.SAPElement(this, false);
  102863. this.max[2] = new OIMO.SAPElement(this, true);
  102864. this.max[0].pair = this.min[0];
  102865. this.max[1].pair = this.min[1];
  102866. this.max[2].pair = this.min[2];
  102867. this.min[0].min1 = this.min[1];
  102868. this.min[0].max1 = this.max[1];
  102869. this.min[0].min2 = this.min[2];
  102870. this.min[0].max2 = this.max[2];
  102871. this.min[1].min1 = this.min[0];
  102872. this.min[1].max1 = this.max[0];
  102873. this.min[1].min2 = this.min[2];
  102874. this.min[1].max2 = this.max[2];
  102875. this.min[2].min1 = this.min[0];
  102876. this.min[2].max1 = this.max[0];
  102877. this.min[2].min2 = this.min[1];
  102878. this.min[2].max2 = this.max[1];
  102879. };
  102880. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102881. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  102882. // Returns whether the proxy is dynamic or not.
  102883. OIMO.SAPProxy.prototype.isDynamic = function () {
  102884. var body = this.shape.parent;
  102885. return body.isDynamic && !body.sleeping;
  102886. };
  102887. OIMO.SAPProxy.prototype.update = function () {
  102888. var te = this.aabb.elements;
  102889. this.min[0].value = te[0];
  102890. this.min[1].value = te[1];
  102891. this.min[2].value = te[2];
  102892. this.max[0].value = te[3];
  102893. this.max[1].value = te[4];
  102894. this.max[2].value = te[5];
  102895. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  102896. this.sap.removeProxy(this);
  102897. this.sap.addProxy(this);
  102898. }
  102899. };
  102900. /**
  102901. * A dynamic bounding volume tree for the broad-phase algorithm.
  102902. * @author saharan
  102903. * @author lo-th
  102904. */
  102905. OIMO.DBVT = function () {
  102906. // The root of the tree.
  102907. this.root = null;
  102908. this.freeNodes = [];
  102909. this.freeNodes.length = 16384;
  102910. this.numFreeNodes = 0;
  102911. this.aabb = new OIMO.AABB();
  102912. };
  102913. OIMO.DBVT.prototype = {
  102914. constructor: OIMO.DBVT,
  102915. /**
  102916. * Move a leaf.
  102917. * @param leaf
  102918. */
  102919. moveLeaf: function (leaf) {
  102920. this.deleteLeaf(leaf);
  102921. this.insertLeaf(leaf);
  102922. },
  102923. /**
  102924. * Insert a leaf to the tree.
  102925. * @param node
  102926. */
  102927. insertLeaf: function (leaf) {
  102928. if (this.root == null) {
  102929. this.root = leaf;
  102930. return;
  102931. }
  102932. var lb = leaf.aabb;
  102933. var sibling = this.root;
  102934. var oldArea;
  102935. var newArea;
  102936. while (sibling.proxy == null) { // descend the node to search the best pair
  102937. var c1 = sibling.child1;
  102938. var c2 = sibling.child2;
  102939. var b = sibling.aabb;
  102940. var c1b = c1.aabb;
  102941. var c2b = c2.aabb;
  102942. oldArea = b.surfaceArea();
  102943. this.aabb.combine(lb, b);
  102944. newArea = this.aabb.surfaceArea();
  102945. var creatingCost = newArea * 2;
  102946. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  102947. var discendingCost1 = incrementalCost;
  102948. this.aabb.combine(lb, c1b);
  102949. if (c1.proxy != null) {
  102950. // leaf cost = area(combined aabb)
  102951. discendingCost1 += this.aabb.surfaceArea();
  102952. } else {
  102953. // node cost = area(combined aabb) - area(old aabb)
  102954. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  102955. }
  102956. var discendingCost2 = incrementalCost;
  102957. this.aabb.combine(lb, c2b);
  102958. if (c2.proxy != null) {
  102959. // leaf cost = area(combined aabb)
  102960. discendingCost2 += this.aabb.surfaceArea();
  102961. } else {
  102962. // node cost = area(combined aabb) - area(old aabb)
  102963. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  102964. }
  102965. if (discendingCost1 < discendingCost2) {
  102966. if (creatingCost < discendingCost1) {
  102967. break;// stop descending
  102968. } else {
  102969. sibling = c1;// descend into first child
  102970. }
  102971. } else {
  102972. if (creatingCost < discendingCost2) {
  102973. break;// stop descending
  102974. } else {
  102975. sibling = c2;// descend into second child
  102976. }
  102977. }
  102978. }
  102979. var oldParent = sibling.parent;
  102980. var newParent;
  102981. if (this.numFreeNodes > 0) {
  102982. newParent = this.freeNodes[--this.numFreeNodes];
  102983. } else {
  102984. newParent = new OIMO.DBVTNode();
  102985. }
  102986. newParent.parent = oldParent;
  102987. newParent.child1 = leaf;
  102988. newParent.child2 = sibling;
  102989. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  102990. newParent.height = sibling.height + 1;
  102991. sibling.parent = newParent;
  102992. leaf.parent = newParent;
  102993. if (sibling == this.root) {
  102994. // replace root
  102995. this.root = newParent;
  102996. } else {
  102997. // replace child
  102998. if (oldParent.child1 == sibling) {
  102999. oldParent.child1 = newParent;
  103000. } else {
  103001. oldParent.child2 = newParent;
  103002. }
  103003. }
  103004. // update whole tree
  103005. do {
  103006. newParent = this.balance(newParent);
  103007. this.fix(newParent);
  103008. newParent = newParent.parent;
  103009. } while (newParent != null);
  103010. },
  103011. getBalance: function (node) {
  103012. if (node.proxy != null) return 0;
  103013. return node.child1.height - node.child2.height;
  103014. },
  103015. /*print:function(node,indent,text){
  103016. var hasChild=node.proxy==null;
  103017. if(hasChild)text=this.print(node.child1,indent+1,text);
  103018. for(var i=indent*2;i>=0;i--){
  103019. text+=" ";
  103020. }
  103021. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103022. if(hasChild)text=this.print(node.child2,indent+1,text);
  103023. return text;
  103024. },*/
  103025. /**
  103026. * Delete a leaf from the tree.
  103027. * @param node
  103028. */
  103029. deleteLeaf: function (leaf) {
  103030. if (leaf == this.root) {
  103031. this.root = null;
  103032. return;
  103033. }
  103034. var parent = leaf.parent;
  103035. var sibling;
  103036. if (parent.child1 == leaf) {
  103037. sibling = parent.child2;
  103038. } else {
  103039. sibling = parent.child1;
  103040. }
  103041. if (parent == this.root) {
  103042. this.root = sibling;
  103043. sibling.parent = null;
  103044. return;
  103045. }
  103046. var grandParent = parent.parent;
  103047. sibling.parent = grandParent;
  103048. if (grandParent.child1 == parent) {
  103049. grandParent.child1 = sibling;
  103050. } else {
  103051. grandParent.child2 = sibling;
  103052. }
  103053. if (this.numFreeNodes < 16384) {
  103054. this.freeNodes[this.numFreeNodes++] = parent;
  103055. }
  103056. do {
  103057. grandParent = this.balance(grandParent);
  103058. this.fix(grandParent);
  103059. grandParent = grandParent.parent;
  103060. } while (grandParent != null);
  103061. },
  103062. balance: function (node) {
  103063. var nh = node.height;
  103064. if (nh < 2) {
  103065. return node;
  103066. }
  103067. var p = node.parent;
  103068. var l = node.child1;
  103069. var r = node.child2;
  103070. var lh = l.height;
  103071. var rh = r.height;
  103072. var balance = lh - rh;
  103073. var t;// for bit operation
  103074. // [ N ]
  103075. // / \
  103076. // [ L ] [ R ]
  103077. // / \ / \
  103078. // [L-L] [L-R] [R-L] [R-R]
  103079. // Is the tree balanced?
  103080. if (balance > 1) {
  103081. var ll = l.child1;
  103082. var lr = l.child2;
  103083. var llh = ll.height;
  103084. var lrh = lr.height;
  103085. // Is L-L higher than L-R?
  103086. if (llh > lrh) {
  103087. // set N to L-R
  103088. l.child2 = node;
  103089. node.parent = l;
  103090. // [ L ]
  103091. // / \
  103092. // [L-L] [ N ]
  103093. // / \ / \
  103094. // [...] [...] [ L ] [ R ]
  103095. // set L-R
  103096. node.child1 = lr;
  103097. lr.parent = node;
  103098. // [ L ]
  103099. // / \
  103100. // [L-L] [ N ]
  103101. // / \ / \
  103102. // [...] [...] [L-R] [ R ]
  103103. // fix bounds and heights
  103104. node.aabb.combine(lr.aabb, r.aabb);
  103105. t = lrh - rh;
  103106. node.height = lrh - (t & t >> 31) + 1;
  103107. l.aabb.combine(ll.aabb, node.aabb);
  103108. t = llh - nh;
  103109. l.height = llh - (t & t >> 31) + 1;
  103110. } else {
  103111. // set N to L-L
  103112. l.child1 = node;
  103113. node.parent = l;
  103114. // [ L ]
  103115. // / \
  103116. // [ N ] [L-R]
  103117. // / \ / \
  103118. // [ L ] [ R ] [...] [...]
  103119. // set L-L
  103120. node.child1 = ll;
  103121. ll.parent = node;
  103122. // [ L ]
  103123. // / \
  103124. // [ N ] [L-R]
  103125. // / \ / \
  103126. // [L-L] [ R ] [...] [...]
  103127. // fix bounds and heights
  103128. node.aabb.combine(ll.aabb, r.aabb);
  103129. t = llh - rh;
  103130. node.height = llh - (t & t >> 31) + 1;
  103131. l.aabb.combine(node.aabb, lr.aabb);
  103132. t = nh - lrh;
  103133. l.height = nh - (t & t >> 31) + 1;
  103134. }
  103135. // set new parent of L
  103136. if (p != null) {
  103137. if (p.child1 == node) {
  103138. p.child1 = l;
  103139. } else {
  103140. p.child2 = l;
  103141. }
  103142. } else {
  103143. this.root = l;
  103144. }
  103145. l.parent = p;
  103146. return l;
  103147. } else if (balance < -1) {
  103148. var rl = r.child1;
  103149. var rr = r.child2;
  103150. var rlh = rl.height;
  103151. var rrh = rr.height;
  103152. // Is R-L higher than R-R?
  103153. if (rlh > rrh) {
  103154. // set N to R-R
  103155. r.child2 = node;
  103156. node.parent = r;
  103157. // [ R ]
  103158. // / \
  103159. // [R-L] [ N ]
  103160. // / \ / \
  103161. // [...] [...] [ L ] [ R ]
  103162. // set R-R
  103163. node.child2 = rr;
  103164. rr.parent = node;
  103165. // [ R ]
  103166. // / \
  103167. // [R-L] [ N ]
  103168. // / \ / \
  103169. // [...] [...] [ L ] [R-R]
  103170. // fix bounds and heights
  103171. node.aabb.combine(l.aabb, rr.aabb);
  103172. t = lh - rrh;
  103173. node.height = lh - (t & t >> 31) + 1;
  103174. r.aabb.combine(rl.aabb, node.aabb);
  103175. t = rlh - nh;
  103176. r.height = rlh - (t & t >> 31) + 1;
  103177. } else {
  103178. // set N to R-L
  103179. r.child1 = node;
  103180. node.parent = r;
  103181. // [ R ]
  103182. // / \
  103183. // [ N ] [R-R]
  103184. // / \ / \
  103185. // [ L ] [ R ] [...] [...]
  103186. // set R-L
  103187. node.child2 = rl;
  103188. rl.parent = node;
  103189. // [ R ]
  103190. // / \
  103191. // [ N ] [R-R]
  103192. // / \ / \
  103193. // [ L ] [R-L] [...] [...]
  103194. // fix bounds and heights
  103195. node.aabb.combine(l.aabb, rl.aabb);
  103196. t = lh - rlh;
  103197. node.height = lh - (t & t >> 31) + 1;
  103198. r.aabb.combine(node.aabb, rr.aabb);
  103199. t = nh - rrh;
  103200. r.height = nh - (t & t >> 31) + 1;
  103201. }
  103202. // set new parent of R
  103203. if (p != null) {
  103204. if (p.child1 == node) {
  103205. p.child1 = r;
  103206. } else {
  103207. p.child2 = r;
  103208. }
  103209. } else {
  103210. this.root = r;
  103211. }
  103212. r.parent = p;
  103213. return r;
  103214. }
  103215. return node;
  103216. },
  103217. fix: function (node) {
  103218. var c1 = node.child1;
  103219. var c2 = node.child2;
  103220. node.aabb.combine(c1.aabb, c2.aabb);
  103221. //var h1 = c1.height;
  103222. //var h2 = c2.height;
  103223. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103224. /*if( h1 < h2 ) {
  103225. node.height = h2+1;
  103226. }else{
  103227. node.height = h1+1;
  103228. }*/
  103229. }
  103230. }
  103231. /**
  103232. * A broad-phase algorithm using dynamic bounding volume tree.
  103233. * @author saharan
  103234. * @author lo-th
  103235. */
  103236. OIMO.DBVTBroadPhase = function () {
  103237. OIMO.BroadPhase.call(this);
  103238. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103239. this.tree = new OIMO.DBVT();
  103240. this.stack = [];
  103241. this.leaves = [];
  103242. this.numLeaves = 0;
  103243. };
  103244. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103245. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103246. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103247. return new OIMO.DBVTProxy(shape);
  103248. };
  103249. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103250. this.tree.insertLeaf(proxy.leaf);
  103251. this.leaves.push(proxy.leaf);
  103252. this.numLeaves++;
  103253. };
  103254. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103255. this.tree.deleteLeaf(proxy.leaf);
  103256. var n = this.leaves.indexOf(proxy.leaf);
  103257. if (n > -1) {
  103258. this.leaves.splice(n, 1);
  103259. this.numLeaves--;
  103260. }
  103261. };
  103262. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103263. if (this.numLeaves < 2) return;
  103264. var leaf, margin = 0.1, i = this.numLeaves;
  103265. while (i--) {
  103266. leaf = this.leaves[i];
  103267. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103268. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103269. this.tree.deleteLeaf(leaf);
  103270. this.tree.insertLeaf(leaf);
  103271. this.collide(leaf, this.tree.root);
  103272. }
  103273. }
  103274. };
  103275. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103276. var stackCount = 2;
  103277. var s1, s2, n1, n2, l1, l2;
  103278. this.stack[0] = node1;
  103279. this.stack[1] = node2;
  103280. while (stackCount > 0) {
  103281. n1 = this.stack[--stackCount];
  103282. n2 = this.stack[--stackCount];
  103283. l1 = n1.proxy != null;
  103284. l2 = n2.proxy != null;
  103285. this.numPairChecks++;
  103286. if (l1 && l2) {
  103287. s1 = n1.proxy.shape;
  103288. s2 = n2.proxy.shape;
  103289. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103290. this.addPair(s1, s2);
  103291. } else {
  103292. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103293. /*if(stackCount+4>=this.maxStack){// expand the stack
  103294. //this.maxStack<<=1;
  103295. this.maxStack*=2;
  103296. var newStack = [];// vector
  103297. newStack.length = this.maxStack;
  103298. for(var i=0;i<stackCount;i++){
  103299. newStack[i] = this.stack[i];
  103300. }
  103301. this.stack = newStack;
  103302. }*/
  103303. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103304. this.stack[stackCount++] = n1.child1;
  103305. this.stack[stackCount++] = n2;
  103306. this.stack[stackCount++] = n1.child2;
  103307. this.stack[stackCount++] = n2;
  103308. } else {
  103309. this.stack[stackCount++] = n1;
  103310. this.stack[stackCount++] = n2.child1;
  103311. this.stack[stackCount++] = n1;
  103312. this.stack[stackCount++] = n2.child2;
  103313. }
  103314. }
  103315. }
  103316. };
  103317. /**
  103318. * A node of the dynamic bounding volume tree.
  103319. * @author saharan
  103320. */
  103321. OIMO.DBVTNode = function () {
  103322. // The first child node of this node.
  103323. this.child1 = null;
  103324. // The second child node of this node.
  103325. this.child2 = null;
  103326. // The parent node of this tree.
  103327. this.parent = null;
  103328. // The proxy of this node. This has no value if this node is not leaf.
  103329. this.proxy = null;
  103330. // The maximum distance from leaf nodes.
  103331. this.height = 0;
  103332. // The AABB of this node.
  103333. this.aabb = new OIMO.AABB();
  103334. };
  103335. /**
  103336. * A proxy for dynamic bounding volume tree broad-phase.
  103337. * @author saharan
  103338. */
  103339. OIMO.DBVTProxy = function (shape) {
  103340. OIMO.Proxy.call(this, shape);
  103341. // The leaf of the proxy.
  103342. this.leaf = new OIMO.DBVTNode();
  103343. this.leaf.proxy = this;
  103344. };
  103345. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103346. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103347. OIMO.DBVTProxy.prototype.update = function () {
  103348. };
  103349. OIMO.World.prototype.add = function (obj) {
  103350. obj = obj || {};
  103351. var type = obj.type || "box";
  103352. if (typeof type === 'string') type = [type];// single shape
  103353. if (type[0].substring(0, 5) == 'joint') { // is joint
  103354. if (type[0] === 'joint') type[0] = 'jointHinge';
  103355. var axe1 = obj.axe1 || [1, 0, 0];
  103356. var axe2 = obj.axe2 || [1, 0, 0];
  103357. var pos1 = obj.pos1 || [0, 0, 0];
  103358. var pos2 = obj.pos2 || [0, 0, 0];
  103359. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103360. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103361. var min, max;
  103362. if (type[0] === "jointDistance") {
  103363. min = obj.min || 0;
  103364. max = obj.max || 10;
  103365. min = min * OIMO.INV_SCALE;
  103366. max = max * OIMO.INV_SCALE;
  103367. } else {
  103368. min = obj.min || 57.29578;
  103369. max = obj.max || 0;
  103370. min = min * OIMO.degtorad;
  103371. max = max * OIMO.degtorad;
  103372. }
  103373. var limit = obj.limit || null;
  103374. var spring = obj.spring || null;
  103375. var motor = obj.motor || null;
  103376. // joint setting
  103377. var jc = new OIMO.JointConfig();
  103378. jc.allowCollision = obj.collision || false;;
  103379. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103380. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103381. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103382. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103383. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103384. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103385. jc.body1 = obj.body1;
  103386. jc.body2 = obj.body2;
  103387. var joint;
  103388. switch (type[0]) {
  103389. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103390. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103391. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103392. break;
  103393. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103394. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103395. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103396. break;
  103397. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103398. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103399. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103400. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103401. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103402. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103403. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103404. break;
  103405. }
  103406. joint.name = obj.name || '';
  103407. // finaly add to physics world
  103408. this.addJoint(joint);
  103409. return joint;
  103410. } else { // is body
  103411. // I'm dynamique or not
  103412. var move = obj.move || false;
  103413. // I can sleep or not
  103414. var noSleep = obj.noSleep || false;
  103415. // My start position
  103416. var p = obj.pos || [0, 0, 0];
  103417. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103418. // My size
  103419. var s = obj.size || [1, 1, 1];
  103420. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103421. // My rotation in degre
  103422. var rot = obj.rot || [0, 0, 0];
  103423. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103424. var r = [];
  103425. for (var i = 0; i < rot.length / 3; i++) {
  103426. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103427. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103428. }
  103429. // My physics setting
  103430. var sc = new OIMO.ShapeConfig();
  103431. if (obj.sc !== undefined) sc = obj.sc;
  103432. if (obj.config) {
  103433. // The density of the shape.
  103434. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103435. // The coefficient of friction of the shape.
  103436. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103437. // The coefficient of restitution of the shape.
  103438. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103439. // The bits of the collision groups to which the shape belongs.
  103440. sc.belongsTo = obj.config[3] || 1;
  103441. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103442. // The bits of the collision groups with which the shape collides.
  103443. sc.collidesWith = obj.config[4] || 0xffffffff;
  103444. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103445. }
  103446. // direct physics setting
  103447. if (obj.density !== undefined) sc.density = obj.density;
  103448. if (obj.friction !== undefined) sc.friction = obj.friction;
  103449. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103450. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103451. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103452. if (obj.massPos) {
  103453. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103454. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103455. }
  103456. if (obj.massRot) {
  103457. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103458. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103459. }
  103460. // My rigidbody
  103461. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103462. // My shapes
  103463. var shapes = [];
  103464. //if( typeof type === 'string' ) type = [type];// single shape
  103465. var n, n2;
  103466. for (var i = 0; i < type.length; i++) {
  103467. n = i * 3;
  103468. n2 = i * 4;
  103469. switch (type[i]) {
  103470. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103471. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103472. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103473. }
  103474. body.addShape(shapes[i]);
  103475. if (i > 0) {
  103476. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103477. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103478. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103479. }
  103480. }
  103481. // I'm static or i move
  103482. if (move) {
  103483. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103484. else body.setupMass(0x1, true);
  103485. if (noSleep) body.allowSleep = false;
  103486. else body.allowSleep = true;
  103487. } else {
  103488. body.setupMass(0x2);
  103489. }
  103490. body.name = obj.name || ' ';
  103491. // finaly add to physics world
  103492. this.addRigidBody(body);
  103493. return body;
  103494. }
  103495. }
  103496. //UMD simplified
  103497. var root = this;
  103498. if (!root['OIMO']) {
  103499. if (true)
  103500. module.exports = OIMO;
  103501. else if (typeof define === 'function' && define.amd)
  103502. define([], function () {
  103503. return OIMO;
  103504. });
  103505. else if (typeof exports === 'object')
  103506. exports["OIMO"] = OIMO;
  103507. else {
  103508. root["OIMO"] = OIMO;
  103509. }
  103510. }
  103511. /***/ }),
  103512. /* 19 */
  103513. /***/ (function(module, exports, __webpack_require__) {
  103514. "use strict";
  103515. Object.defineProperty(exports, "__esModule", { value: true });
  103516. var babylonjs_1 = __webpack_require__(0);
  103517. var helper_1 = __webpack_require__(2);
  103518. var TemplateManager = (function () {
  103519. function TemplateManager(containerElement) {
  103520. this.containerElement = containerElement;
  103521. this.templates = {};
  103522. this.onInit = new babylonjs_1.Observable();
  103523. this.onLoaded = new babylonjs_1.Observable();
  103524. this.onStateChange = new babylonjs_1.Observable();
  103525. this.onAllLoaded = new babylonjs_1.Observable();
  103526. this.onEventTriggered = new babylonjs_1.Observable();
  103527. this.eventManager = new eventManager_1.EventManager(this);
  103528. }
  103529. TemplateManager.prototype.initTemplate = function (templates) {
  103530. var _this = this;
  103531. var internalInit = function (dependencyMap, name, parentTemplate) {
  103532. var template = _this.templates[name];
  103533. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103534. return internalInit(dependencyMap[childName], childName, template);
  103535. });
  103536. var addToParent = function () {
  103537. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103538. template.appendTo(containingElement);
  103539. _this.checkLoadedState();
  103540. };
  103541. if (parentTemplate && !parentTemplate.parent) {
  103542. parentTemplate.onAppended.add(function () {
  103543. addToParent();
  103544. });
  103545. }
  103546. else {
  103547. addToParent();
  103548. }
  103549. return template;
  103550. };
  103551. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103552. if (_this.templates['main']) {
  103553. internalInit(htmlTree, 'main');
  103554. }
  103555. else {
  103556. _this.checkLoadedState();
  103557. }
  103558. return;
  103559. });
  103560. };
  103561. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103562. var _this = this;
  103563. var promises = Object.keys(templates).map(function (name) {
  103564. if (!templates[name])
  103565. return Promise.resolve(false);
  103566. var template = new Template(name, templates[name]);
  103567. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103568. _this.templates[name] = template;
  103569. return template.initPromise;
  103570. });
  103571. return Promise.all(promises).then(function () {
  103572. var templateStructure = {};
  103573. var buildTree = function (parentObject, name) {
  103574. _this.templates[name].isInHtmlTree = true;
  103575. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103576. childNodes.forEach(function (element) {
  103577. parentObject[element] = {};
  103578. buildTree(parentObject[element], element);
  103579. });
  103580. };
  103581. if (_this.templates['main']) {
  103582. buildTree(templateStructure, "main");
  103583. }
  103584. return templateStructure;
  103585. });
  103586. };
  103587. TemplateManager.prototype.getCanvas = function () {
  103588. return this.containerElement.querySelector('canvas');
  103589. };
  103590. TemplateManager.prototype.getTemplate = function (name) {
  103591. return this.templates[name];
  103592. };
  103593. TemplateManager.prototype.checkLoadedState = function () {
  103594. var _this = this;
  103595. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103596. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103597. });
  103598. if (done) {
  103599. this.onAllLoaded.notifyObservers(this);
  103600. }
  103601. };
  103602. TemplateManager.prototype.dispose = function () {
  103603. var _this = this;
  103604. Object.keys(this.templates).forEach(function (template) {
  103605. _this.templates[template].dispose();
  103606. });
  103607. this.onInit.clear();
  103608. this.onAllLoaded.clear();
  103609. this.onEventTriggered.clear();
  103610. this.onLoaded.clear();
  103611. this.onStateChange.clear();
  103612. };
  103613. return TemplateManager;
  103614. }());
  103615. exports.TemplateManager = TemplateManager;
  103616. var Handlebars = __webpack_require__(20);
  103617. var eventManager_1 = __webpack_require__(21);
  103618. Handlebars.registerHelper('eachInMap', function (map, block) {
  103619. var out = '';
  103620. Object.keys(map).map(function (prop) {
  103621. var data = map[prop];
  103622. if (typeof data === 'object') {
  103623. data.id = data.id || prop;
  103624. out += block.fn(data);
  103625. }
  103626. else {
  103627. out += block.fn({ id: prop, value: data });
  103628. }
  103629. });
  103630. return out;
  103631. });
  103632. var Template = (function () {
  103633. function Template(name, _configuration) {
  103634. var _this = this;
  103635. this.name = name;
  103636. this._configuration = _configuration;
  103637. this.onInit = new babylonjs_1.Observable();
  103638. this.onLoaded = new babylonjs_1.Observable();
  103639. this.onAppended = new babylonjs_1.Observable();
  103640. this.onStateChange = new babylonjs_1.Observable();
  103641. this.onEventTriggered = new babylonjs_1.Observable();
  103642. this.loadRequests = [];
  103643. this.isLoaded = false;
  103644. this.isShown = false;
  103645. this.isInHtmlTree = false;
  103646. this.onInit.notifyObservers(this);
  103647. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103648. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103649. if (htmlTemplate) {
  103650. _this.htmlTemplate = htmlTemplate;
  103651. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103652. var config = _this._configuration.params || {};
  103653. var rawHtml = compiledTemplate(config);
  103654. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103655. _this.isLoaded = true;
  103656. _this.isShown = true;
  103657. _this.onLoaded.notifyObservers(_this);
  103658. }
  103659. return _this;
  103660. });
  103661. }
  103662. Template.prototype.updateParams = function (params) {
  103663. this._configuration.params = params;
  103664. if (this.isLoaded) {
  103665. this.dispose();
  103666. }
  103667. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103668. var config = this._configuration.params || {};
  103669. var rawHtml = compiledTemplate(config);
  103670. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103671. if (this.parent) {
  103672. this.appendTo(this.parent, true);
  103673. }
  103674. };
  103675. Object.defineProperty(Template.prototype, "configuration", {
  103676. get: function () {
  103677. return this._configuration;
  103678. },
  103679. enumerable: true,
  103680. configurable: true
  103681. });
  103682. Template.prototype.getChildElements = function () {
  103683. var childrenArray = [];
  103684. var children = this.fragment.children;
  103685. if (!children) {
  103686. children = this.fragment.querySelectorAll('*');
  103687. }
  103688. for (var i = 0; i < children.length; ++i) {
  103689. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103690. }
  103691. return childrenArray;
  103692. };
  103693. Template.prototype.appendTo = function (parent, forceRemove) {
  103694. var _this = this;
  103695. if (this.parent) {
  103696. if (forceRemove) {
  103697. this.parent.removeChild(this.fragment);
  103698. }
  103699. else {
  103700. return;
  103701. }
  103702. }
  103703. this.parent = parent;
  103704. if (this._configuration.id) {
  103705. this.parent.id = this._configuration.id;
  103706. }
  103707. this.fragment = this.parent.appendChild(this.fragment);
  103708. setTimeout(function () {
  103709. _this.registerEvents();
  103710. _this.onAppended.notifyObservers(_this);
  103711. });
  103712. };
  103713. Template.prototype.show = function (visibilityFunction) {
  103714. var _this = this;
  103715. if (this.isHiding)
  103716. return Promise.resolve(this);
  103717. return Promise.resolve().then(function () {
  103718. _this.isShowing = true;
  103719. if (visibilityFunction) {
  103720. return visibilityFunction(_this);
  103721. }
  103722. else {
  103723. _this.parent.style.display = 'flex';
  103724. return _this;
  103725. }
  103726. }).then(function () {
  103727. _this.isShown = true;
  103728. _this.isShowing = false;
  103729. _this.onStateChange.notifyObservers(_this);
  103730. return _this;
  103731. });
  103732. };
  103733. Template.prototype.hide = function (visibilityFunction) {
  103734. var _this = this;
  103735. if (this.isShowing)
  103736. return Promise.resolve(this);
  103737. return Promise.resolve().then(function () {
  103738. _this.isHiding = true;
  103739. if (visibilityFunction) {
  103740. return visibilityFunction(_this);
  103741. }
  103742. else {
  103743. _this.parent.style.display = 'hide';
  103744. return _this;
  103745. }
  103746. }).then(function () {
  103747. _this.isShown = false;
  103748. _this.isHiding = false;
  103749. _this.onStateChange.notifyObservers(_this);
  103750. return _this;
  103751. });
  103752. };
  103753. Template.prototype.dispose = function () {
  103754. this.onAppended.clear();
  103755. this.onEventTriggered.clear();
  103756. this.onInit.clear();
  103757. this.onLoaded.clear();
  103758. this.onStateChange.clear();
  103759. this.isLoaded = false;
  103760. this.parent.removeChild(this.fragment);
  103761. this.loadRequests.forEach(function (request) {
  103762. request.abort();
  103763. });
  103764. };
  103765. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  103766. var _this = this;
  103767. if (!templateConfig) {
  103768. return Promise.reject('No templateConfig provided');
  103769. }
  103770. else if (templateConfig.html !== undefined) {
  103771. return Promise.resolve(templateConfig.html);
  103772. }
  103773. else {
  103774. var location_1 = getTemplateLocation(templateConfig);
  103775. if (helper_1.isUrl(location_1)) {
  103776. return new Promise(function (resolve, reject) {
  103777. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  103778. resolve(data);
  103779. }, undefined, undefined, false, function (request, error) {
  103780. reject(error);
  103781. });
  103782. _this.loadRequests.push(fileRequest);
  103783. });
  103784. }
  103785. else {
  103786. location_1 = location_1.replace('#', '');
  103787. var element = document.getElementById(location_1);
  103788. if (element) {
  103789. return Promise.resolve(element.innerHTML);
  103790. }
  103791. else {
  103792. return Promise.reject('Template ID not found');
  103793. }
  103794. }
  103795. }
  103796. };
  103797. Template.prototype.registerEvents = function () {
  103798. var _this = this;
  103799. this.registeredEvents = this.registeredEvents || [];
  103800. if (this.registeredEvents.length) {
  103801. this.registeredEvents.forEach(function (evt) {
  103802. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  103803. });
  103804. }
  103805. if (this._configuration.events) {
  103806. var _loop_1 = function (eventName) {
  103807. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  103808. var functionToFire_1 = function (selector, event) {
  103809. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  103810. };
  103811. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  103812. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  103813. }
  103814. else if (typeof this_1._configuration.events[eventName] === 'object') {
  103815. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  103816. var event_1 = this_1._configuration.events[eventName] || {};
  103817. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  103818. if (selector && selector.indexOf('#') !== 0) {
  103819. selector = '#' + selector;
  103820. }
  103821. var htmlElement = _this.parent.querySelector(selector);
  103822. if (htmlElement) {
  103823. var binding = functionToFire_1.bind(_this, selector);
  103824. htmlElement.addEventListener(eventName, binding, false);
  103825. _this.registeredEvents.push({
  103826. htmlElement: htmlElement,
  103827. eventName: eventName,
  103828. function: binding
  103829. });
  103830. }
  103831. });
  103832. }
  103833. }
  103834. };
  103835. var this_1 = this;
  103836. for (var eventName in this._configuration.events) {
  103837. _loop_1(eventName);
  103838. }
  103839. }
  103840. };
  103841. return Template;
  103842. }());
  103843. exports.Template = Template;
  103844. function getTemplateLocation(templateConfig) {
  103845. if (!templateConfig || typeof templateConfig === 'string') {
  103846. return templateConfig;
  103847. }
  103848. else {
  103849. return templateConfig.location;
  103850. }
  103851. }
  103852. exports.getTemplateLocation = getTemplateLocation;
  103853. /***/ }),
  103854. /* 20 */
  103855. /***/ (function(module, exports, __webpack_require__) {
  103856. /**!
  103857. @license
  103858. handlebars v4.0.11
  103859. Copyright (C) 2011-2017 by Yehuda Katz
  103860. Permission is hereby granted, free of charge, to any person obtaining a copy
  103861. of this software and associated documentation files (the "Software"), to deal
  103862. in the Software without restriction, including without limitation the rights
  103863. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  103864. copies of the Software, and to permit persons to whom the Software is
  103865. furnished to do so, subject to the following conditions:
  103866. The above copyright notice and this permission notice shall be included in
  103867. all copies or substantial portions of the Software.
  103868. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  103869. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  103870. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  103871. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  103872. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  103873. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  103874. THE SOFTWARE.
  103875. */
  103876. !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],
  103877. 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){
  103878. 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"]}])});
  103879. /***/ }),
  103880. /* 21 */
  103881. /***/ (function(module, exports, __webpack_require__) {
  103882. "use strict";
  103883. Object.defineProperty(exports, "__esModule", { value: true });
  103884. var EventManager = (function () {
  103885. function EventManager(templateManager) {
  103886. var _this = this;
  103887. this.templateManager = templateManager;
  103888. this.callbacksContainer = {};
  103889. this.templateManager.onEventTriggered.add(function (eventData) {
  103890. _this.eventTriggered(eventData);
  103891. });
  103892. }
  103893. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  103894. if (!this.callbacksContainer[templateName]) {
  103895. this.callbacksContainer[templateName] = [];
  103896. }
  103897. this.callbacksContainer[templateName].push({
  103898. eventType: eventType,
  103899. callback: callback
  103900. });
  103901. };
  103902. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  103903. var callbackDefs = this.callbacksContainer[templateName] || [];
  103904. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  103905. };
  103906. EventManager.prototype.eventTriggered = function (data) {
  103907. var templateName = data.template.name;
  103908. var eventType = data.event.type;
  103909. var selector = data.selector;
  103910. var callbackDefs = this.callbacksContainer[templateName] || [];
  103911. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  103912. callbackDef.callback(data);
  103913. });
  103914. };
  103915. return EventManager;
  103916. }());
  103917. exports.EventManager = EventManager;
  103918. /***/ }),
  103919. /* 22 */
  103920. /***/ (function(module, exports, __webpack_require__) {
  103921. "use strict";
  103922. Object.defineProperty(exports, "__esModule", { value: true });
  103923. var mappers_1 = __webpack_require__(1);
  103924. var types_1 = __webpack_require__(23);
  103925. var deepmerge = __webpack_require__(13);
  103926. var babylonjs_1 = __webpack_require__(0);
  103927. var ConfigurationLoader = (function () {
  103928. function ConfigurationLoader() {
  103929. this.configurationCache = {};
  103930. this.loadRequests = [];
  103931. }
  103932. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  103933. var _this = this;
  103934. if (initConfig === void 0) { initConfig = {}; }
  103935. var loadedConfig = deepmerge({}, initConfig);
  103936. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  103937. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  103938. if (loadedConfig.configuration) {
  103939. var mapperType_1 = "json";
  103940. return Promise.resolve().then(function () {
  103941. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  103942. var url = '';
  103943. if (typeof loadedConfig.configuration === "string") {
  103944. url = loadedConfig.configuration;
  103945. }
  103946. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  103947. url = loadedConfig.configuration.url;
  103948. var type = loadedConfig.configuration.mapper;
  103949. if (!type) {
  103950. type = loadedConfig.configuration.url.split('.').pop();
  103951. }
  103952. mapperType_1 = type || mapperType_1;
  103953. }
  103954. return _this.loadFile(url);
  103955. }
  103956. else {
  103957. if (typeof loadedConfig.configuration === "object") {
  103958. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  103959. return loadedConfig.configuration.payload || {};
  103960. }
  103961. return {};
  103962. }
  103963. }).then(function (data) {
  103964. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  103965. var parsed = mapper.map(data);
  103966. var merged = deepmerge(loadedConfig, parsed);
  103967. if (callback)
  103968. callback(merged);
  103969. return merged;
  103970. });
  103971. }
  103972. else {
  103973. if (callback)
  103974. callback(loadedConfig);
  103975. return Promise.resolve(loadedConfig);
  103976. }
  103977. };
  103978. ConfigurationLoader.prototype.dispose = function () {
  103979. this.loadRequests.forEach(function (request) {
  103980. request.abort();
  103981. });
  103982. };
  103983. ConfigurationLoader.prototype.loadFile = function (url) {
  103984. var _this = this;
  103985. var cacheReference = this.configurationCache;
  103986. if (cacheReference[url]) {
  103987. return Promise.resolve(cacheReference[url]);
  103988. }
  103989. return new Promise(function (resolve, reject) {
  103990. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  103991. reject(error);
  103992. });
  103993. _this.loadRequests.push(fileRequest);
  103994. });
  103995. };
  103996. return ConfigurationLoader;
  103997. }());
  103998. exports.ConfigurationLoader = ConfigurationLoader;
  103999. exports.configurationLoader = new ConfigurationLoader();
  104000. exports.default = exports.configurationLoader;
  104001. /***/ }),
  104002. /* 23 */
  104003. /***/ (function(module, exports, __webpack_require__) {
  104004. "use strict";
  104005. Object.defineProperty(exports, "__esModule", { value: true });
  104006. var minimal_1 = __webpack_require__(24);
  104007. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104008. var default_1 = __webpack_require__(25);
  104009. exports.defaultConfiguration = default_1.defaultConfiguration;
  104010. var getConfigurationType = function (type) {
  104011. switch (type) {
  104012. case 'default':
  104013. return default_1.defaultConfiguration;
  104014. case 'minimal':
  104015. return minimal_1.minimalConfiguration;
  104016. case 'none':
  104017. return {};
  104018. default:
  104019. return default_1.defaultConfiguration;
  104020. }
  104021. };
  104022. exports.getConfigurationType = getConfigurationType;
  104023. /***/ }),
  104024. /* 24 */
  104025. /***/ (function(module, exports, __webpack_require__) {
  104026. "use strict";
  104027. Object.defineProperty(exports, "__esModule", { value: true });
  104028. exports.minimalConfiguration = {
  104029. version: "0.1",
  104030. templates: {
  104031. main: {
  104032. html: __webpack_require__(6)
  104033. },
  104034. loadingScreen: {
  104035. html: __webpack_require__(7),
  104036. params: {
  104037. backgroundColor: "#000000",
  104038. loadingImage: __webpack_require__(8)
  104039. }
  104040. },
  104041. viewer: {
  104042. html: __webpack_require__(9),
  104043. },
  104044. overlay: {
  104045. html: __webpack_require__(10),
  104046. params: {
  104047. closeImage: __webpack_require__(11),
  104048. closeText: 'Close'
  104049. }
  104050. },
  104051. error: {
  104052. html: __webpack_require__(12)
  104053. }
  104054. },
  104055. engine: {
  104056. antialiasing: true
  104057. }
  104058. };
  104059. /***/ }),
  104060. /* 25 */
  104061. /***/ (function(module, exports, __webpack_require__) {
  104062. "use strict";
  104063. Object.defineProperty(exports, "__esModule", { value: true });
  104064. exports.defaultConfiguration = {
  104065. version: "3.2.0-alpha4",
  104066. templates: {
  104067. main: {
  104068. html: __webpack_require__(6)
  104069. },
  104070. loadingScreen: {
  104071. html: __webpack_require__(7),
  104072. params: {
  104073. backgroundColor: "#000000",
  104074. loadingImage: __webpack_require__(8)
  104075. }
  104076. },
  104077. viewer: {
  104078. html: __webpack_require__(9),
  104079. events: {
  104080. pointerout: true,
  104081. pointerdown: true,
  104082. pointerup: true
  104083. }
  104084. },
  104085. navBar: {
  104086. html: __webpack_require__(26),
  104087. params: {
  104088. buttons: {
  104089. "fullscreen-button": {
  104090. altText: "Fullscreen",
  104091. image: __webpack_require__(27)
  104092. }
  104093. },
  104094. visibilityTimeout: 2000
  104095. },
  104096. events: {
  104097. pointerdown: { 'fullscreen-button': true },
  104098. pointerover: true
  104099. }
  104100. },
  104101. overlay: {
  104102. html: __webpack_require__(10),
  104103. params: {
  104104. closeImage: __webpack_require__(11),
  104105. closeText: 'Close'
  104106. }
  104107. },
  104108. help: {
  104109. html: __webpack_require__(28)
  104110. },
  104111. share: {
  104112. html: __webpack_require__(29)
  104113. },
  104114. error: {
  104115. html: __webpack_require__(12)
  104116. }
  104117. },
  104118. camera: {
  104119. behaviors: {
  104120. autoRotate: 0,
  104121. framing: {
  104122. type: 2,
  104123. zoomOnBoundingInfo: true,
  104124. zoomStopsAnimation: false
  104125. }
  104126. }
  104127. },
  104128. skybox: {
  104129. pbr: true,
  104130. blur: 0.7,
  104131. infiniteDIstance: false,
  104132. },
  104133. ground: true,
  104134. engine: {
  104135. antialiasing: true
  104136. },
  104137. scene: {
  104138. imageProcessingConfiguration: {
  104139. exposure: 1.4,
  104140. contrast: 1.66,
  104141. toneMappingEnabled: true
  104142. }
  104143. }
  104144. };
  104145. /***/ }),
  104146. /* 26 */
  104147. /***/ (function(module, exports) {
  104148. 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>";
  104149. /***/ }),
  104150. /* 27 */
  104151. /***/ (function(module, exports) {
  104152. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104153. /***/ }),
  104154. /* 28 */
  104155. /***/ (function(module, exports) {
  104156. module.exports = "HELP";
  104157. /***/ }),
  104158. /* 29 */
  104159. /***/ (function(module, exports) {
  104160. module.exports = "SHARE";
  104161. /***/ }),
  104162. /* 30 */
  104163. /***/ (function(module, exports, __webpack_require__) {
  104164. "use strict";
  104165. Object.defineProperty(exports, "__esModule", { value: true });
  104166. var babylonjs_1 = __webpack_require__(0);
  104167. var modelAnimation_1 = __webpack_require__(31);
  104168. var ViewerModel = (function () {
  104169. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104170. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104171. this._modelConfiguration = _modelConfiguration;
  104172. this._scene = _scene;
  104173. this.onLoadedObservable = new babylonjs_1.Observable();
  104174. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104175. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104176. this._animations = [];
  104177. if (!disableAutoLoad) {
  104178. this._initLoad();
  104179. }
  104180. }
  104181. ViewerModel.prototype.load = function () {
  104182. if (this.loader) {
  104183. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104184. }
  104185. else {
  104186. this._initLoad();
  104187. }
  104188. };
  104189. ViewerModel.prototype.getAnimationNames = function () {
  104190. return this._animations.map(function (a) { return a.name; });
  104191. };
  104192. ViewerModel.prototype._getAnimationByName = function (name) {
  104193. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104194. if (filtered.length === 1) {
  104195. return filtered[0];
  104196. }
  104197. else {
  104198. return null;
  104199. }
  104200. };
  104201. ViewerModel.prototype.playAnimation = function (name) {
  104202. var animation = this._getAnimationByName(name);
  104203. if (animation) {
  104204. if (this.currentAnimation) {
  104205. this.currentAnimation.stop();
  104206. }
  104207. this.currentAnimation = animation;
  104208. animation.start();
  104209. return animation;
  104210. }
  104211. else {
  104212. throw new Error("animation not found - " + name);
  104213. }
  104214. };
  104215. ViewerModel.prototype._initLoad = function () {
  104216. var _this = this;
  104217. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104218. return babylonjs_1.Tools.Error("No model URL to load.");
  104219. }
  104220. var parts = this._modelConfiguration.url.split('/');
  104221. var filename = parts.pop() || this._modelConfiguration.url;
  104222. var base = parts.length ? parts.join('/') + '/' : './';
  104223. var plugin = this._modelConfiguration.loader;
  104224. var animationsArray = this._scene.animationGroups.slice();
  104225. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104226. meshes.forEach(function (mesh) {
  104227. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104228. });
  104229. _this.meshes = meshes;
  104230. _this.particleSystems = particleSystems;
  104231. _this.skeletons = skeletons;
  104232. if (_this.loader.name === 'gltf') {
  104233. _this._scene.animationGroups.forEach(function (ag) {
  104234. if (animationsArray.indexOf(ag) === -1) {
  104235. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104236. }
  104237. });
  104238. }
  104239. else {
  104240. skeletons.forEach(function (skeleton, idx) {
  104241. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104242. skeleton.getAnimatables().forEach(function (a) {
  104243. if (a.animations[0]) {
  104244. ag.addTargetedAnimation(a.animations[0], a);
  104245. }
  104246. });
  104247. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104248. });
  104249. }
  104250. if (_this._modelConfiguration.animation) {
  104251. if (_this._modelConfiguration.animation.playOnce) {
  104252. _this._animations.forEach(function (a) {
  104253. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104254. });
  104255. }
  104256. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104257. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104258. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104259. _this.playAnimation(animationName);
  104260. }
  104261. }
  104262. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104263. }, function (progressEvent) {
  104264. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104265. }, function (e, m, exception) {
  104266. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104267. }, plugin);
  104268. this.loader['animationStartMode'] = 0;
  104269. };
  104270. ViewerModel.prototype.dispose = function () {
  104271. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104272. this.skeletons.forEach(function (s) { return s.dispose(); });
  104273. this._animations.forEach(function (ag) { return ag.dispose(); });
  104274. this.meshes.forEach(function (m) { return m.dispose(); });
  104275. };
  104276. return ViewerModel;
  104277. }());
  104278. exports.ViewerModel = ViewerModel;
  104279. /***/ }),
  104280. /* 31 */
  104281. /***/ (function(module, exports, __webpack_require__) {
  104282. "use strict";
  104283. Object.defineProperty(exports, "__esModule", { value: true });
  104284. var AnimationPlayMode;
  104285. (function (AnimationPlayMode) {
  104286. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104287. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104288. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104289. var AnimationState;
  104290. (function (AnimationState) {
  104291. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104292. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104293. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104294. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104295. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104296. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104297. var GroupModelAnimation = (function () {
  104298. function GroupModelAnimation(_animationGroup) {
  104299. var _this = this;
  104300. this._animationGroup = _animationGroup;
  104301. this._state = AnimationState.INIT;
  104302. this._playMode = AnimationPlayMode.LOOP;
  104303. this._animationGroup.onAnimationEndObservable.add(function () {
  104304. _this.stop();
  104305. _this._state = AnimationState.ENDED;
  104306. });
  104307. }
  104308. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104309. get: function () {
  104310. return this._animationGroup.name;
  104311. },
  104312. enumerable: true,
  104313. configurable: true
  104314. });
  104315. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104316. get: function () {
  104317. return this._state;
  104318. },
  104319. enumerable: true,
  104320. configurable: true
  104321. });
  104322. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104323. get: function () {
  104324. return this._animationGroup.speedRatio;
  104325. },
  104326. set: function (value) {
  104327. this._animationGroup.speedRatio = value;
  104328. },
  104329. enumerable: true,
  104330. configurable: true
  104331. });
  104332. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104333. get: function () {
  104334. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104335. var keys = ta.animation.getKeys();
  104336. return keys[keys.length - 1].frame;
  104337. });
  104338. return Math.max.apply(null, animationFrames);
  104339. },
  104340. enumerable: true,
  104341. configurable: true
  104342. });
  104343. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104344. get: function () {
  104345. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104346. var animatable = this._animationGroup.animatables[i];
  104347. var animations = animatable.getAnimations();
  104348. if (!animations || !animations.length) {
  104349. continue;
  104350. }
  104351. for (var idx = 0; idx < animations.length; ++idx) {
  104352. if (animations[idx].currentFrame) {
  104353. return animations[idx].currentFrame;
  104354. }
  104355. }
  104356. }
  104357. return 0;
  104358. },
  104359. enumerable: true,
  104360. configurable: true
  104361. });
  104362. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104363. get: function () {
  104364. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104365. var animatable = this._animationGroup.animatables[i];
  104366. var animations = animatable.getAnimations();
  104367. if (!animations || !animations.length) {
  104368. continue;
  104369. }
  104370. for (var idx = 0; idx < animations.length; ++idx) {
  104371. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104372. return animations[idx].animation.framePerSecond;
  104373. }
  104374. }
  104375. }
  104376. return 0;
  104377. },
  104378. enumerable: true,
  104379. configurable: true
  104380. });
  104381. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104382. get: function () {
  104383. return this._playMode;
  104384. },
  104385. set: function (value) {
  104386. if (value === this._playMode) {
  104387. return;
  104388. }
  104389. this._playMode = value;
  104390. if (this.state === AnimationState.PLAYING) {
  104391. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104392. }
  104393. else {
  104394. this._animationGroup.reset();
  104395. this._state = AnimationState.INIT;
  104396. }
  104397. },
  104398. enumerable: true,
  104399. configurable: true
  104400. });
  104401. GroupModelAnimation.prototype.reset = function () {
  104402. this._animationGroup.reset();
  104403. };
  104404. GroupModelAnimation.prototype.restart = function () {
  104405. this._animationGroup.restart();
  104406. };
  104407. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104408. this._animationGroup['_animatables'].forEach(function (a) {
  104409. a.goToFrame(frameNumber);
  104410. });
  104411. };
  104412. GroupModelAnimation.prototype.start = function () {
  104413. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104414. if (this._animationGroup.isStarted) {
  104415. this._state = AnimationState.PLAYING;
  104416. }
  104417. };
  104418. GroupModelAnimation.prototype.pause = function () {
  104419. this._animationGroup.pause();
  104420. this._state = AnimationState.PAUSED;
  104421. };
  104422. GroupModelAnimation.prototype.stop = function () {
  104423. this._animationGroup.stop();
  104424. if (!this._animationGroup.isStarted) {
  104425. this._state = AnimationState.STOPPED;
  104426. }
  104427. };
  104428. GroupModelAnimation.prototype.dispose = function () {
  104429. this._animationGroup.dispose();
  104430. };
  104431. return GroupModelAnimation;
  104432. }());
  104433. exports.GroupModelAnimation = GroupModelAnimation;
  104434. /***/ }),
  104435. /* 32 */
  104436. /***/ (function(module, exports, __webpack_require__) {
  104437. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  104438. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  104439. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  104440. 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;
  104441. return c > 3 && r && Object.defineProperty(target, key, r), r;
  104442. };
  104443. var __extends = (this && this.__extends) || (function () {
  104444. var extendStatics = Object.setPrototypeOf ||
  104445. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104446. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104447. return function (d, b) {
  104448. extendStatics(d, b);
  104449. function __() { this.constructor = d; }
  104450. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104451. };
  104452. })();
  104453. (function universalModuleDefinition(root, factory) {
  104454. if(true)
  104455. module.exports = factory(__webpack_require__(0));
  104456. else if(typeof define === 'function' && define.amd)
  104457. define("babylonjs-loaders", ["babylonjs"], factory);
  104458. else if(typeof exports === 'object')
  104459. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  104460. else {
  104461. root["BABYLON"] = factory(root["BABYLON"]);
  104462. }
  104463. })(this, function(BABYLON) {
  104464. var BABYLON;
  104465. (function (BABYLON) {
  104466. var STLFileLoader = /** @class */ (function () {
  104467. function STLFileLoader() {
  104468. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104469. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104470. 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;
  104471. 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;
  104472. this.name = "stl";
  104473. // force data to come in as an ArrayBuffer
  104474. // we'll convert to string if it looks like it's an ASCII .stl
  104475. this.extensions = {
  104476. ".stl": { isBinary: true },
  104477. };
  104478. }
  104479. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104480. var matches;
  104481. if (this.isBinary(data)) {
  104482. // binary .stl
  104483. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104484. this.parseBinary(babylonMesh, data);
  104485. if (meshes) {
  104486. meshes.push(babylonMesh);
  104487. }
  104488. return true;
  104489. }
  104490. // ASCII .stl
  104491. // convert to string
  104492. var array_buffer = new Uint8Array(data);
  104493. var str = '';
  104494. for (var i = 0; i < data.byteLength; i++) {
  104495. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104496. }
  104497. data = str;
  104498. while (matches = this.solidPattern.exec(data)) {
  104499. var meshName = matches[1];
  104500. var meshNameFromEnd = matches[3];
  104501. if (meshName != meshNameFromEnd) {
  104502. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104503. return false;
  104504. }
  104505. // check meshesNames
  104506. if (meshesNames && meshName) {
  104507. if (meshesNames instanceof Array) {
  104508. if (!meshesNames.indexOf(meshName)) {
  104509. continue;
  104510. }
  104511. }
  104512. else {
  104513. if (meshName !== meshesNames) {
  104514. continue;
  104515. }
  104516. }
  104517. }
  104518. // stl mesh name can be empty as well
  104519. meshName = meshName || "stlmesh";
  104520. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104521. this.parseASCII(babylonMesh, matches[2]);
  104522. if (meshes) {
  104523. meshes.push(babylonMesh);
  104524. }
  104525. }
  104526. return true;
  104527. };
  104528. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104529. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104530. if (result) {
  104531. scene.createDefaultCameraOrLight();
  104532. }
  104533. return result;
  104534. };
  104535. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104536. var container = new BABYLON.AssetContainer(scene);
  104537. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104538. container.removeAllFromScene();
  104539. return container;
  104540. };
  104541. STLFileLoader.prototype.isBinary = function (data) {
  104542. // check if file size is correct for binary stl
  104543. var faceSize, nFaces, reader;
  104544. reader = new DataView(data);
  104545. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104546. nFaces = reader.getUint32(80, true);
  104547. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104548. return true;
  104549. }
  104550. // check characters higher than ASCII to confirm binary
  104551. var fileLength = reader.byteLength;
  104552. for (var index = 0; index < fileLength; index++) {
  104553. if (reader.getUint8(index) > 127) {
  104554. return true;
  104555. }
  104556. }
  104557. return false;
  104558. };
  104559. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104560. var reader = new DataView(data);
  104561. var faces = reader.getUint32(80, true);
  104562. var dataOffset = 84;
  104563. var faceLength = 12 * 4 + 2;
  104564. var offset = 0;
  104565. var positions = new Float32Array(faces * 3 * 3);
  104566. var normals = new Float32Array(faces * 3 * 3);
  104567. var indices = new Uint32Array(faces * 3);
  104568. var indicesCount = 0;
  104569. for (var face = 0; face < faces; face++) {
  104570. var start = dataOffset + face * faceLength;
  104571. var normalX = reader.getFloat32(start, true);
  104572. var normalY = reader.getFloat32(start + 4, true);
  104573. var normalZ = reader.getFloat32(start + 8, true);
  104574. for (var i = 1; i <= 3; i++) {
  104575. var vertexstart = start + i * 12;
  104576. // ordering is intentional to match ascii import
  104577. positions[offset] = reader.getFloat32(vertexstart, true);
  104578. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104579. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104580. normals[offset] = normalX;
  104581. normals[offset + 2] = normalY;
  104582. normals[offset + 1] = normalZ;
  104583. offset += 3;
  104584. }
  104585. indices[indicesCount] = indicesCount++;
  104586. indices[indicesCount] = indicesCount++;
  104587. indices[indicesCount] = indicesCount++;
  104588. }
  104589. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104590. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104591. mesh.setIndices(indices);
  104592. mesh.computeWorldMatrix(true);
  104593. };
  104594. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104595. var positions = [];
  104596. var normals = [];
  104597. var indices = [];
  104598. var indicesCount = 0;
  104599. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104600. var matches;
  104601. while (matches = this.facetsPattern.exec(solidData)) {
  104602. var facet = matches[1];
  104603. //one normal per face
  104604. var normalMatches = this.normalPattern.exec(facet);
  104605. this.normalPattern.lastIndex = 0;
  104606. if (!normalMatches) {
  104607. continue;
  104608. }
  104609. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104610. var vertexMatch;
  104611. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104612. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104613. normals.push(normal[0], normal[1], normal[2]);
  104614. }
  104615. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104616. this.vertexPattern.lastIndex = 0;
  104617. }
  104618. this.facetsPattern.lastIndex = 0;
  104619. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104620. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104621. mesh.setIndices(indices);
  104622. mesh.computeWorldMatrix(true);
  104623. };
  104624. return STLFileLoader;
  104625. }());
  104626. BABYLON.STLFileLoader = STLFileLoader;
  104627. if (BABYLON.SceneLoader) {
  104628. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104629. }
  104630. })(BABYLON || (BABYLON = {}));
  104631. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104632. var BABYLON;
  104633. (function (BABYLON) {
  104634. /**
  104635. * Class reading and parsing the MTL file bundled with the obj file.
  104636. */
  104637. var MTLFileLoader = /** @class */ (function () {
  104638. function MTLFileLoader() {
  104639. // All material loaded from the mtl will be set here
  104640. this.materials = [];
  104641. }
  104642. /**
  104643. * This function will read the mtl file and create each material described inside
  104644. * This function could be improve by adding :
  104645. * -some component missing (Ni, Tf...)
  104646. * -including the specific options available
  104647. *
  104648. * @param scene
  104649. * @param data
  104650. * @param rootUrl
  104651. */
  104652. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104653. //Split the lines from the file
  104654. var lines = data.split('\n');
  104655. //Space char
  104656. var delimiter_pattern = /\s+/;
  104657. //Array with RGB colors
  104658. var color;
  104659. //New material
  104660. var material = null;
  104661. //Look at each line
  104662. for (var i = 0; i < lines.length; i++) {
  104663. var line = lines[i].trim();
  104664. // Blank line or comment
  104665. if (line.length === 0 || line.charAt(0) === '#') {
  104666. continue;
  104667. }
  104668. //Get the first parameter (keyword)
  104669. var pos = line.indexOf(' ');
  104670. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104671. key = key.toLowerCase();
  104672. //Get the data following the key
  104673. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104674. //This mtl keyword will create the new material
  104675. if (key === "newmtl") {
  104676. //Check if it is the first material.
  104677. // Materials specifications are described after this keyword.
  104678. if (material) {
  104679. //Add the previous material in the material array.
  104680. this.materials.push(material);
  104681. }
  104682. //Create a new material.
  104683. // value is the name of the material read in the mtl file
  104684. material = new BABYLON.StandardMaterial(value, scene);
  104685. }
  104686. else if (key === "kd" && material) {
  104687. // Diffuse color (color under white light) using RGB values
  104688. //value = "r g b"
  104689. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104690. //color = [r,g,b]
  104691. //Set tghe color into the material
  104692. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104693. }
  104694. else if (key === "ka" && material) {
  104695. // Ambient color (color under shadow) using RGB values
  104696. //value = "r g b"
  104697. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104698. //color = [r,g,b]
  104699. //Set tghe color into the material
  104700. material.ambientColor = BABYLON.Color3.FromArray(color);
  104701. }
  104702. else if (key === "ks" && material) {
  104703. // Specular color (color when light is reflected from shiny surface) using RGB values
  104704. //value = "r g b"
  104705. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104706. //color = [r,g,b]
  104707. //Set the color into the material
  104708. material.specularColor = BABYLON.Color3.FromArray(color);
  104709. }
  104710. else if (key === "ke" && material) {
  104711. // Emissive color using RGB values
  104712. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104713. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104714. }
  104715. else if (key === "ns" && material) {
  104716. //value = "Integer"
  104717. material.specularPower = parseFloat(value);
  104718. }
  104719. else if (key === "d" && material) {
  104720. //d is dissolve for current material. It mean alpha for BABYLON
  104721. material.alpha = parseFloat(value);
  104722. //Texture
  104723. //This part can be improved by adding the possible options of texture
  104724. }
  104725. else if (key === "map_ka" && material) {
  104726. // ambient texture map with a loaded image
  104727. //We must first get the folder of the image
  104728. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104729. }
  104730. else if (key === "map_kd" && material) {
  104731. // Diffuse texture map with a loaded image
  104732. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104733. }
  104734. else if (key === "map_ks" && material) {
  104735. // Specular texture map with a loaded image
  104736. //We must first get the folder of the image
  104737. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104738. }
  104739. else if (key === "map_ns") {
  104740. //Specular
  104741. //Specular highlight component
  104742. //We must first get the folder of the image
  104743. //
  104744. //Not supported by BABYLON
  104745. //
  104746. // continue;
  104747. }
  104748. else if (key === "map_bump" && material) {
  104749. //The bump texture
  104750. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104751. }
  104752. else if (key === "map_d" && material) {
  104753. // The dissolve of the material
  104754. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104755. //Options for illumination
  104756. }
  104757. else if (key === "illum") {
  104758. //Illumination
  104759. if (value === "0") {
  104760. //That mean Kd == Kd
  104761. }
  104762. else if (value === "1") {
  104763. //Color on and Ambient on
  104764. }
  104765. else if (value === "2") {
  104766. //Highlight on
  104767. }
  104768. else if (value === "3") {
  104769. //Reflection on and Ray trace on
  104770. }
  104771. else if (value === "4") {
  104772. //Transparency: Glass on, Reflection: Ray trace on
  104773. }
  104774. else if (value === "5") {
  104775. //Reflection: Fresnel on and Ray trace on
  104776. }
  104777. else if (value === "6") {
  104778. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  104779. }
  104780. else if (value === "7") {
  104781. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  104782. }
  104783. else if (value === "8") {
  104784. //Reflection on and Ray trace off
  104785. }
  104786. else if (value === "9") {
  104787. //Transparency: Glass on, Reflection: Ray trace off
  104788. }
  104789. else if (value === "10") {
  104790. //Casts shadows onto invisible surfaces
  104791. }
  104792. }
  104793. else {
  104794. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  104795. }
  104796. }
  104797. //At the end of the file, add the last material
  104798. if (material) {
  104799. this.materials.push(material);
  104800. }
  104801. };
  104802. /**
  104803. * Gets the texture for the material.
  104804. *
  104805. * If the material is imported from input file,
  104806. * We sanitize the url to ensure it takes the textre from aside the material.
  104807. *
  104808. * @param rootUrl The root url to load from
  104809. * @param value The value stored in the mtl
  104810. * @return The Texture
  104811. */
  104812. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  104813. if (!value) {
  104814. return null;
  104815. }
  104816. var url = rootUrl;
  104817. // Load from input file.
  104818. if (rootUrl === "file:") {
  104819. var lastDelimiter = value.lastIndexOf("\\");
  104820. if (lastDelimiter === -1) {
  104821. lastDelimiter = value.lastIndexOf("/");
  104822. }
  104823. if (lastDelimiter > -1) {
  104824. url += value.substr(lastDelimiter + 1);
  104825. }
  104826. else {
  104827. url += value;
  104828. }
  104829. }
  104830. else {
  104831. url += value;
  104832. }
  104833. return new BABYLON.Texture(url, scene);
  104834. };
  104835. return MTLFileLoader;
  104836. }());
  104837. BABYLON.MTLFileLoader = MTLFileLoader;
  104838. var OBJFileLoader = /** @class */ (function () {
  104839. function OBJFileLoader() {
  104840. this.name = "obj";
  104841. this.extensions = ".obj";
  104842. this.obj = /^o/;
  104843. this.group = /^g/;
  104844. this.mtllib = /^mtllib /;
  104845. this.usemtl = /^usemtl /;
  104846. this.smooth = /^s /;
  104847. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104848. // vn float float float
  104849. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104850. // vt float float
  104851. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104852. // f vertex vertex vertex ...
  104853. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  104854. // f vertex/uvs vertex/uvs vertex/uvs ...
  104855. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104856. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  104857. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104858. // f vertex//normal vertex//normal vertex//normal ...
  104859. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  104860. }
  104861. /**
  104862. * Calls synchronously the MTL file attached to this obj.
  104863. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  104864. * Without this function materials are not displayed in the first frame (but displayed after).
  104865. * In consequence it is impossible to get material information in your HTML file
  104866. *
  104867. * @param url The URL of the MTL file
  104868. * @param rootUrl
  104869. * @param onSuccess Callback function to be called when the MTL file is loaded
  104870. * @private
  104871. */
  104872. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  104873. //The complete path to the mtl file
  104874. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  104875. // Loads through the babylon tools to allow fileInput search.
  104876. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  104877. };
  104878. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104879. //get the meshes from OBJ file
  104880. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  104881. //Push meshes from OBJ file into the variable mesh of this function
  104882. if (meshes) {
  104883. loadedMeshes.forEach(function (mesh) {
  104884. meshes.push(mesh);
  104885. });
  104886. }
  104887. return true;
  104888. };
  104889. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  104890. //Get the 3D model
  104891. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  104892. };
  104893. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104894. var container = new BABYLON.AssetContainer(scene);
  104895. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104896. container.removeAllFromScene();
  104897. return container;
  104898. };
  104899. /**
  104900. * Read the OBJ file and create an Array of meshes.
  104901. * Each mesh contains all information given by the OBJ and the MTL file.
  104902. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  104903. *
  104904. * @param meshesNames
  104905. * @param scene BABYLON.Scene The scene where are displayed the data
  104906. * @param data String The content of the obj file
  104907. * @param rootUrl String The path to the folder
  104908. * @returns Array<AbstractMesh>
  104909. * @private
  104910. */
  104911. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  104912. var positions = []; //values for the positions of vertices
  104913. var normals = []; //Values for the normals
  104914. var uvs = []; //Values for the textures
  104915. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  104916. var handledMesh; //The current mesh of meshes array
  104917. var indicesForBabylon = []; //The list of indices for VertexData
  104918. var wrappedPositionForBabylon = []; //The list of position in vectors
  104919. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  104920. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  104921. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  104922. var curPositionInIndices = 0;
  104923. var hasMeshes = false; //Meshes are defined in the file
  104924. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  104925. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  104926. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  104927. var triangles = []; //Indices from new triangles coming from polygons
  104928. var materialNameFromObj = ""; //The name of the current material
  104929. var fileToLoad = ""; //The name of the mtlFile to load
  104930. var materialsFromMTLFile = new MTLFileLoader();
  104931. var objMeshName = ""; //The name of the current obj mesh
  104932. var increment = 1; //Id for meshes created by the multimaterial
  104933. var isFirstMaterial = true;
  104934. /**
  104935. * Search for obj in the given array.
  104936. * This function is called to check if a couple of data already exists in an array.
  104937. *
  104938. * If found, returns the index of the founded tuple index. Returns -1 if not found
  104939. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  104940. * @param obj Array<number>
  104941. * @returns {boolean}
  104942. */
  104943. var isInArray = function (arr, obj) {
  104944. if (!arr[obj[0]])
  104945. arr[obj[0]] = { normals: [], idx: [] };
  104946. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104947. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  104948. };
  104949. var isInArrayUV = function (arr, obj) {
  104950. if (!arr[obj[0]])
  104951. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  104952. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104953. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  104954. return arr[obj[0]].idx[idx];
  104955. }
  104956. return -1;
  104957. };
  104958. /**
  104959. * This function set the data for each triangle.
  104960. * Data are position, normals and uvs
  104961. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  104962. * If the tuple already exist, add only their indice
  104963. *
  104964. * @param indicePositionFromObj Integer The index in positions array
  104965. * @param indiceUvsFromObj Integer The index in uvs array
  104966. * @param indiceNormalFromObj Integer The index in normals array
  104967. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  104968. * @param textureVectorFromOBJ Vector3 The value of uvs
  104969. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  104970. */
  104971. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  104972. //Check if this tuple already exists in the list of tuples
  104973. var _index;
  104974. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  104975. _index = isInArrayUV(tuplePosNorm, [
  104976. indicePositionFromObj,
  104977. indiceNormalFromObj,
  104978. indiceUvsFromObj
  104979. ]);
  104980. }
  104981. else {
  104982. _index = isInArray(tuplePosNorm, [
  104983. indicePositionFromObj,
  104984. indiceNormalFromObj
  104985. ]);
  104986. }
  104987. //If it not exists
  104988. if (_index == -1) {
  104989. //Add an new indice.
  104990. //The array of indices is only an array with his length equal to the number of triangles - 1.
  104991. //We add vertices data in this order
  104992. indicesForBabylon.push(wrappedPositionForBabylon.length);
  104993. //Push the position of vertice for Babylon
  104994. //Each element is a BABYLON.Vector3(x,y,z)
  104995. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  104996. //Push the uvs for Babylon
  104997. //Each element is a BABYLON.Vector3(u,v)
  104998. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  104999. //Push the normals for Babylon
  105000. //Each element is a BABYLON.Vector3(x,y,z)
  105001. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105002. //Add the tuple in the comparison list
  105003. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105004. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105005. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105006. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105007. }
  105008. else {
  105009. //The tuple already exists
  105010. //Add the index of the already existing tuple
  105011. //At this index we can get the value of position, normal and uvs of vertex
  105012. indicesForBabylon.push(_index);
  105013. }
  105014. };
  105015. /**
  105016. * Transform BABYLON.Vector() object onto 3 digits in an array
  105017. */
  105018. var unwrapData = function () {
  105019. //Every array has the same length
  105020. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105021. //Push the x, y, z values of each element in the unwrapped array
  105022. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105023. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105024. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105025. }
  105026. // Reset arrays for the next new meshes
  105027. wrappedPositionForBabylon = [];
  105028. wrappedNormalsForBabylon = [];
  105029. wrappedUvsForBabylon = [];
  105030. tuplePosNorm = [];
  105031. curPositionInIndices = 0;
  105032. };
  105033. /**
  105034. * Create triangles from polygons by recursion
  105035. * The best to understand how it works is to draw it in the same time you get the recursion.
  105036. * It is important to notice that a triangle is a polygon
  105037. * We get 4 patterns of face defined in OBJ File :
  105038. * facePattern1 = ["1","2","3","4","5","6"]
  105039. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105040. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105041. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105042. * Each pattern is divided by the same method
  105043. * @param face Array[String] The indices of elements
  105044. * @param v Integer The variable to increment
  105045. */
  105046. var getTriangles = function (face, v) {
  105047. //Work for each element of the array
  105048. if (v + 1 < face.length) {
  105049. //Add on the triangle variable the indexes to obtain triangles
  105050. triangles.push(face[0], face[v], face[v + 1]);
  105051. //Incrementation for recursion
  105052. v += 1;
  105053. //Recursion
  105054. getTriangles(face, v);
  105055. }
  105056. //Result obtained after 2 iterations:
  105057. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105058. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105059. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105060. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105061. };
  105062. /**
  105063. * Create triangles and push the data for each polygon for the pattern 1
  105064. * In this pattern we get vertice positions
  105065. * @param face
  105066. * @param v
  105067. */
  105068. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105069. //Get the indices of triangles for each polygon
  105070. getTriangles(face, v);
  105071. //For each element in the triangles array.
  105072. //This var could contains 1 to an infinity of triangles
  105073. for (var k = 0; k < triangles.length; k++) {
  105074. // Set position indice
  105075. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105076. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105077. positions[indicePositionFromObj], //Get the vectors data
  105078. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105079. );
  105080. }
  105081. //Reset variable for the next line
  105082. triangles = [];
  105083. };
  105084. /**
  105085. * Create triangles and push the data for each polygon for the pattern 2
  105086. * In this pattern we get vertice positions and uvsu
  105087. * @param face
  105088. * @param v
  105089. */
  105090. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105091. //Get the indices of triangles for each polygon
  105092. getTriangles(face, v);
  105093. for (var k = 0; k < triangles.length; k++) {
  105094. //triangle[k] = "1/1"
  105095. //Split the data for getting position and uv
  105096. var point = triangles[k].split("/"); // ["1", "1"]
  105097. //Set position indice
  105098. var indicePositionFromObj = parseInt(point[0]) - 1;
  105099. //Set uv indice
  105100. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105101. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105102. positions[indicePositionFromObj], //Get the values for each element
  105103. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105104. );
  105105. }
  105106. //Reset variable for the next line
  105107. triangles = [];
  105108. };
  105109. /**
  105110. * Create triangles and push the data for each polygon for the pattern 3
  105111. * In this pattern we get vertice positions, uvs and normals
  105112. * @param face
  105113. * @param v
  105114. */
  105115. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105116. //Get the indices of triangles for each polygon
  105117. getTriangles(face, v);
  105118. for (var k = 0; k < triangles.length; k++) {
  105119. //triangle[k] = "1/1/1"
  105120. //Split the data for getting position, uv, and normals
  105121. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105122. // Set position indice
  105123. var indicePositionFromObj = parseInt(point[0]) - 1;
  105124. // Set uv indice
  105125. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105126. // Set normal indice
  105127. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105128. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105129. );
  105130. }
  105131. //Reset variable for the next line
  105132. triangles = [];
  105133. };
  105134. /**
  105135. * Create triangles and push the data for each polygon for the pattern 4
  105136. * In this pattern we get vertice positions and normals
  105137. * @param face
  105138. * @param v
  105139. */
  105140. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105141. getTriangles(face, v);
  105142. for (var k = 0; k < triangles.length; k++) {
  105143. //triangle[k] = "1//1"
  105144. //Split the data for getting position and normals
  105145. var point = triangles[k].split("//"); // ["1", "1"]
  105146. // We check indices, and normals
  105147. var indicePositionFromObj = parseInt(point[0]) - 1;
  105148. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105149. setData(indicePositionFromObj, 1, //Default value for uv
  105150. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105151. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105152. }
  105153. //Reset variable for the next line
  105154. triangles = [];
  105155. };
  105156. var addPreviousObjMesh = function () {
  105157. //Check if it is not the first mesh. Otherwise we don't have data.
  105158. if (meshesFromObj.length > 0) {
  105159. //Get the previous mesh for applying the data about the faces
  105160. //=> in obj file, faces definition append after the name of the mesh
  105161. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105162. //Set the data into Array for the mesh
  105163. unwrapData();
  105164. // Reverse tab. Otherwise face are displayed in the wrong sens
  105165. indicesForBabylon.reverse();
  105166. //Set the information for the mesh
  105167. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105168. handledMesh.indices = indicesForBabylon.slice();
  105169. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105170. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105171. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105172. //Reset the array for the next mesh
  105173. indicesForBabylon = [];
  105174. unwrappedPositionsForBabylon = [];
  105175. unwrappedNormalsForBabylon = [];
  105176. unwrappedUVForBabylon = [];
  105177. }
  105178. };
  105179. //Main function
  105180. //Split the file into lines
  105181. var lines = data.split('\n');
  105182. //Look at each line
  105183. for (var i = 0; i < lines.length; i++) {
  105184. var line = lines[i].trim();
  105185. var result;
  105186. //Comment or newLine
  105187. if (line.length === 0 || line.charAt(0) === '#') {
  105188. continue;
  105189. //Get information about one position possible for the vertices
  105190. }
  105191. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105192. //Create a Vector3 with the position x, y, z
  105193. //Value of result:
  105194. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105195. //Add the Vector in the list of positions
  105196. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105197. }
  105198. else if ((result = this.normalPattern.exec(line)) !== null) {
  105199. //Create a Vector3 with the normals x, y, z
  105200. //Value of result
  105201. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105202. //Add the Vector in the list of normals
  105203. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105204. }
  105205. else if ((result = this.uvPattern.exec(line)) !== null) {
  105206. //Create a Vector2 with the normals u, v
  105207. //Value of result
  105208. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105209. //Add the Vector in the list of uvs
  105210. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105211. //Identify patterns of faces
  105212. //Face could be defined in different type of pattern
  105213. }
  105214. else if ((result = this.facePattern3.exec(line)) !== null) {
  105215. //Value of result:
  105216. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105217. //Set the data for this face
  105218. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105219. 1);
  105220. }
  105221. else if ((result = this.facePattern4.exec(line)) !== null) {
  105222. //Value of result:
  105223. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105224. //Set the data for this face
  105225. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105226. 1);
  105227. }
  105228. else if ((result = this.facePattern2.exec(line)) !== null) {
  105229. //Value of result:
  105230. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105231. //Set the data for this face
  105232. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105233. 1);
  105234. }
  105235. else if ((result = this.facePattern1.exec(line)) !== null) {
  105236. //Value of result
  105237. //["f 1 2 3", "1 2 3"...]
  105238. //Set the data for this face
  105239. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105240. 1);
  105241. //Define a mesh or an object
  105242. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105243. }
  105244. else if (this.group.test(line) || this.obj.test(line)) {
  105245. //Create a new mesh corresponding to the name of the group.
  105246. //Definition of the mesh
  105247. var objMesh =
  105248. //Set the name of the current obj mesh
  105249. {
  105250. name: line.substring(2).trim(),
  105251. indices: undefined,
  105252. positions: undefined,
  105253. normals: undefined,
  105254. uvs: undefined,
  105255. materialName: ""
  105256. };
  105257. addPreviousObjMesh();
  105258. //Push the last mesh created with only the name
  105259. meshesFromObj.push(objMesh);
  105260. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105261. hasMeshes = true;
  105262. isFirstMaterial = true;
  105263. increment = 1;
  105264. //Keyword for applying a material
  105265. }
  105266. else if (this.usemtl.test(line)) {
  105267. //Get the name of the material
  105268. materialNameFromObj = line.substring(7).trim();
  105269. //If this new material is in the same mesh
  105270. if (!isFirstMaterial) {
  105271. //Set the data for the previous mesh
  105272. addPreviousObjMesh();
  105273. //Create a new mesh
  105274. var objMesh =
  105275. //Set the name of the current obj mesh
  105276. {
  105277. name: objMeshName + "_mm" + increment.toString(),
  105278. indices: undefined,
  105279. positions: undefined,
  105280. normals: undefined,
  105281. uvs: undefined,
  105282. materialName: materialNameFromObj
  105283. };
  105284. increment++;
  105285. //If meshes are already defined
  105286. meshesFromObj.push(objMesh);
  105287. }
  105288. //Set the material name if the previous line define a mesh
  105289. if (hasMeshes && isFirstMaterial) {
  105290. //Set the material name to the previous mesh (1 material per mesh)
  105291. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105292. isFirstMaterial = false;
  105293. }
  105294. //Keyword for loading the mtl file
  105295. }
  105296. else if (this.mtllib.test(line)) {
  105297. //Get the name of mtl file
  105298. fileToLoad = line.substring(7).trim();
  105299. //Apply smoothing
  105300. }
  105301. else if (this.smooth.test(line)) {
  105302. // smooth shading => apply smoothing
  105303. //Toda y I don't know it work with babylon and with obj.
  105304. //With the obj file an integer is set
  105305. }
  105306. else {
  105307. //If there is another possibility
  105308. console.log("Unhandled expression at line : " + line);
  105309. }
  105310. }
  105311. //At the end of the file, add the last mesh into the meshesFromObj array
  105312. if (hasMeshes) {
  105313. //Set the data for the last mesh
  105314. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105315. //Reverse indices for displaying faces in the good sens
  105316. indicesForBabylon.reverse();
  105317. //Get the good array
  105318. unwrapData();
  105319. //Set array
  105320. handledMesh.indices = indicesForBabylon;
  105321. handledMesh.positions = unwrappedPositionsForBabylon;
  105322. handledMesh.normals = unwrappedNormalsForBabylon;
  105323. handledMesh.uvs = unwrappedUVForBabylon;
  105324. }
  105325. //If any o or g keyword found, create a mesj with a random id
  105326. if (!hasMeshes) {
  105327. // reverse tab of indices
  105328. indicesForBabylon.reverse();
  105329. //Get positions normals uvs
  105330. unwrapData();
  105331. //Set data for one mesh
  105332. meshesFromObj.push({
  105333. name: BABYLON.Geometry.RandomId(),
  105334. indices: indicesForBabylon,
  105335. positions: unwrappedPositionsForBabylon,
  105336. normals: unwrappedNormalsForBabylon,
  105337. uvs: unwrappedUVForBabylon,
  105338. materialName: materialNameFromObj
  105339. });
  105340. }
  105341. //Create a BABYLON.Mesh list
  105342. var babylonMeshesArray = []; //The mesh for babylon
  105343. var materialToUse = new Array();
  105344. //Set data for each mesh
  105345. for (var j = 0; j < meshesFromObj.length; j++) {
  105346. //check meshesNames (stlFileLoader)
  105347. if (meshesNames && meshesFromObj[j].name) {
  105348. if (meshesNames instanceof Array) {
  105349. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105350. continue;
  105351. }
  105352. }
  105353. else {
  105354. if (meshesFromObj[j].name !== meshesNames) {
  105355. continue;
  105356. }
  105357. }
  105358. }
  105359. //Get the current mesh
  105360. //Set the data with VertexBuffer for each mesh
  105361. handledMesh = meshesFromObj[j];
  105362. //Create a BABYLON.Mesh with the name of the obj mesh
  105363. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105364. //Push the name of the material to an array
  105365. //This is indispensable for the importMesh function
  105366. materialToUse.push(meshesFromObj[j].materialName);
  105367. var vertexData = new BABYLON.VertexData(); //The container for the values
  105368. //Set the data for the babylonMesh
  105369. vertexData.positions = handledMesh.positions;
  105370. vertexData.normals = handledMesh.normals;
  105371. vertexData.uvs = handledMesh.uvs;
  105372. vertexData.indices = handledMesh.indices;
  105373. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105374. vertexData.applyToMesh(babylonMesh);
  105375. //Push the mesh into an array
  105376. babylonMeshesArray.push(babylonMesh);
  105377. }
  105378. //load the materials
  105379. //Check if we have a file to load
  105380. if (fileToLoad !== "") {
  105381. //Load the file synchronously
  105382. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105383. //Create materials thanks MTLLoader function
  105384. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105385. //Look at each material loaded in the mtl file
  105386. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105387. //Three variables to get all meshes with the same material
  105388. var startIndex = 0;
  105389. var _indices = [];
  105390. var _index;
  105391. //The material from MTL file is used in the meshes loaded
  105392. //Push the indice in an array
  105393. //Check if the material is not used for another mesh
  105394. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105395. _indices.push(_index);
  105396. startIndex = _index + 1;
  105397. }
  105398. //If the material is not used dispose it
  105399. if (_index == -1 && _indices.length == 0) {
  105400. //If the material is not needed, remove it
  105401. materialsFromMTLFile.materials[n].dispose();
  105402. }
  105403. else {
  105404. for (var o = 0; o < _indices.length; o++) {
  105405. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105406. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105407. }
  105408. }
  105409. }
  105410. });
  105411. }
  105412. //Return an array with all BABYLON.Mesh
  105413. return babylonMeshesArray;
  105414. };
  105415. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105416. return OBJFileLoader;
  105417. }());
  105418. BABYLON.OBJFileLoader = OBJFileLoader;
  105419. if (BABYLON.SceneLoader) {
  105420. //Add this loader into the register plugin
  105421. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105422. }
  105423. })(BABYLON || (BABYLON = {}));
  105424. //# sourceMappingURL=babylon.objFileLoader.js.map
  105425. var BABYLON;
  105426. (function (BABYLON) {
  105427. var GLTFLoaderCoordinateSystemMode;
  105428. (function (GLTFLoaderCoordinateSystemMode) {
  105429. /**
  105430. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105431. */
  105432. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105433. /**
  105434. * Sets the useRightHandedSystem flag on the scene.
  105435. */
  105436. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105437. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105438. var GLTFLoaderAnimationStartMode;
  105439. (function (GLTFLoaderAnimationStartMode) {
  105440. /**
  105441. * No animation will start.
  105442. */
  105443. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105444. /**
  105445. * The first animation will start.
  105446. */
  105447. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105448. /**
  105449. * All animations will start.
  105450. */
  105451. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105452. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105453. var GLTFLoaderState;
  105454. (function (GLTFLoaderState) {
  105455. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  105456. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  105457. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  105458. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105459. var GLTFFileLoader = /** @class */ (function () {
  105460. function GLTFFileLoader() {
  105461. // #region Common options
  105462. /**
  105463. * Raised when the asset has been parsed.
  105464. * The data.json property stores the glTF JSON.
  105465. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  105466. */
  105467. this.onParsedObservable = new BABYLON.Observable();
  105468. // #endregion
  105469. // #region V2 options
  105470. /**
  105471. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  105472. */
  105473. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105474. /**
  105475. * The animation start mode (NONE, FIRST, ALL).
  105476. */
  105477. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105478. /**
  105479. * Set to true to compile materials before raising the success callback.
  105480. */
  105481. this.compileMaterials = false;
  105482. /**
  105483. * Set to true to also compile materials with clip planes.
  105484. */
  105485. this.useClipPlane = false;
  105486. /**
  105487. * Set to true to compile shadow generators before raising the success callback.
  105488. */
  105489. this.compileShadowGenerators = false;
  105490. /**
  105491. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105492. */
  105493. this.onMeshLoadedObservable = new BABYLON.Observable();
  105494. /**
  105495. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  105496. */
  105497. this.onTextureLoadedObservable = new BABYLON.Observable();
  105498. /**
  105499. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105500. */
  105501. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105502. /**
  105503. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  105504. */
  105505. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  105506. /**
  105507. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105508. * For assets with LODs, raised when all of the LODs are complete.
  105509. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105510. */
  105511. this.onCompleteObservable = new BABYLON.Observable();
  105512. /**
  105513. * Raised when the loader is disposed.
  105514. */
  105515. this.onDisposeObservable = new BABYLON.Observable();
  105516. /**
  105517. * Raised after a loader extension is created.
  105518. * Set additional options for a loader extension in this event.
  105519. */
  105520. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105521. // #endregion
  105522. this._loader = null;
  105523. this.name = "gltf";
  105524. this.extensions = {
  105525. ".gltf": { isBinary: false },
  105526. ".glb": { isBinary: true }
  105527. };
  105528. }
  105529. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105530. set: function (callback) {
  105531. if (this._onParsedObserver) {
  105532. this.onParsedObservable.remove(this._onParsedObserver);
  105533. }
  105534. this._onParsedObserver = this.onParsedObservable.add(callback);
  105535. },
  105536. enumerable: true,
  105537. configurable: true
  105538. });
  105539. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105540. set: function (callback) {
  105541. if (this._onMeshLoadedObserver) {
  105542. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105543. }
  105544. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105545. },
  105546. enumerable: true,
  105547. configurable: true
  105548. });
  105549. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105550. set: function (callback) {
  105551. if (this._onTextureLoadedObserver) {
  105552. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105553. }
  105554. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105555. },
  105556. enumerable: true,
  105557. configurable: true
  105558. });
  105559. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105560. set: function (callback) {
  105561. if (this._onMaterialLoadedObserver) {
  105562. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105563. }
  105564. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105565. },
  105566. enumerable: true,
  105567. configurable: true
  105568. });
  105569. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  105570. set: function (callback) {
  105571. if (this._onAnimationGroupLoadedObserver) {
  105572. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  105573. }
  105574. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  105575. },
  105576. enumerable: true,
  105577. configurable: true
  105578. });
  105579. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105580. set: function (callback) {
  105581. if (this._onCompleteObserver) {
  105582. this.onCompleteObservable.remove(this._onCompleteObserver);
  105583. }
  105584. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105585. },
  105586. enumerable: true,
  105587. configurable: true
  105588. });
  105589. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105590. set: function (callback) {
  105591. if (this._onDisposeObserver) {
  105592. this.onDisposeObservable.remove(this._onDisposeObserver);
  105593. }
  105594. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105595. },
  105596. enumerable: true,
  105597. configurable: true
  105598. });
  105599. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105600. set: function (callback) {
  105601. if (this._onExtensionLoadedObserver) {
  105602. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105603. }
  105604. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105605. },
  105606. enumerable: true,
  105607. configurable: true
  105608. });
  105609. /**
  105610. * Gets a promise that resolves when the asset is completely loaded.
  105611. * @returns A promise that resolves when the asset is completely loaded.
  105612. */
  105613. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105614. var _this = this;
  105615. return new Promise(function (resolve) {
  105616. _this.onCompleteObservable.add(function () {
  105617. resolve();
  105618. }, undefined, undefined, undefined, true);
  105619. });
  105620. };
  105621. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105622. /**
  105623. * The loader state or null if not active.
  105624. */
  105625. get: function () {
  105626. return this._loader ? this._loader.state : null;
  105627. },
  105628. enumerable: true,
  105629. configurable: true
  105630. });
  105631. /**
  105632. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105633. */
  105634. GLTFFileLoader.prototype.dispose = function () {
  105635. if (this._loader) {
  105636. this._loader.dispose();
  105637. this._loader = null;
  105638. }
  105639. this.onMeshLoadedObservable.clear();
  105640. this.onTextureLoadedObservable.clear();
  105641. this.onMaterialLoadedObservable.clear();
  105642. this.onDisposeObservable.notifyObservers(this);
  105643. this.onDisposeObservable.clear();
  105644. };
  105645. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105646. var _this = this;
  105647. return Promise.resolve().then(function () {
  105648. var loaderData = _this._parse(data);
  105649. _this._loader = _this._getLoader(loaderData);
  105650. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105651. });
  105652. };
  105653. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105654. var _this = this;
  105655. return Promise.resolve().then(function () {
  105656. var loaderData = _this._parse(data);
  105657. _this._loader = _this._getLoader(loaderData);
  105658. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105659. });
  105660. };
  105661. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105662. var _this = this;
  105663. return Promise.resolve().then(function () {
  105664. var loaderData = _this._parse(data);
  105665. _this._loader = _this._getLoader(loaderData);
  105666. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105667. var container = new BABYLON.AssetContainer(scene);
  105668. Array.prototype.push.apply(container.meshes, result.meshes);
  105669. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105670. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105671. container.removeAllFromScene();
  105672. return container;
  105673. });
  105674. });
  105675. };
  105676. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105677. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105678. };
  105679. GLTFFileLoader.prototype.createPlugin = function () {
  105680. return new GLTFFileLoader();
  105681. };
  105682. GLTFFileLoader.prototype._parse = function (data) {
  105683. var parsedData;
  105684. if (data instanceof ArrayBuffer) {
  105685. parsedData = GLTFFileLoader._parseBinary(data);
  105686. }
  105687. else {
  105688. parsedData = {
  105689. json: JSON.parse(data),
  105690. bin: null
  105691. };
  105692. }
  105693. this.onParsedObservable.notifyObservers(parsedData);
  105694. this.onParsedObservable.clear();
  105695. return parsedData;
  105696. };
  105697. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105698. var _this = this;
  105699. var loaderVersion = { major: 2, minor: 0 };
  105700. var asset = loaderData.json.asset || {};
  105701. var version = GLTFFileLoader._parseVersion(asset.version);
  105702. if (!version) {
  105703. throw new Error("Invalid version: " + asset.version);
  105704. }
  105705. if (asset.minVersion !== undefined) {
  105706. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105707. if (!minVersion) {
  105708. throw new Error("Invalid minimum version: " + asset.minVersion);
  105709. }
  105710. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105711. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105712. }
  105713. }
  105714. var createLoaders = {
  105715. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105716. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105717. };
  105718. var createLoader = createLoaders[version.major];
  105719. if (!createLoader) {
  105720. throw new Error("Unsupported version: " + asset.version);
  105721. }
  105722. var loader = createLoader();
  105723. loader.coordinateSystemMode = this.coordinateSystemMode;
  105724. loader.animationStartMode = this.animationStartMode;
  105725. loader.compileMaterials = this.compileMaterials;
  105726. loader.useClipPlane = this.useClipPlane;
  105727. loader.compileShadowGenerators = this.compileShadowGenerators;
  105728. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  105729. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  105730. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  105731. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  105732. loader.onCompleteObservable.add(function () {
  105733. _this.onMeshLoadedObservable.clear();
  105734. _this.onTextureLoadedObservable.clear();
  105735. _this.onMaterialLoadedObservable.clear();
  105736. _this.onCompleteObservable.notifyObservers(_this);
  105737. _this.onCompleteObservable.clear();
  105738. });
  105739. return loader;
  105740. };
  105741. GLTFFileLoader._parseBinary = function (data) {
  105742. var Binary = {
  105743. Magic: 0x46546C67
  105744. };
  105745. var binaryReader = new BinaryReader(data);
  105746. var magic = binaryReader.readUint32();
  105747. if (magic !== Binary.Magic) {
  105748. throw new Error("Unexpected magic: " + magic);
  105749. }
  105750. var version = binaryReader.readUint32();
  105751. switch (version) {
  105752. case 1: return GLTFFileLoader._parseV1(binaryReader);
  105753. case 2: return GLTFFileLoader._parseV2(binaryReader);
  105754. }
  105755. throw new Error("Unsupported version: " + version);
  105756. };
  105757. GLTFFileLoader._parseV1 = function (binaryReader) {
  105758. var ContentFormat = {
  105759. JSON: 0
  105760. };
  105761. var length = binaryReader.readUint32();
  105762. if (length != binaryReader.getLength()) {
  105763. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105764. }
  105765. var contentLength = binaryReader.readUint32();
  105766. var contentFormat = binaryReader.readUint32();
  105767. var content;
  105768. switch (contentFormat) {
  105769. case ContentFormat.JSON: {
  105770. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105771. break;
  105772. }
  105773. default: {
  105774. throw new Error("Unexpected content format: " + contentFormat);
  105775. }
  105776. }
  105777. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  105778. var body = binaryReader.readUint8Array(bytesRemaining);
  105779. return {
  105780. json: content,
  105781. bin: body
  105782. };
  105783. };
  105784. GLTFFileLoader._parseV2 = function (binaryReader) {
  105785. var ChunkFormat = {
  105786. JSON: 0x4E4F534A,
  105787. BIN: 0x004E4942
  105788. };
  105789. var length = binaryReader.readUint32();
  105790. if (length !== binaryReader.getLength()) {
  105791. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105792. }
  105793. // JSON chunk
  105794. var chunkLength = binaryReader.readUint32();
  105795. var chunkFormat = binaryReader.readUint32();
  105796. if (chunkFormat !== ChunkFormat.JSON) {
  105797. throw new Error("First chunk format is not JSON");
  105798. }
  105799. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  105800. // Look for BIN chunk
  105801. var bin = null;
  105802. while (binaryReader.getPosition() < binaryReader.getLength()) {
  105803. var chunkLength_1 = binaryReader.readUint32();
  105804. var chunkFormat_1 = binaryReader.readUint32();
  105805. switch (chunkFormat_1) {
  105806. case ChunkFormat.JSON: {
  105807. throw new Error("Unexpected JSON chunk");
  105808. }
  105809. case ChunkFormat.BIN: {
  105810. bin = binaryReader.readUint8Array(chunkLength_1);
  105811. break;
  105812. }
  105813. default: {
  105814. // ignore unrecognized chunkFormat
  105815. binaryReader.skipBytes(chunkLength_1);
  105816. break;
  105817. }
  105818. }
  105819. }
  105820. return {
  105821. json: json,
  105822. bin: bin
  105823. };
  105824. };
  105825. GLTFFileLoader._parseVersion = function (version) {
  105826. if (version === "1.0" || version === "1.0.1") {
  105827. return {
  105828. major: 1,
  105829. minor: 0
  105830. };
  105831. }
  105832. var match = (version + "").match(/^(\d+)\.(\d+)/);
  105833. if (!match) {
  105834. return null;
  105835. }
  105836. return {
  105837. major: parseInt(match[1]),
  105838. minor: parseInt(match[2])
  105839. };
  105840. };
  105841. GLTFFileLoader._compareVersion = function (a, b) {
  105842. if (a.major > b.major)
  105843. return 1;
  105844. if (a.major < b.major)
  105845. return -1;
  105846. if (a.minor > b.minor)
  105847. return 1;
  105848. if (a.minor < b.minor)
  105849. return -1;
  105850. return 0;
  105851. };
  105852. GLTFFileLoader._decodeBufferToText = function (buffer) {
  105853. var result = "";
  105854. var length = buffer.byteLength;
  105855. for (var i = 0; i < length; i++) {
  105856. result += String.fromCharCode(buffer[i]);
  105857. }
  105858. return result;
  105859. };
  105860. // #endregion
  105861. // #region V1 options
  105862. GLTFFileLoader.IncrementalLoading = true;
  105863. GLTFFileLoader.HomogeneousCoordinates = false;
  105864. return GLTFFileLoader;
  105865. }());
  105866. BABYLON.GLTFFileLoader = GLTFFileLoader;
  105867. var BinaryReader = /** @class */ (function () {
  105868. function BinaryReader(arrayBuffer) {
  105869. this._arrayBuffer = arrayBuffer;
  105870. this._dataView = new DataView(arrayBuffer);
  105871. this._byteOffset = 0;
  105872. }
  105873. BinaryReader.prototype.getPosition = function () {
  105874. return this._byteOffset;
  105875. };
  105876. BinaryReader.prototype.getLength = function () {
  105877. return this._arrayBuffer.byteLength;
  105878. };
  105879. BinaryReader.prototype.readUint32 = function () {
  105880. var value = this._dataView.getUint32(this._byteOffset, true);
  105881. this._byteOffset += 4;
  105882. return value;
  105883. };
  105884. BinaryReader.prototype.readUint8Array = function (length) {
  105885. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  105886. this._byteOffset += length;
  105887. return value;
  105888. };
  105889. BinaryReader.prototype.skipBytes = function (length) {
  105890. this._byteOffset += length;
  105891. };
  105892. return BinaryReader;
  105893. }());
  105894. if (BABYLON.SceneLoader) {
  105895. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  105896. }
  105897. })(BABYLON || (BABYLON = {}));
  105898. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  105899. var BABYLON;
  105900. (function (BABYLON) {
  105901. var GLTF1;
  105902. (function (GLTF1) {
  105903. /**
  105904. * Enums
  105905. */
  105906. var EComponentType;
  105907. (function (EComponentType) {
  105908. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  105909. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105910. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  105911. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105912. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  105913. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  105914. var EShaderType;
  105915. (function (EShaderType) {
  105916. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  105917. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  105918. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  105919. var EParameterType;
  105920. (function (EParameterType) {
  105921. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  105922. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105923. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  105924. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105925. EParameterType[EParameterType["INT"] = 5124] = "INT";
  105926. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  105927. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  105928. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  105929. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  105930. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  105931. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  105932. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  105933. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  105934. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  105935. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  105936. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  105937. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  105938. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  105939. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  105940. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  105941. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  105942. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  105943. var ETextureWrapMode;
  105944. (function (ETextureWrapMode) {
  105945. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  105946. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  105947. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  105948. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  105949. var ETextureFilterType;
  105950. (function (ETextureFilterType) {
  105951. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  105952. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  105953. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  105954. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  105955. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  105956. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  105957. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  105958. var ETextureFormat;
  105959. (function (ETextureFormat) {
  105960. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  105961. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  105962. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  105963. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  105964. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  105965. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  105966. var ECullingType;
  105967. (function (ECullingType) {
  105968. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  105969. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  105970. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  105971. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  105972. var EBlendingFunction;
  105973. (function (EBlendingFunction) {
  105974. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  105975. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  105976. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  105977. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  105978. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  105979. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  105980. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  105981. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  105982. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  105983. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  105984. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  105985. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  105986. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  105987. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  105988. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  105989. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  105990. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105991. })(BABYLON || (BABYLON = {}));
  105992. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105993. var BABYLON;
  105994. (function (BABYLON) {
  105995. var GLTF1;
  105996. (function (GLTF1) {
  105997. /**
  105998. * Tokenizer. Used for shaders compatibility
  105999. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106000. */
  106001. var ETokenType;
  106002. (function (ETokenType) {
  106003. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106004. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106005. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106006. })(ETokenType || (ETokenType = {}));
  106007. var Tokenizer = /** @class */ (function () {
  106008. function Tokenizer(toParse) {
  106009. this._pos = 0;
  106010. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106011. this._toParse = toParse;
  106012. this._maxPos = toParse.length;
  106013. }
  106014. Tokenizer.prototype.getNextToken = function () {
  106015. if (this.isEnd())
  106016. return ETokenType.END_OF_INPUT;
  106017. this.currentString = this.read();
  106018. this.currentToken = ETokenType.UNKNOWN;
  106019. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106020. this.currentToken = ETokenType.IDENTIFIER;
  106021. this.currentIdentifier = this.currentString;
  106022. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106023. this.currentIdentifier += this.currentString;
  106024. this.forward();
  106025. }
  106026. }
  106027. return this.currentToken;
  106028. };
  106029. Tokenizer.prototype.peek = function () {
  106030. return this._toParse[this._pos];
  106031. };
  106032. Tokenizer.prototype.read = function () {
  106033. return this._toParse[this._pos++];
  106034. };
  106035. Tokenizer.prototype.forward = function () {
  106036. this._pos++;
  106037. };
  106038. Tokenizer.prototype.isEnd = function () {
  106039. return this._pos >= this._maxPos;
  106040. };
  106041. return Tokenizer;
  106042. }());
  106043. /**
  106044. * Values
  106045. */
  106046. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106047. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106048. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106049. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106050. /**
  106051. * Parse
  106052. */
  106053. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106054. for (var buf in parsedBuffers) {
  106055. var parsedBuffer = parsedBuffers[buf];
  106056. gltfRuntime.buffers[buf] = parsedBuffer;
  106057. gltfRuntime.buffersCount++;
  106058. }
  106059. };
  106060. var parseShaders = function (parsedShaders, gltfRuntime) {
  106061. for (var sha in parsedShaders) {
  106062. var parsedShader = parsedShaders[sha];
  106063. gltfRuntime.shaders[sha] = parsedShader;
  106064. gltfRuntime.shaderscount++;
  106065. }
  106066. };
  106067. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106068. for (var object in parsedObjects) {
  106069. var parsedObject = parsedObjects[object];
  106070. gltfRuntime[runtimeProperty][object] = parsedObject;
  106071. }
  106072. };
  106073. /**
  106074. * Utils
  106075. */
  106076. var normalizeUVs = function (buffer) {
  106077. if (!buffer) {
  106078. return;
  106079. }
  106080. for (var i = 0; i < buffer.length / 2; i++) {
  106081. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106082. }
  106083. };
  106084. var getAttribute = function (attributeParameter) {
  106085. if (attributeParameter.semantic === "NORMAL") {
  106086. return "normal";
  106087. }
  106088. else if (attributeParameter.semantic === "POSITION") {
  106089. return "position";
  106090. }
  106091. else if (attributeParameter.semantic === "JOINT") {
  106092. return "matricesIndices";
  106093. }
  106094. else if (attributeParameter.semantic === "WEIGHT") {
  106095. return "matricesWeights";
  106096. }
  106097. else if (attributeParameter.semantic === "COLOR") {
  106098. return "color";
  106099. }
  106100. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106101. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106102. return "uv" + (channel === 0 ? "" : channel + 1);
  106103. }
  106104. return null;
  106105. };
  106106. /**
  106107. * Loads and creates animations
  106108. */
  106109. var loadAnimations = function (gltfRuntime) {
  106110. for (var anim in gltfRuntime.animations) {
  106111. var animation = gltfRuntime.animations[anim];
  106112. if (!animation.channels || !animation.samplers) {
  106113. continue;
  106114. }
  106115. var lastAnimation = null;
  106116. for (var i = 0; i < animation.channels.length; i++) {
  106117. // Get parameters and load buffers
  106118. var channel = animation.channels[i];
  106119. var sampler = animation.samplers[channel.sampler];
  106120. if (!sampler) {
  106121. continue;
  106122. }
  106123. var inputData = null;
  106124. var outputData = null;
  106125. if (animation.parameters) {
  106126. inputData = animation.parameters[sampler.input];
  106127. outputData = animation.parameters[sampler.output];
  106128. }
  106129. else {
  106130. inputData = sampler.input;
  106131. outputData = sampler.output;
  106132. }
  106133. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106134. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106135. var targetID = channel.target.id;
  106136. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106137. if (targetNode === null) {
  106138. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106139. }
  106140. if (targetNode === null) {
  106141. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106142. continue;
  106143. }
  106144. var isBone = targetNode instanceof BABYLON.Bone;
  106145. // Get target path (position, rotation or scaling)
  106146. var targetPath = channel.target.path;
  106147. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106148. if (targetPathIndex !== -1) {
  106149. targetPath = babylonAnimationPaths[targetPathIndex];
  106150. }
  106151. // Determine animation type
  106152. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106153. if (!isBone) {
  106154. if (targetPath === "rotationQuaternion") {
  106155. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106156. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106157. }
  106158. else {
  106159. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106160. }
  106161. }
  106162. // Create animation and key frames
  106163. var babylonAnimation = null;
  106164. var keys = [];
  106165. var arrayOffset = 0;
  106166. var modifyKey = false;
  106167. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106168. babylonAnimation = lastAnimation;
  106169. modifyKey = true;
  106170. }
  106171. if (!modifyKey) {
  106172. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106173. }
  106174. // For each frame
  106175. for (var j = 0; j < bufferInput.length; j++) {
  106176. var value = null;
  106177. if (targetPath === "rotationQuaternion") {
  106178. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106179. arrayOffset += 4;
  106180. }
  106181. else {
  106182. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106183. arrayOffset += 3;
  106184. }
  106185. if (isBone) {
  106186. var bone = targetNode;
  106187. var translation = BABYLON.Vector3.Zero();
  106188. var rotationQuaternion = new BABYLON.Quaternion();
  106189. var scaling = BABYLON.Vector3.Zero();
  106190. // Warning on decompose
  106191. var mat = bone.getBaseMatrix();
  106192. if (modifyKey && lastAnimation) {
  106193. mat = lastAnimation.getKeys()[j].value;
  106194. }
  106195. mat.decompose(scaling, rotationQuaternion, translation);
  106196. if (targetPath === "position") {
  106197. translation = value;
  106198. }
  106199. else if (targetPath === "rotationQuaternion") {
  106200. rotationQuaternion = value;
  106201. }
  106202. else {
  106203. scaling = value;
  106204. }
  106205. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106206. }
  106207. if (!modifyKey) {
  106208. keys.push({
  106209. frame: bufferInput[j],
  106210. value: value
  106211. });
  106212. }
  106213. else if (lastAnimation) {
  106214. lastAnimation.getKeys()[j].value = value;
  106215. }
  106216. }
  106217. // Finish
  106218. if (!modifyKey && babylonAnimation) {
  106219. babylonAnimation.setKeys(keys);
  106220. targetNode.animations.push(babylonAnimation);
  106221. }
  106222. lastAnimation = babylonAnimation;
  106223. gltfRuntime.scene.stopAnimation(targetNode);
  106224. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106225. }
  106226. }
  106227. };
  106228. /**
  106229. * Returns the bones transformation matrix
  106230. */
  106231. var configureBoneTransformation = function (node) {
  106232. var mat = null;
  106233. if (node.translation || node.rotation || node.scale) {
  106234. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106235. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106236. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106237. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106238. }
  106239. else {
  106240. mat = BABYLON.Matrix.FromArray(node.matrix);
  106241. }
  106242. return mat;
  106243. };
  106244. /**
  106245. * Returns the parent bone
  106246. */
  106247. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106248. // Try to find
  106249. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106250. if (newSkeleton.bones[i].name === jointName) {
  106251. return newSkeleton.bones[i];
  106252. }
  106253. }
  106254. // Not found, search in gltf nodes
  106255. var nodes = gltfRuntime.nodes;
  106256. for (var nde in nodes) {
  106257. var node = nodes[nde];
  106258. if (!node.jointName) {
  106259. continue;
  106260. }
  106261. var children = node.children;
  106262. for (var i = 0; i < children.length; i++) {
  106263. var child = gltfRuntime.nodes[children[i]];
  106264. if (!child.jointName) {
  106265. continue;
  106266. }
  106267. if (child.jointName === jointName) {
  106268. var mat = configureBoneTransformation(node);
  106269. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106270. bone.id = nde;
  106271. return bone;
  106272. }
  106273. }
  106274. }
  106275. return null;
  106276. };
  106277. /**
  106278. * Returns the appropriate root node
  106279. */
  106280. var getNodeToRoot = function (nodesToRoot, id) {
  106281. for (var i = 0; i < nodesToRoot.length; i++) {
  106282. var nodeToRoot = nodesToRoot[i];
  106283. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106284. var child = nodeToRoot.node.children[j];
  106285. if (child === id) {
  106286. return nodeToRoot.bone;
  106287. }
  106288. }
  106289. }
  106290. return null;
  106291. };
  106292. /**
  106293. * Returns the node with the joint name
  106294. */
  106295. var getJointNode = function (gltfRuntime, jointName) {
  106296. var nodes = gltfRuntime.nodes;
  106297. var node = nodes[jointName];
  106298. if (node) {
  106299. return {
  106300. node: node,
  106301. id: jointName
  106302. };
  106303. }
  106304. for (var nde in nodes) {
  106305. node = nodes[nde];
  106306. if (node.jointName === jointName) {
  106307. return {
  106308. node: node,
  106309. id: nde
  106310. };
  106311. }
  106312. }
  106313. return null;
  106314. };
  106315. /**
  106316. * Checks if a nodes is in joints
  106317. */
  106318. var nodeIsInJoints = function (skins, id) {
  106319. for (var i = 0; i < skins.jointNames.length; i++) {
  106320. if (skins.jointNames[i] === id) {
  106321. return true;
  106322. }
  106323. }
  106324. return false;
  106325. };
  106326. /**
  106327. * Fills the nodes to root for bones and builds hierarchy
  106328. */
  106329. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106330. // Creates nodes for root
  106331. for (var nde in gltfRuntime.nodes) {
  106332. var node = gltfRuntime.nodes[nde];
  106333. var id = nde;
  106334. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106335. continue;
  106336. }
  106337. // Create node to root bone
  106338. var mat = configureBoneTransformation(node);
  106339. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106340. bone.id = id;
  106341. nodesToRoot.push({ bone: bone, node: node, id: id });
  106342. }
  106343. // Parenting
  106344. for (var i = 0; i < nodesToRoot.length; i++) {
  106345. var nodeToRoot = nodesToRoot[i];
  106346. var children = nodeToRoot.node.children;
  106347. for (var j = 0; j < children.length; j++) {
  106348. var child = null;
  106349. for (var k = 0; k < nodesToRoot.length; k++) {
  106350. if (nodesToRoot[k].id === children[j]) {
  106351. child = nodesToRoot[k];
  106352. break;
  106353. }
  106354. }
  106355. if (child) {
  106356. child.bone._parent = nodeToRoot.bone;
  106357. nodeToRoot.bone.children.push(child.bone);
  106358. }
  106359. }
  106360. }
  106361. };
  106362. /**
  106363. * Imports a skeleton
  106364. */
  106365. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106366. if (!newSkeleton) {
  106367. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106368. }
  106369. if (!skins.babylonSkeleton) {
  106370. return newSkeleton;
  106371. }
  106372. // Find the root bones
  106373. var nodesToRoot = [];
  106374. var nodesToRootToAdd = [];
  106375. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106376. newSkeleton.bones = [];
  106377. // Joints
  106378. for (var i = 0; i < skins.jointNames.length; i++) {
  106379. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106380. if (!jointNode) {
  106381. continue;
  106382. }
  106383. var node = jointNode.node;
  106384. if (!node) {
  106385. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106386. continue;
  106387. }
  106388. var id = jointNode.id;
  106389. // Optimize, if the bone already exists...
  106390. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106391. if (existingBone) {
  106392. newSkeleton.bones.push(existingBone);
  106393. continue;
  106394. }
  106395. // Search for parent bone
  106396. var foundBone = false;
  106397. var parentBone = null;
  106398. for (var j = 0; j < i; j++) {
  106399. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106400. if (!jointNode_1) {
  106401. continue;
  106402. }
  106403. var joint = jointNode_1.node;
  106404. if (!joint) {
  106405. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106406. continue;
  106407. }
  106408. var children = joint.children;
  106409. if (!children) {
  106410. continue;
  106411. }
  106412. foundBone = false;
  106413. for (var k = 0; k < children.length; k++) {
  106414. if (children[k] === id) {
  106415. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106416. foundBone = true;
  106417. break;
  106418. }
  106419. }
  106420. if (foundBone) {
  106421. break;
  106422. }
  106423. }
  106424. // Create bone
  106425. var mat = configureBoneTransformation(node);
  106426. if (!parentBone && nodesToRoot.length > 0) {
  106427. parentBone = getNodeToRoot(nodesToRoot, id);
  106428. if (parentBone) {
  106429. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106430. nodesToRootToAdd.push(parentBone);
  106431. }
  106432. }
  106433. }
  106434. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106435. bone.id = id;
  106436. }
  106437. // Polish
  106438. var bones = newSkeleton.bones;
  106439. newSkeleton.bones = [];
  106440. for (var i = 0; i < skins.jointNames.length; i++) {
  106441. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106442. if (!jointNode) {
  106443. continue;
  106444. }
  106445. for (var j = 0; j < bones.length; j++) {
  106446. if (bones[j].id === jointNode.id) {
  106447. newSkeleton.bones.push(bones[j]);
  106448. break;
  106449. }
  106450. }
  106451. }
  106452. newSkeleton.prepare();
  106453. // Finish
  106454. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106455. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106456. }
  106457. return newSkeleton;
  106458. };
  106459. /**
  106460. * Imports a mesh and its geometries
  106461. */
  106462. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106463. if (!newMesh) {
  106464. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106465. newMesh.id = id;
  106466. }
  106467. if (!node.babylonNode) {
  106468. return newMesh;
  106469. }
  106470. var subMaterials = [];
  106471. var vertexData = null;
  106472. var verticesStarts = new Array();
  106473. var verticesCounts = new Array();
  106474. var indexStarts = new Array();
  106475. var indexCounts = new Array();
  106476. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106477. var meshID = meshes[meshIndex];
  106478. var mesh = gltfRuntime.meshes[meshID];
  106479. if (!mesh) {
  106480. continue;
  106481. }
  106482. // Positions, normals and UVs
  106483. for (var i = 0; i < mesh.primitives.length; i++) {
  106484. // Temporary vertex data
  106485. var tempVertexData = new BABYLON.VertexData();
  106486. var primitive = mesh.primitives[i];
  106487. if (primitive.mode !== 4) {
  106488. // continue;
  106489. }
  106490. var attributes = primitive.attributes;
  106491. var accessor = null;
  106492. var buffer = null;
  106493. // Set positions, normal and uvs
  106494. for (var semantic in attributes) {
  106495. // Link accessor and buffer view
  106496. accessor = gltfRuntime.accessors[attributes[semantic]];
  106497. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106498. if (semantic === "NORMAL") {
  106499. tempVertexData.normals = new Float32Array(buffer.length);
  106500. tempVertexData.normals.set(buffer);
  106501. }
  106502. else if (semantic === "POSITION") {
  106503. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106504. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106505. for (var j = 0; j < buffer.length; j += 4) {
  106506. tempVertexData.positions[j] = buffer[j];
  106507. tempVertexData.positions[j + 1] = buffer[j + 1];
  106508. tempVertexData.positions[j + 2] = buffer[j + 2];
  106509. }
  106510. }
  106511. else {
  106512. tempVertexData.positions = new Float32Array(buffer.length);
  106513. tempVertexData.positions.set(buffer);
  106514. }
  106515. verticesCounts.push(tempVertexData.positions.length);
  106516. }
  106517. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106518. var channel = Number(semantic.split("_")[1]);
  106519. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106520. var uvs = new Float32Array(buffer.length);
  106521. uvs.set(buffer);
  106522. normalizeUVs(uvs);
  106523. tempVertexData.set(uvs, uvKind);
  106524. }
  106525. else if (semantic === "JOINT") {
  106526. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106527. tempVertexData.matricesIndices.set(buffer);
  106528. }
  106529. else if (semantic === "WEIGHT") {
  106530. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106531. tempVertexData.matricesWeights.set(buffer);
  106532. }
  106533. else if (semantic === "COLOR") {
  106534. tempVertexData.colors = new Float32Array(buffer.length);
  106535. tempVertexData.colors.set(buffer);
  106536. }
  106537. }
  106538. // Indices
  106539. accessor = gltfRuntime.accessors[primitive.indices];
  106540. if (accessor) {
  106541. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106542. tempVertexData.indices = new Int32Array(buffer.length);
  106543. tempVertexData.indices.set(buffer);
  106544. indexCounts.push(tempVertexData.indices.length);
  106545. }
  106546. else {
  106547. // Set indices on the fly
  106548. var indices = [];
  106549. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106550. indices.push(j);
  106551. }
  106552. tempVertexData.indices = new Int32Array(indices);
  106553. indexCounts.push(tempVertexData.indices.length);
  106554. }
  106555. if (!vertexData) {
  106556. vertexData = tempVertexData;
  106557. }
  106558. else {
  106559. vertexData.merge(tempVertexData);
  106560. }
  106561. // Sub material
  106562. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106563. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106564. // Update vertices start and index start
  106565. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106566. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106567. }
  106568. }
  106569. var material;
  106570. if (subMaterials.length > 1) {
  106571. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106572. material.subMaterials = subMaterials;
  106573. }
  106574. else {
  106575. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106576. }
  106577. if (subMaterials.length === 1) {
  106578. material = subMaterials[0];
  106579. }
  106580. if (!newMesh.material) {
  106581. newMesh.material = material;
  106582. }
  106583. // Apply geometry
  106584. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106585. newMesh.computeWorldMatrix(true);
  106586. // Apply submeshes
  106587. newMesh.subMeshes = [];
  106588. var index = 0;
  106589. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106590. var meshID = meshes[meshIndex];
  106591. var mesh = gltfRuntime.meshes[meshID];
  106592. if (!mesh) {
  106593. continue;
  106594. }
  106595. for (var i = 0; i < mesh.primitives.length; i++) {
  106596. if (mesh.primitives[i].mode !== 4) {
  106597. //continue;
  106598. }
  106599. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106600. index++;
  106601. }
  106602. }
  106603. // Finish
  106604. return newMesh;
  106605. };
  106606. /**
  106607. * Configure node transformation from position, rotation and scaling
  106608. */
  106609. var configureNode = function (newNode, position, rotation, scaling) {
  106610. if (newNode.position) {
  106611. newNode.position = position;
  106612. }
  106613. if (newNode.rotationQuaternion || newNode.rotation) {
  106614. newNode.rotationQuaternion = rotation;
  106615. }
  106616. if (newNode.scaling) {
  106617. newNode.scaling = scaling;
  106618. }
  106619. };
  106620. /**
  106621. * Configures node from transformation matrix
  106622. */
  106623. var configureNodeFromMatrix = function (newNode, node, parent) {
  106624. if (node.matrix) {
  106625. var position = new BABYLON.Vector3(0, 0, 0);
  106626. var rotation = new BABYLON.Quaternion();
  106627. var scaling = new BABYLON.Vector3(0, 0, 0);
  106628. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106629. mat.decompose(scaling, rotation, position);
  106630. configureNode(newNode, position, rotation, scaling);
  106631. }
  106632. else if (node.translation && node.rotation && node.scale) {
  106633. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106634. }
  106635. newNode.computeWorldMatrix(true);
  106636. };
  106637. /**
  106638. * Imports a node
  106639. */
  106640. var importNode = function (gltfRuntime, node, id, parent) {
  106641. var lastNode = null;
  106642. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106643. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106644. return null;
  106645. }
  106646. }
  106647. // Meshes
  106648. if (node.skin) {
  106649. if (node.meshes) {
  106650. var skin = gltfRuntime.skins[node.skin];
  106651. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106652. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106653. if (newMesh.skeleton === null) {
  106654. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106655. if (!skin.babylonSkeleton) {
  106656. skin.babylonSkeleton = newMesh.skeleton;
  106657. }
  106658. }
  106659. lastNode = newMesh;
  106660. }
  106661. }
  106662. else if (node.meshes) {
  106663. /**
  106664. * Improve meshes property
  106665. */
  106666. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106667. lastNode = newMesh;
  106668. }
  106669. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106670. var light = gltfRuntime.lights[node.light];
  106671. if (light) {
  106672. if (light.type === "ambient") {
  106673. var ambienLight = light[light.type];
  106674. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106675. hemiLight.name = node.name || "";
  106676. if (ambienLight.color) {
  106677. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106678. }
  106679. lastNode = hemiLight;
  106680. }
  106681. else if (light.type === "directional") {
  106682. var directionalLight = light[light.type];
  106683. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106684. dirLight.name = node.name || "";
  106685. if (directionalLight.color) {
  106686. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106687. }
  106688. lastNode = dirLight;
  106689. }
  106690. else if (light.type === "point") {
  106691. var pointLight = light[light.type];
  106692. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106693. ptLight.name = node.name || "";
  106694. if (pointLight.color) {
  106695. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106696. }
  106697. lastNode = ptLight;
  106698. }
  106699. else if (light.type === "spot") {
  106700. var spotLight = light[light.type];
  106701. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106702. spLight.name = node.name || "";
  106703. if (spotLight.color) {
  106704. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106705. }
  106706. if (spotLight.fallOfAngle) {
  106707. spLight.angle = spotLight.fallOfAngle;
  106708. }
  106709. if (spotLight.fallOffExponent) {
  106710. spLight.exponent = spotLight.fallOffExponent;
  106711. }
  106712. lastNode = spLight;
  106713. }
  106714. }
  106715. }
  106716. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106717. var camera = gltfRuntime.cameras[node.camera];
  106718. if (camera) {
  106719. if (camera.type === "orthographic") {
  106720. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106721. orthoCamera.name = node.name || "";
  106722. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106723. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106724. lastNode = orthoCamera;
  106725. }
  106726. else if (camera.type === "perspective") {
  106727. var perspectiveCamera = camera[camera.type];
  106728. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106729. persCamera.name = node.name || "";
  106730. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106731. if (!perspectiveCamera.aspectRatio) {
  106732. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106733. }
  106734. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106735. persCamera.maxZ = perspectiveCamera.zfar;
  106736. persCamera.minZ = perspectiveCamera.znear;
  106737. }
  106738. lastNode = persCamera;
  106739. }
  106740. }
  106741. }
  106742. // Empty node
  106743. if (!node.jointName) {
  106744. if (node.babylonNode) {
  106745. return node.babylonNode;
  106746. }
  106747. else if (lastNode === null) {
  106748. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106749. node.babylonNode = dummy;
  106750. lastNode = dummy;
  106751. }
  106752. }
  106753. if (lastNode !== null) {
  106754. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106755. configureNodeFromMatrix(lastNode, node, parent);
  106756. }
  106757. else {
  106758. var translation = node.translation || [0, 0, 0];
  106759. var rotation = node.rotation || [0, 0, 0, 1];
  106760. var scale = node.scale || [1, 1, 1];
  106761. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106762. }
  106763. lastNode.updateCache(true);
  106764. node.babylonNode = lastNode;
  106765. }
  106766. return lastNode;
  106767. };
  106768. /**
  106769. * Traverses nodes and creates them
  106770. */
  106771. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106772. if (meshIncluded === void 0) { meshIncluded = false; }
  106773. var node = gltfRuntime.nodes[id];
  106774. var newNode = null;
  106775. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  106776. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  106777. meshIncluded = true;
  106778. }
  106779. else {
  106780. meshIncluded = false;
  106781. }
  106782. }
  106783. else {
  106784. meshIncluded = true;
  106785. }
  106786. if (!node.jointName && meshIncluded) {
  106787. newNode = importNode(gltfRuntime, node, id, parent);
  106788. if (newNode !== null) {
  106789. newNode.id = id;
  106790. newNode.parent = parent;
  106791. }
  106792. }
  106793. if (node.children) {
  106794. for (var i = 0; i < node.children.length; i++) {
  106795. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  106796. }
  106797. }
  106798. };
  106799. /**
  106800. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  106801. */
  106802. var postLoad = function (gltfRuntime) {
  106803. // Nodes
  106804. var currentScene = gltfRuntime.currentScene;
  106805. if (currentScene) {
  106806. for (var i = 0; i < currentScene.nodes.length; i++) {
  106807. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106808. }
  106809. }
  106810. else {
  106811. for (var thing in gltfRuntime.scenes) {
  106812. currentScene = gltfRuntime.scenes[thing];
  106813. for (var i = 0; i < currentScene.nodes.length; i++) {
  106814. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106815. }
  106816. }
  106817. }
  106818. // Set animations
  106819. loadAnimations(gltfRuntime);
  106820. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  106821. var skeleton = gltfRuntime.scene.skeletons[i];
  106822. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  106823. }
  106824. };
  106825. /**
  106826. * onBind shaderrs callback to set uniforms and matrices
  106827. */
  106828. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  106829. var materialValues = material.values || technique.parameters;
  106830. for (var unif in unTreatedUniforms) {
  106831. var uniform = unTreatedUniforms[unif];
  106832. var type = uniform.type;
  106833. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  106834. if (uniform.semantic && !uniform.source && !uniform.node) {
  106835. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  106836. }
  106837. else if (uniform.semantic && (uniform.source || uniform.node)) {
  106838. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  106839. if (source === null) {
  106840. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  106841. }
  106842. if (source === null) {
  106843. continue;
  106844. }
  106845. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  106846. }
  106847. }
  106848. else {
  106849. var value = materialValues[technique.uniforms[unif]];
  106850. if (!value) {
  106851. continue;
  106852. }
  106853. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106854. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  106855. if (texture === null || texture === undefined) {
  106856. continue;
  106857. }
  106858. shaderMaterial.getEffect().setTexture(unif, texture);
  106859. }
  106860. else {
  106861. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  106862. }
  106863. }
  106864. }
  106865. onSuccess(shaderMaterial);
  106866. };
  106867. /**
  106868. * Prepare uniforms to send the only one time
  106869. * Loads the appropriate textures
  106870. */
  106871. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  106872. var materialValues = material.values || technique.parameters;
  106873. var techniqueUniforms = technique.uniforms;
  106874. /**
  106875. * Prepare values here (not matrices)
  106876. */
  106877. for (var unif in unTreatedUniforms) {
  106878. var uniform = unTreatedUniforms[unif];
  106879. var type = uniform.type;
  106880. var value = materialValues[techniqueUniforms[unif]];
  106881. if (value === undefined) {
  106882. // In case the value is the same for all materials
  106883. value = uniform.value;
  106884. }
  106885. if (!value) {
  106886. continue;
  106887. }
  106888. var onLoadTexture = function (uniformName) {
  106889. return function (texture) {
  106890. if (uniform.value && uniformName) {
  106891. // Static uniform
  106892. shaderMaterial.setTexture(uniformName, texture);
  106893. delete unTreatedUniforms[uniformName];
  106894. }
  106895. };
  106896. };
  106897. // Texture (sampler2D)
  106898. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106899. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  106900. }
  106901. else {
  106902. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  106903. // Static uniform
  106904. delete unTreatedUniforms[unif];
  106905. }
  106906. }
  106907. }
  106908. };
  106909. /**
  106910. * Shader compilation failed
  106911. */
  106912. var onShaderCompileError = function (program, shaderMaterial, onError) {
  106913. return function (effect, error) {
  106914. shaderMaterial.dispose(true);
  106915. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  106916. };
  106917. };
  106918. /**
  106919. * Shader compilation success
  106920. */
  106921. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  106922. return function (_) {
  106923. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  106924. shaderMaterial.onBind = function (mesh) {
  106925. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  106926. };
  106927. };
  106928. };
  106929. /**
  106930. * Returns the appropriate uniform if already handled by babylon
  106931. */
  106932. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  106933. for (var unif in technique.uniforms) {
  106934. var uniform = technique.uniforms[unif];
  106935. var uniformParameter = technique.parameters[uniform];
  106936. if (tokenizer.currentIdentifier === unif) {
  106937. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  106938. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106939. if (transformIndex !== -1) {
  106940. delete unTreatedUniforms[unif];
  106941. return babylonTransforms[transformIndex];
  106942. }
  106943. }
  106944. }
  106945. }
  106946. return tokenizer.currentIdentifier;
  106947. };
  106948. /**
  106949. * All shaders loaded. Create materials one by one
  106950. */
  106951. var importMaterials = function (gltfRuntime) {
  106952. // Create materials
  106953. for (var mat in gltfRuntime.materials) {
  106954. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  106955. }
  106956. };
  106957. /**
  106958. * Implementation of the base glTF spec
  106959. */
  106960. var GLTFLoaderBase = /** @class */ (function () {
  106961. function GLTFLoaderBase() {
  106962. }
  106963. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  106964. var gltfRuntime = {
  106965. extensions: {},
  106966. accessors: {},
  106967. buffers: {},
  106968. bufferViews: {},
  106969. meshes: {},
  106970. lights: {},
  106971. cameras: {},
  106972. nodes: {},
  106973. images: {},
  106974. textures: {},
  106975. shaders: {},
  106976. programs: {},
  106977. samplers: {},
  106978. techniques: {},
  106979. materials: {},
  106980. animations: {},
  106981. skins: {},
  106982. extensionsUsed: [],
  106983. scenes: {},
  106984. buffersCount: 0,
  106985. shaderscount: 0,
  106986. scene: scene,
  106987. rootUrl: rootUrl,
  106988. loadedBufferCount: 0,
  106989. loadedBufferViews: {},
  106990. loadedShaderCount: 0,
  106991. importOnlyMeshes: false,
  106992. dummyNodes: []
  106993. };
  106994. // Parse
  106995. if (parsedData.extensions) {
  106996. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  106997. }
  106998. if (parsedData.extensionsUsed) {
  106999. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107000. }
  107001. if (parsedData.buffers) {
  107002. parseBuffers(parsedData.buffers, gltfRuntime);
  107003. }
  107004. if (parsedData.bufferViews) {
  107005. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107006. }
  107007. if (parsedData.accessors) {
  107008. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107009. }
  107010. if (parsedData.meshes) {
  107011. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107012. }
  107013. if (parsedData.lights) {
  107014. parseObject(parsedData.lights, "lights", gltfRuntime);
  107015. }
  107016. if (parsedData.cameras) {
  107017. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107018. }
  107019. if (parsedData.nodes) {
  107020. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107021. }
  107022. if (parsedData.images) {
  107023. parseObject(parsedData.images, "images", gltfRuntime);
  107024. }
  107025. if (parsedData.textures) {
  107026. parseObject(parsedData.textures, "textures", gltfRuntime);
  107027. }
  107028. if (parsedData.shaders) {
  107029. parseShaders(parsedData.shaders, gltfRuntime);
  107030. }
  107031. if (parsedData.programs) {
  107032. parseObject(parsedData.programs, "programs", gltfRuntime);
  107033. }
  107034. if (parsedData.samplers) {
  107035. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107036. }
  107037. if (parsedData.techniques) {
  107038. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107039. }
  107040. if (parsedData.materials) {
  107041. parseObject(parsedData.materials, "materials", gltfRuntime);
  107042. }
  107043. if (parsedData.animations) {
  107044. parseObject(parsedData.animations, "animations", gltfRuntime);
  107045. }
  107046. if (parsedData.skins) {
  107047. parseObject(parsedData.skins, "skins", gltfRuntime);
  107048. }
  107049. if (parsedData.scenes) {
  107050. gltfRuntime.scenes = parsedData.scenes;
  107051. }
  107052. if (parsedData.scene && parsedData.scenes) {
  107053. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107054. }
  107055. return gltfRuntime;
  107056. };
  107057. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107058. var buffer = gltfRuntime.buffers[id];
  107059. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107060. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107061. }
  107062. else {
  107063. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107064. if (request) {
  107065. onError(request.status + " " + request.statusText);
  107066. }
  107067. });
  107068. }
  107069. };
  107070. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107071. var texture = gltfRuntime.textures[id];
  107072. if (!texture || !texture.source) {
  107073. onError("");
  107074. return;
  107075. }
  107076. if (texture.babylonTexture) {
  107077. onSuccess(null);
  107078. return;
  107079. }
  107080. var source = gltfRuntime.images[texture.source];
  107081. if (BABYLON.Tools.IsBase64(source.uri)) {
  107082. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107083. }
  107084. else {
  107085. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107086. if (request) {
  107087. onError(request.status + " " + request.statusText);
  107088. }
  107089. });
  107090. }
  107091. };
  107092. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107093. var texture = gltfRuntime.textures[id];
  107094. if (texture.babylonTexture) {
  107095. onSuccess(texture.babylonTexture);
  107096. return;
  107097. }
  107098. var sampler = gltfRuntime.samplers[texture.sampler];
  107099. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107100. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107101. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107102. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107103. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107104. var blob = new Blob([buffer]);
  107105. var blobURL = URL.createObjectURL(blob);
  107106. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107107. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107108. if (sampler.wrapS !== undefined) {
  107109. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107110. }
  107111. if (sampler.wrapT !== undefined) {
  107112. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107113. }
  107114. newTexture.name = id;
  107115. texture.babylonTexture = newTexture;
  107116. onSuccess(newTexture);
  107117. };
  107118. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107119. var shader = gltfRuntime.shaders[id];
  107120. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107121. var shaderString = atob(shader.uri.split(",")[1]);
  107122. onSuccess(shaderString);
  107123. }
  107124. else {
  107125. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107126. if (request) {
  107127. onError(request.status + " " + request.statusText);
  107128. }
  107129. });
  107130. }
  107131. };
  107132. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107133. var material = gltfRuntime.materials[id];
  107134. if (!material.technique) {
  107135. if (onError) {
  107136. onError("No technique found.");
  107137. }
  107138. return;
  107139. }
  107140. var technique = gltfRuntime.techniques[material.technique];
  107141. if (!technique) {
  107142. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107143. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107144. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107145. onSuccess(defaultMaterial);
  107146. return;
  107147. }
  107148. var program = gltfRuntime.programs[technique.program];
  107149. var states = technique.states;
  107150. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107151. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107152. var newVertexShader = "";
  107153. var newPixelShader = "";
  107154. var vertexTokenizer = new Tokenizer(vertexShader);
  107155. var pixelTokenizer = new Tokenizer(pixelShader);
  107156. var unTreatedUniforms = {};
  107157. var uniforms = [];
  107158. var attributes = [];
  107159. var samplers = [];
  107160. // Fill uniform, sampler2D and attributes
  107161. for (var unif in technique.uniforms) {
  107162. var uniform = technique.uniforms[unif];
  107163. var uniformParameter = technique.parameters[uniform];
  107164. unTreatedUniforms[unif] = uniformParameter;
  107165. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107166. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107167. if (transformIndex !== -1) {
  107168. uniforms.push(babylonTransforms[transformIndex]);
  107169. delete unTreatedUniforms[unif];
  107170. }
  107171. else {
  107172. uniforms.push(unif);
  107173. }
  107174. }
  107175. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107176. samplers.push(unif);
  107177. }
  107178. else {
  107179. uniforms.push(unif);
  107180. }
  107181. }
  107182. for (var attr in technique.attributes) {
  107183. var attribute = technique.attributes[attr];
  107184. var attributeParameter = technique.parameters[attribute];
  107185. if (attributeParameter.semantic) {
  107186. attributes.push(getAttribute(attributeParameter));
  107187. }
  107188. }
  107189. // Configure vertex shader
  107190. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107191. var tokenType = vertexTokenizer.currentToken;
  107192. if (tokenType !== ETokenType.IDENTIFIER) {
  107193. newVertexShader += vertexTokenizer.currentString;
  107194. continue;
  107195. }
  107196. var foundAttribute = false;
  107197. for (var attr in technique.attributes) {
  107198. var attribute = technique.attributes[attr];
  107199. var attributeParameter = technique.parameters[attribute];
  107200. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107201. newVertexShader += getAttribute(attributeParameter);
  107202. foundAttribute = true;
  107203. break;
  107204. }
  107205. }
  107206. if (foundAttribute) {
  107207. continue;
  107208. }
  107209. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107210. }
  107211. // Configure pixel shader
  107212. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107213. var tokenType = pixelTokenizer.currentToken;
  107214. if (tokenType !== ETokenType.IDENTIFIER) {
  107215. newPixelShader += pixelTokenizer.currentString;
  107216. continue;
  107217. }
  107218. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107219. }
  107220. // Create shader material
  107221. var shaderPath = {
  107222. vertex: program.vertexShader + id,
  107223. fragment: program.fragmentShader + id
  107224. };
  107225. var options = {
  107226. attributes: attributes,
  107227. uniforms: uniforms,
  107228. samplers: samplers,
  107229. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107230. };
  107231. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107232. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107233. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107234. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107235. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107236. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107237. if (states && states.functions) {
  107238. var functions = states.functions;
  107239. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107240. shaderMaterial.backFaceCulling = false;
  107241. }
  107242. var blendFunc = functions.blendFuncSeparate;
  107243. if (blendFunc) {
  107244. 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) {
  107245. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107246. }
  107247. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107248. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107249. }
  107250. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107251. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107252. }
  107253. 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) {
  107254. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107255. }
  107256. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107257. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107258. }
  107259. 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) {
  107260. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107261. }
  107262. }
  107263. }
  107264. };
  107265. return GLTFLoaderBase;
  107266. }());
  107267. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107268. /**
  107269. * glTF V1 Loader
  107270. */
  107271. var GLTFLoader = /** @class */ (function () {
  107272. function GLTFLoader() {
  107273. // #region Stubs for IGLTFLoader interface
  107274. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107275. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107276. this.compileMaterials = false;
  107277. this.useClipPlane = false;
  107278. this.compileShadowGenerators = false;
  107279. this.onDisposeObservable = new BABYLON.Observable();
  107280. this.onMeshLoadedObservable = new BABYLON.Observable();
  107281. this.onTextureLoadedObservable = new BABYLON.Observable();
  107282. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107283. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107284. this.onCompleteObservable = new BABYLON.Observable();
  107285. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107286. this.state = null;
  107287. }
  107288. GLTFLoader.RegisterExtension = function (extension) {
  107289. if (GLTFLoader.Extensions[extension.name]) {
  107290. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107291. return;
  107292. }
  107293. GLTFLoader.Extensions[extension.name] = extension;
  107294. };
  107295. GLTFLoader.prototype.dispose = function () { };
  107296. // #endregion
  107297. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107298. var _this = this;
  107299. scene.useRightHandedSystem = true;
  107300. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107301. gltfRuntime.importOnlyMeshes = true;
  107302. if (meshesNames === "") {
  107303. gltfRuntime.importMeshesNames = [];
  107304. }
  107305. else if (typeof meshesNames === "string") {
  107306. gltfRuntime.importMeshesNames = [meshesNames];
  107307. }
  107308. else if (meshesNames && !(meshesNames instanceof Array)) {
  107309. gltfRuntime.importMeshesNames = [meshesNames];
  107310. }
  107311. else {
  107312. gltfRuntime.importMeshesNames = [];
  107313. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107314. }
  107315. // Create nodes
  107316. _this._createNodes(gltfRuntime);
  107317. var meshes = new Array();
  107318. var skeletons = new Array();
  107319. // Fill arrays of meshes and skeletons
  107320. for (var nde in gltfRuntime.nodes) {
  107321. var node = gltfRuntime.nodes[nde];
  107322. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107323. meshes.push(node.babylonNode);
  107324. }
  107325. }
  107326. for (var skl in gltfRuntime.skins) {
  107327. var skin = gltfRuntime.skins[skl];
  107328. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107329. skeletons.push(skin.babylonSkeleton);
  107330. }
  107331. }
  107332. // Load buffers, shaders, materials, etc.
  107333. _this._loadBuffersAsync(gltfRuntime, function () {
  107334. _this._loadShadersAsync(gltfRuntime, function () {
  107335. importMaterials(gltfRuntime);
  107336. postLoad(gltfRuntime);
  107337. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107338. onSuccess(meshes, [], skeletons);
  107339. }
  107340. });
  107341. }, onProgress);
  107342. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107343. onSuccess(meshes, [], skeletons);
  107344. }
  107345. }, onError);
  107346. return true;
  107347. };
  107348. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107349. var _this = this;
  107350. return new Promise(function (resolve, reject) {
  107351. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107352. resolve({
  107353. meshes: meshes,
  107354. particleSystems: particleSystems,
  107355. skeletons: skeletons
  107356. });
  107357. }, onProgress, function (message) {
  107358. reject(new Error(message));
  107359. });
  107360. });
  107361. };
  107362. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107363. var _this = this;
  107364. scene.useRightHandedSystem = true;
  107365. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107366. // Load runtime extensios
  107367. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107368. // Create nodes
  107369. _this._createNodes(gltfRuntime);
  107370. // Load buffers, shaders, materials, etc.
  107371. _this._loadBuffersAsync(gltfRuntime, function () {
  107372. _this._loadShadersAsync(gltfRuntime, function () {
  107373. importMaterials(gltfRuntime);
  107374. postLoad(gltfRuntime);
  107375. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107376. onSuccess();
  107377. }
  107378. });
  107379. });
  107380. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107381. onSuccess();
  107382. }
  107383. }, onError);
  107384. }, onError);
  107385. };
  107386. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107387. var _this = this;
  107388. return new Promise(function (resolve, reject) {
  107389. _this._loadAsync(scene, data, rootUrl, function () {
  107390. resolve();
  107391. }, onProgress, function (message) {
  107392. reject(new Error(message));
  107393. });
  107394. });
  107395. };
  107396. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107397. var hasShaders = false;
  107398. var processShader = function (sha, shader) {
  107399. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107400. gltfRuntime.loadedShaderCount++;
  107401. if (shaderString) {
  107402. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107403. }
  107404. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107405. onload();
  107406. }
  107407. }, function () {
  107408. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107409. });
  107410. };
  107411. for (var sha in gltfRuntime.shaders) {
  107412. hasShaders = true;
  107413. var shader = gltfRuntime.shaders[sha];
  107414. if (shader) {
  107415. processShader.bind(this, sha, shader)();
  107416. }
  107417. else {
  107418. BABYLON.Tools.Error("No shader named: " + sha);
  107419. }
  107420. }
  107421. if (!hasShaders) {
  107422. onload();
  107423. }
  107424. };
  107425. ;
  107426. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107427. var hasBuffers = false;
  107428. var processBuffer = function (buf, buffer) {
  107429. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107430. gltfRuntime.loadedBufferCount++;
  107431. if (bufferView) {
  107432. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107433. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107434. }
  107435. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107436. }
  107437. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107438. onLoad();
  107439. }
  107440. }, function () {
  107441. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107442. });
  107443. };
  107444. for (var buf in gltfRuntime.buffers) {
  107445. hasBuffers = true;
  107446. var buffer = gltfRuntime.buffers[buf];
  107447. if (buffer) {
  107448. processBuffer.bind(this, buf, buffer)();
  107449. }
  107450. else {
  107451. BABYLON.Tools.Error("No buffer named: " + buf);
  107452. }
  107453. }
  107454. if (!hasBuffers) {
  107455. onLoad();
  107456. }
  107457. };
  107458. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107459. var currentScene = gltfRuntime.currentScene;
  107460. if (currentScene) {
  107461. // Only one scene even if multiple scenes are defined
  107462. for (var i = 0; i < currentScene.nodes.length; i++) {
  107463. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107464. }
  107465. }
  107466. else {
  107467. // Load all scenes
  107468. for (var thing in gltfRuntime.scenes) {
  107469. currentScene = gltfRuntime.scenes[thing];
  107470. for (var i = 0; i < currentScene.nodes.length; i++) {
  107471. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107472. }
  107473. }
  107474. }
  107475. };
  107476. GLTFLoader.Extensions = {};
  107477. return GLTFLoader;
  107478. }());
  107479. GLTF1.GLTFLoader = GLTFLoader;
  107480. ;
  107481. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107482. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107483. })(BABYLON || (BABYLON = {}));
  107484. //# sourceMappingURL=babylon.glTFLoader.js.map
  107485. var BABYLON;
  107486. (function (BABYLON) {
  107487. var GLTF1;
  107488. (function (GLTF1) {
  107489. /**
  107490. * Utils functions for GLTF
  107491. */
  107492. var GLTFUtils = /** @class */ (function () {
  107493. function GLTFUtils() {
  107494. }
  107495. /**
  107496. * Sets the given "parameter" matrix
  107497. * @param scene: the {BABYLON.Scene} object
  107498. * @param source: the source node where to pick the matrix
  107499. * @param parameter: the GLTF technique parameter
  107500. * @param uniformName: the name of the shader's uniform
  107501. * @param shaderMaterial: the shader material
  107502. */
  107503. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107504. var mat = null;
  107505. if (parameter.semantic === "MODEL") {
  107506. mat = source.getWorldMatrix();
  107507. }
  107508. else if (parameter.semantic === "PROJECTION") {
  107509. mat = scene.getProjectionMatrix();
  107510. }
  107511. else if (parameter.semantic === "VIEW") {
  107512. mat = scene.getViewMatrix();
  107513. }
  107514. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107515. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107516. }
  107517. else if (parameter.semantic === "MODELVIEW") {
  107518. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107519. }
  107520. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107521. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107522. }
  107523. else if (parameter.semantic === "MODELINVERSE") {
  107524. mat = source.getWorldMatrix().invert();
  107525. }
  107526. else if (parameter.semantic === "VIEWINVERSE") {
  107527. mat = scene.getViewMatrix().invert();
  107528. }
  107529. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107530. mat = scene.getProjectionMatrix().invert();
  107531. }
  107532. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107533. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107534. }
  107535. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107536. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107537. }
  107538. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107539. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107540. }
  107541. else {
  107542. debugger;
  107543. }
  107544. if (mat) {
  107545. switch (parameter.type) {
  107546. case GLTF1.EParameterType.FLOAT_MAT2:
  107547. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107548. break;
  107549. case GLTF1.EParameterType.FLOAT_MAT3:
  107550. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107551. break;
  107552. case GLTF1.EParameterType.FLOAT_MAT4:
  107553. shaderMaterial.setMatrix(uniformName, mat);
  107554. break;
  107555. default: break;
  107556. }
  107557. }
  107558. };
  107559. /**
  107560. * Sets the given "parameter" matrix
  107561. * @param shaderMaterial: the shader material
  107562. * @param uniform: the name of the shader's uniform
  107563. * @param value: the value of the uniform
  107564. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107565. */
  107566. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107567. switch (type) {
  107568. case GLTF1.EParameterType.FLOAT:
  107569. shaderMaterial.setFloat(uniform, value);
  107570. return true;
  107571. case GLTF1.EParameterType.FLOAT_VEC2:
  107572. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107573. return true;
  107574. case GLTF1.EParameterType.FLOAT_VEC3:
  107575. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107576. return true;
  107577. case GLTF1.EParameterType.FLOAT_VEC4:
  107578. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107579. return true;
  107580. default: return false;
  107581. }
  107582. };
  107583. /**
  107584. * Returns the wrap mode of the texture
  107585. * @param mode: the mode value
  107586. */
  107587. GLTFUtils.GetWrapMode = function (mode) {
  107588. switch (mode) {
  107589. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107590. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107591. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107592. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107593. }
  107594. };
  107595. /**
  107596. * Returns the byte stride giving an accessor
  107597. * @param accessor: the GLTF accessor objet
  107598. */
  107599. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107600. // Needs this function since "byteStride" isn't requiered in glTF format
  107601. var type = accessor.type;
  107602. switch (type) {
  107603. case "VEC2": return 2;
  107604. case "VEC3": return 3;
  107605. case "VEC4": return 4;
  107606. case "MAT2": return 4;
  107607. case "MAT3": return 9;
  107608. case "MAT4": return 16;
  107609. default: return 1;
  107610. }
  107611. };
  107612. /**
  107613. * Returns the texture filter mode giving a mode value
  107614. * @param mode: the filter mode value
  107615. */
  107616. GLTFUtils.GetTextureFilterMode = function (mode) {
  107617. switch (mode) {
  107618. case GLTF1.ETextureFilterType.LINEAR:
  107619. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107620. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107621. case GLTF1.ETextureFilterType.NEAREST:
  107622. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107623. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107624. }
  107625. };
  107626. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107627. var byteOffset = bufferView.byteOffset + byteOffset;
  107628. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107629. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107630. throw new Error("Buffer access is out of range");
  107631. }
  107632. var buffer = loadedBufferView.buffer;
  107633. byteOffset += loadedBufferView.byteOffset;
  107634. switch (componentType) {
  107635. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107636. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107637. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107638. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107639. default: return new Float32Array(buffer, byteOffset, byteLength);
  107640. }
  107641. };
  107642. /**
  107643. * Returns a buffer from its accessor
  107644. * @param gltfRuntime: the GLTF runtime
  107645. * @param accessor: the GLTF accessor
  107646. */
  107647. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107648. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107649. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107650. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107651. };
  107652. /**
  107653. * Decodes a buffer view into a string
  107654. * @param view: the buffer view
  107655. */
  107656. GLTFUtils.DecodeBufferToText = function (view) {
  107657. var result = "";
  107658. var length = view.byteLength;
  107659. for (var i = 0; i < length; ++i) {
  107660. result += String.fromCharCode(view[i]);
  107661. }
  107662. return result;
  107663. };
  107664. /**
  107665. * Returns the default material of gltf. Related to
  107666. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107667. * @param scene: the Babylon.js scene
  107668. */
  107669. GLTFUtils.GetDefaultMaterial = function (scene) {
  107670. if (!GLTFUtils._DefaultMaterial) {
  107671. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107672. "precision highp float;",
  107673. "",
  107674. "uniform mat4 worldView;",
  107675. "uniform mat4 projection;",
  107676. "",
  107677. "attribute vec3 position;",
  107678. "",
  107679. "void main(void)",
  107680. "{",
  107681. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107682. "}"
  107683. ].join("\n");
  107684. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107685. "precision highp float;",
  107686. "",
  107687. "uniform vec4 u_emission;",
  107688. "",
  107689. "void main(void)",
  107690. "{",
  107691. " gl_FragColor = u_emission;",
  107692. "}"
  107693. ].join("\n");
  107694. var shaderPath = {
  107695. vertex: "GLTFDefaultMaterial",
  107696. fragment: "GLTFDefaultMaterial"
  107697. };
  107698. var options = {
  107699. attributes: ["position"],
  107700. uniforms: ["worldView", "projection", "u_emission"],
  107701. samplers: new Array(),
  107702. needAlphaBlending: false
  107703. };
  107704. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107705. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107706. }
  107707. return GLTFUtils._DefaultMaterial;
  107708. };
  107709. // The GLTF default material
  107710. GLTFUtils._DefaultMaterial = null;
  107711. return GLTFUtils;
  107712. }());
  107713. GLTF1.GLTFUtils = GLTFUtils;
  107714. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107715. })(BABYLON || (BABYLON = {}));
  107716. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107717. var BABYLON;
  107718. (function (BABYLON) {
  107719. var GLTF1;
  107720. (function (GLTF1) {
  107721. var GLTFLoaderExtension = /** @class */ (function () {
  107722. function GLTFLoaderExtension(name) {
  107723. this._name = name;
  107724. }
  107725. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107726. get: function () {
  107727. return this._name;
  107728. },
  107729. enumerable: true,
  107730. configurable: true
  107731. });
  107732. /**
  107733. * Defines an override for loading the runtime
  107734. * Return true to stop further extensions from loading the runtime
  107735. */
  107736. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107737. return false;
  107738. };
  107739. /**
  107740. * Defines an onverride for creating gltf runtime
  107741. * Return true to stop further extensions from creating the runtime
  107742. */
  107743. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107744. return false;
  107745. };
  107746. /**
  107747. * Defines an override for loading buffers
  107748. * Return true to stop further extensions from loading this buffer
  107749. */
  107750. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107751. return false;
  107752. };
  107753. /**
  107754. * Defines an override for loading texture buffers
  107755. * Return true to stop further extensions from loading this texture data
  107756. */
  107757. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107758. return false;
  107759. };
  107760. /**
  107761. * Defines an override for creating textures
  107762. * Return true to stop further extensions from loading this texture
  107763. */
  107764. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107765. return false;
  107766. };
  107767. /**
  107768. * Defines an override for loading shader strings
  107769. * Return true to stop further extensions from loading this shader data
  107770. */
  107771. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107772. return false;
  107773. };
  107774. /**
  107775. * Defines an override for loading materials
  107776. * Return true to stop further extensions from loading this material
  107777. */
  107778. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107779. return false;
  107780. };
  107781. // ---------
  107782. // Utilities
  107783. // ---------
  107784. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107785. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107786. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  107787. }, function () {
  107788. setTimeout(function () {
  107789. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107790. });
  107791. });
  107792. };
  107793. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107794. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107795. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  107796. }, function () {
  107797. setTimeout(function () {
  107798. onSuccess();
  107799. });
  107800. });
  107801. };
  107802. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107803. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107804. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107805. }, function () {
  107806. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107807. });
  107808. };
  107809. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  107810. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  107811. };
  107812. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107813. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107814. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107815. }, function () {
  107816. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107817. });
  107818. };
  107819. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107820. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107821. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107822. }, function () {
  107823. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107824. });
  107825. };
  107826. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107827. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107828. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107829. }, function () {
  107830. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107831. });
  107832. };
  107833. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107834. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107835. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107836. }, function () {
  107837. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107838. });
  107839. };
  107840. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107841. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107842. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107843. if (func(loaderExtension)) {
  107844. return;
  107845. }
  107846. }
  107847. defaultFunc();
  107848. };
  107849. return GLTFLoaderExtension;
  107850. }());
  107851. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107852. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107853. })(BABYLON || (BABYLON = {}));
  107854. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107855. var BABYLON;
  107856. (function (BABYLON) {
  107857. var GLTF1;
  107858. (function (GLTF1) {
  107859. var BinaryExtensionBufferName = "binary_glTF";
  107860. ;
  107861. ;
  107862. var GLTFBinaryExtension = /** @class */ (function (_super) {
  107863. __extends(GLTFBinaryExtension, _super);
  107864. function GLTFBinaryExtension() {
  107865. return _super.call(this, "KHR_binary_glTF") || this;
  107866. }
  107867. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107868. var extensionsUsed = data.json.extensionsUsed;
  107869. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  107870. return false;
  107871. }
  107872. this._bin = data.bin;
  107873. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107874. return true;
  107875. };
  107876. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107877. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  107878. return false;
  107879. }
  107880. if (id !== BinaryExtensionBufferName) {
  107881. return false;
  107882. }
  107883. onSuccess(this._bin);
  107884. return true;
  107885. };
  107886. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107887. var texture = gltfRuntime.textures[id];
  107888. var source = gltfRuntime.images[texture.source];
  107889. if (!source.extensions || !(this.name in source.extensions)) {
  107890. return false;
  107891. }
  107892. var sourceExt = source.extensions[this.name];
  107893. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  107894. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107895. onSuccess(buffer);
  107896. return true;
  107897. };
  107898. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107899. var shader = gltfRuntime.shaders[id];
  107900. if (!shader.extensions || !(this.name in shader.extensions)) {
  107901. return false;
  107902. }
  107903. var binaryExtensionShader = shader.extensions[this.name];
  107904. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  107905. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107906. setTimeout(function () {
  107907. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  107908. onSuccess(shaderString);
  107909. });
  107910. return true;
  107911. };
  107912. return GLTFBinaryExtension;
  107913. }(GLTF1.GLTFLoaderExtension));
  107914. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  107915. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  107916. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107917. })(BABYLON || (BABYLON = {}));
  107918. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  107919. var BABYLON;
  107920. (function (BABYLON) {
  107921. var GLTF1;
  107922. (function (GLTF1) {
  107923. ;
  107924. ;
  107925. ;
  107926. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  107927. __extends(GLTFMaterialsCommonExtension, _super);
  107928. function GLTFMaterialsCommonExtension() {
  107929. return _super.call(this, "KHR_materials_common") || this;
  107930. }
  107931. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107932. if (!gltfRuntime.extensions)
  107933. return false;
  107934. var extension = gltfRuntime.extensions[this.name];
  107935. if (!extension)
  107936. return false;
  107937. // Create lights
  107938. var lights = extension.lights;
  107939. if (lights) {
  107940. for (var thing in lights) {
  107941. var light = lights[thing];
  107942. switch (light.type) {
  107943. case "ambient":
  107944. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  107945. var ambient = light.ambient;
  107946. if (ambient) {
  107947. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  107948. }
  107949. break;
  107950. case "point":
  107951. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  107952. var point = light.point;
  107953. if (point) {
  107954. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  107955. }
  107956. break;
  107957. case "directional":
  107958. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  107959. var directional = light.directional;
  107960. if (directional) {
  107961. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  107962. }
  107963. break;
  107964. case "spot":
  107965. var spot = light.spot;
  107966. if (spot) {
  107967. 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);
  107968. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  107969. }
  107970. break;
  107971. default:
  107972. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  107973. break;
  107974. }
  107975. }
  107976. }
  107977. return false;
  107978. };
  107979. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107980. var material = gltfRuntime.materials[id];
  107981. if (!material || !material.extensions)
  107982. return false;
  107983. var extension = material.extensions[this.name];
  107984. if (!extension)
  107985. return false;
  107986. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107987. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107988. if (extension.technique === "CONSTANT") {
  107989. standardMaterial.disableLighting = true;
  107990. }
  107991. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  107992. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  107993. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  107994. // Ambient
  107995. if (typeof extension.values.ambient === "string") {
  107996. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  107997. }
  107998. else {
  107999. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108000. }
  108001. // Diffuse
  108002. if (typeof extension.values.diffuse === "string") {
  108003. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108004. }
  108005. else {
  108006. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108007. }
  108008. // Emission
  108009. if (typeof extension.values.emission === "string") {
  108010. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108011. }
  108012. else {
  108013. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108014. }
  108015. // Specular
  108016. if (typeof extension.values.specular === "string") {
  108017. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108018. }
  108019. else {
  108020. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108021. }
  108022. return true;
  108023. };
  108024. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108025. // Create buffer from texture url
  108026. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108027. // Create texture from buffer
  108028. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108029. }, onError);
  108030. };
  108031. return GLTFMaterialsCommonExtension;
  108032. }(GLTF1.GLTFLoaderExtension));
  108033. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108034. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108035. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108036. })(BABYLON || (BABYLON = {}));
  108037. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108038. var BABYLON;
  108039. (function (BABYLON) {
  108040. var GLTF2;
  108041. (function (GLTF2) {
  108042. var ArrayItem = /** @class */ (function () {
  108043. function ArrayItem() {
  108044. }
  108045. ArrayItem.Assign = function (values) {
  108046. if (values) {
  108047. for (var index = 0; index < values.length; index++) {
  108048. values[index]._index = index;
  108049. }
  108050. }
  108051. };
  108052. return ArrayItem;
  108053. }());
  108054. GLTF2.ArrayItem = ArrayItem;
  108055. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108056. })(BABYLON || (BABYLON = {}));
  108057. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108058. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108059. var BABYLON;
  108060. (function (BABYLON) {
  108061. var GLTF2;
  108062. (function (GLTF2) {
  108063. var GLTFLoader = /** @class */ (function () {
  108064. function GLTFLoader() {
  108065. this._completePromises = new Array();
  108066. this._disposed = false;
  108067. this._state = null;
  108068. this._extensions = {};
  108069. this._defaultSampler = {};
  108070. this._requests = new Array();
  108071. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108072. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108073. this.compileMaterials = false;
  108074. this.useClipPlane = false;
  108075. this.compileShadowGenerators = false;
  108076. this.onDisposeObservable = new BABYLON.Observable();
  108077. this.onMeshLoadedObservable = new BABYLON.Observable();
  108078. this.onTextureLoadedObservable = new BABYLON.Observable();
  108079. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108080. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108081. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108082. this.onCompleteObservable = new BABYLON.Observable();
  108083. }
  108084. GLTFLoader._Register = function (name, factory) {
  108085. if (GLTFLoader._Factories[name]) {
  108086. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108087. return;
  108088. }
  108089. GLTFLoader._Factories[name] = factory;
  108090. // Keep the order of registration so that extensions registered first are called first.
  108091. GLTFLoader._Names.push(name);
  108092. };
  108093. Object.defineProperty(GLTFLoader.prototype, "state", {
  108094. get: function () {
  108095. return this._state;
  108096. },
  108097. enumerable: true,
  108098. configurable: true
  108099. });
  108100. GLTFLoader.prototype.dispose = function () {
  108101. if (this._disposed) {
  108102. return;
  108103. }
  108104. this._disposed = true;
  108105. this.onDisposeObservable.notifyObservers(this);
  108106. this.onDisposeObservable.clear();
  108107. this._clear();
  108108. };
  108109. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108110. var _this = this;
  108111. return Promise.resolve().then(function () {
  108112. var nodes = null;
  108113. if (meshesNames) {
  108114. var nodeMap_1 = {};
  108115. if (_this._gltf.nodes) {
  108116. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108117. var node = _a[_i];
  108118. if (node.name) {
  108119. nodeMap_1[node.name] = node;
  108120. }
  108121. }
  108122. }
  108123. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108124. nodes = names.map(function (name) {
  108125. var node = nodeMap_1[name];
  108126. if (!node) {
  108127. throw new Error("Failed to find node '" + name + "'");
  108128. }
  108129. return node;
  108130. });
  108131. }
  108132. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108133. return {
  108134. meshes: _this._getMeshes(),
  108135. particleSystems: [],
  108136. skeletons: _this._getSkeletons(),
  108137. };
  108138. });
  108139. });
  108140. };
  108141. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108142. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108143. };
  108144. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108145. var _this = this;
  108146. return Promise.resolve().then(function () {
  108147. _this._loadExtensions();
  108148. _this._babylonScene = scene;
  108149. _this._rootUrl = rootUrl;
  108150. _this._progressCallback = onProgress;
  108151. _this._state = BABYLON.GLTFLoaderState.Loading;
  108152. _this._loadData(data);
  108153. _this._checkExtensions();
  108154. var promises = new Array();
  108155. if (nodes) {
  108156. promises.push(_this._loadNodesAsync(nodes));
  108157. }
  108158. else {
  108159. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108160. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108161. }
  108162. if (_this.compileMaterials) {
  108163. promises.push(_this._compileMaterialsAsync());
  108164. }
  108165. if (_this.compileShadowGenerators) {
  108166. promises.push(_this._compileShadowGeneratorsAsync());
  108167. }
  108168. var resultPromise = Promise.all(promises).then(function () {
  108169. _this._state = BABYLON.GLTFLoaderState.Ready;
  108170. _this._startAnimations();
  108171. });
  108172. resultPromise.then(function () {
  108173. _this._rootBabylonMesh.setEnabled(true);
  108174. BABYLON.Tools.SetImmediate(function () {
  108175. if (!_this._disposed) {
  108176. Promise.all(_this._completePromises).then(function () {
  108177. _this._state = BABYLON.GLTFLoaderState.Complete;
  108178. _this.onCompleteObservable.notifyObservers(_this);
  108179. _this.onCompleteObservable.clear();
  108180. _this._clear();
  108181. }).catch(function (error) {
  108182. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108183. _this._clear();
  108184. });
  108185. }
  108186. });
  108187. });
  108188. return resultPromise;
  108189. }).catch(function (error) {
  108190. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108191. _this._clear();
  108192. throw error;
  108193. });
  108194. };
  108195. GLTFLoader.prototype._loadExtensions = function () {
  108196. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108197. var name_1 = _a[_i];
  108198. var extension = GLTFLoader._Factories[name_1](this);
  108199. this._extensions[name_1] = extension;
  108200. this.onExtensionLoadedObservable.notifyObservers(extension);
  108201. }
  108202. this.onExtensionLoadedObservable.clear();
  108203. };
  108204. GLTFLoader.prototype._loadData = function (data) {
  108205. this._gltf = data.json;
  108206. this._setupData();
  108207. if (data.bin) {
  108208. var buffers = this._gltf.buffers;
  108209. if (buffers && buffers[0] && !buffers[0].uri) {
  108210. var binaryBuffer = buffers[0];
  108211. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108212. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108213. }
  108214. binaryBuffer._data = Promise.resolve(data.bin);
  108215. }
  108216. else {
  108217. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108218. }
  108219. }
  108220. };
  108221. GLTFLoader.prototype._setupData = function () {
  108222. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108223. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108224. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108225. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108226. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108227. GLTF2.ArrayItem.Assign(this._gltf.images);
  108228. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108229. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108230. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108231. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108232. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108233. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108234. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108235. if (this._gltf.nodes) {
  108236. var nodeParents = {};
  108237. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108238. var node = _a[_i];
  108239. if (node.children) {
  108240. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108241. var index = _c[_b];
  108242. nodeParents[index] = node._index;
  108243. }
  108244. }
  108245. }
  108246. var rootNode = this._createRootNode();
  108247. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108248. var node = _e[_d];
  108249. var parentIndex = nodeParents[node._index];
  108250. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108251. }
  108252. }
  108253. };
  108254. GLTFLoader.prototype._checkExtensions = function () {
  108255. if (this._gltf.extensionsRequired) {
  108256. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108257. var name_2 = _a[_i];
  108258. var extension = this._extensions[name_2];
  108259. if (!extension || !extension.enabled) {
  108260. throw new Error("Require extension " + name_2 + " is not available");
  108261. }
  108262. }
  108263. }
  108264. };
  108265. GLTFLoader.prototype._createRootNode = function () {
  108266. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108267. this._rootBabylonMesh.setEnabled(false);
  108268. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108269. switch (this.coordinateSystemMode) {
  108270. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108271. if (!this._babylonScene.useRightHandedSystem) {
  108272. rootNode.rotation = [0, 1, 0, 0];
  108273. rootNode.scale = [1, 1, -1];
  108274. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108275. }
  108276. break;
  108277. }
  108278. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108279. this._babylonScene.useRightHandedSystem = true;
  108280. break;
  108281. }
  108282. default: {
  108283. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108284. }
  108285. }
  108286. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108287. return rootNode;
  108288. };
  108289. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108290. var promises = new Array();
  108291. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108292. var node = nodes_1[_i];
  108293. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108294. }
  108295. promises.push(this._loadAnimationsAsync());
  108296. return Promise.all(promises).then(function () { });
  108297. };
  108298. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108299. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108300. if (promise) {
  108301. return promise;
  108302. }
  108303. var promises = new Array();
  108304. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108305. var index = _a[_i];
  108306. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108307. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108308. }
  108309. promises.push(this._loadAnimationsAsync());
  108310. return Promise.all(promises).then(function () { });
  108311. };
  108312. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  108313. if (node._babylonMesh) {
  108314. callback(node._babylonMesh);
  108315. }
  108316. if (node._primitiveBabylonMeshes) {
  108317. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108318. var babylonMesh = _a[_i];
  108319. callback(babylonMesh);
  108320. }
  108321. }
  108322. };
  108323. GLTFLoader.prototype._getMeshes = function () {
  108324. var meshes = new Array();
  108325. // Root mesh is always first.
  108326. meshes.push(this._rootBabylonMesh);
  108327. var nodes = this._gltf.nodes;
  108328. if (nodes) {
  108329. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108330. var node = nodes_2[_i];
  108331. this._forEachNodeMesh(node, function (mesh) {
  108332. meshes.push(mesh);
  108333. });
  108334. }
  108335. }
  108336. return meshes;
  108337. };
  108338. GLTFLoader.prototype._getSkeletons = function () {
  108339. var skeletons = new Array();
  108340. var skins = this._gltf.skins;
  108341. if (skins) {
  108342. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108343. var skin = skins_1[_i];
  108344. if (skin._babylonSkeleton) {
  108345. skeletons.push(skin._babylonSkeleton);
  108346. }
  108347. }
  108348. }
  108349. return skeletons;
  108350. };
  108351. GLTFLoader.prototype._startAnimations = function () {
  108352. var animations = this._gltf.animations;
  108353. if (!animations) {
  108354. return;
  108355. }
  108356. switch (this.animationStartMode) {
  108357. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108358. // do nothing
  108359. break;
  108360. }
  108361. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108362. var animation = animations[0];
  108363. animation._babylonAnimationGroup.start(true);
  108364. break;
  108365. }
  108366. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108367. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108368. var animation = animations_1[_i];
  108369. animation._babylonAnimationGroup.start(true);
  108370. }
  108371. break;
  108372. }
  108373. default: {
  108374. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108375. return;
  108376. }
  108377. }
  108378. };
  108379. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108380. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108381. if (promise) {
  108382. return promise;
  108383. }
  108384. if (node._babylonMesh) {
  108385. throw new Error(context + ": Invalid recursive node hierarchy");
  108386. }
  108387. var promises = new Array();
  108388. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108389. node._babylonMesh = babylonMesh;
  108390. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108391. node._babylonAnimationTargets.push(babylonMesh);
  108392. GLTFLoader._LoadTransform(node, babylonMesh);
  108393. if (node.mesh != undefined) {
  108394. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108395. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108396. }
  108397. if (node.children) {
  108398. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108399. var index = _a[_i];
  108400. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108401. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108402. }
  108403. }
  108404. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108405. return Promise.all(promises).then(function () { });
  108406. };
  108407. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108408. // TODO: instancing
  108409. var _this = this;
  108410. var promises = new Array();
  108411. var primitives = mesh.primitives;
  108412. if (!primitives || primitives.length === 0) {
  108413. throw new Error(context + ": Primitives are missing");
  108414. }
  108415. GLTF2.ArrayItem.Assign(primitives);
  108416. if (primitives.length === 1) {
  108417. var primitive = primitives[0];
  108418. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108419. }
  108420. else {
  108421. node._primitiveBabylonMeshes = [];
  108422. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108423. var primitive = primitives_1[_i];
  108424. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108425. node._primitiveBabylonMeshes.push(babylonMesh);
  108426. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108427. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108428. }
  108429. }
  108430. if (node.skin != undefined) {
  108431. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108432. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108433. }
  108434. return Promise.all(promises).then(function () {
  108435. _this._forEachNodeMesh(node, function (babylonMesh) {
  108436. babylonMesh._refreshBoundingInfo(true);
  108437. });
  108438. });
  108439. };
  108440. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108441. var _this = this;
  108442. var promises = new Array();
  108443. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108444. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  108445. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  108446. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  108447. }));
  108448. if (primitive.material == undefined) {
  108449. babylonMesh.material = this._getDefaultMaterial();
  108450. }
  108451. else {
  108452. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108453. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  108454. babylonMesh.material = babylonMaterial;
  108455. }));
  108456. }
  108457. return Promise.all(promises).then(function () { });
  108458. };
  108459. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108460. var _this = this;
  108461. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108462. if (promise) {
  108463. return promise;
  108464. }
  108465. var attributes = primitive.attributes;
  108466. if (!attributes) {
  108467. throw new Error(context + ": Attributes are missing");
  108468. }
  108469. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  108470. // TODO: handle other primitive modes
  108471. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  108472. }
  108473. var promises = new Array();
  108474. var babylonVertexData = new BABYLON.VertexData();
  108475. if (primitive.indices == undefined) {
  108476. var positionAccessorIndex = attributes["POSITION"];
  108477. if (positionAccessorIndex != undefined) {
  108478. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  108479. babylonVertexData.indices = new Uint32Array(accessor.count);
  108480. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  108481. babylonVertexData.indices[i] = i;
  108482. }
  108483. }
  108484. }
  108485. else {
  108486. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108487. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  108488. babylonVertexData.indices = data;
  108489. }));
  108490. }
  108491. var loadAttribute = function (attribute, kind) {
  108492. if (attributes[attribute] == undefined) {
  108493. return;
  108494. }
  108495. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108496. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108497. babylonMesh._delayInfo.push(kind);
  108498. }
  108499. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108500. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108501. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  108502. if (attribute === "COLOR_0") {
  108503. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  108504. babylonMesh.hasVertexAlpha = true;
  108505. if (accessor.type === "VEC3") {
  108506. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  108507. }
  108508. }
  108509. babylonVertexData.set(attributeData, kind);
  108510. }));
  108511. };
  108512. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108513. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108514. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108515. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108516. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108517. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108518. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108519. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108520. return Promise.all(promises).then(function () {
  108521. return babylonVertexData;
  108522. });
  108523. };
  108524. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108525. if (!primitive.targets) {
  108526. return;
  108527. }
  108528. if (node._numMorphTargets == undefined) {
  108529. node._numMorphTargets = primitive.targets.length;
  108530. }
  108531. else if (primitive.targets.length !== node._numMorphTargets) {
  108532. throw new Error(context + ": Primitives do not have the same number of targets");
  108533. }
  108534. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108535. for (var index = 0; index < primitive.targets.length; index++) {
  108536. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108537. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108538. // TODO: tell the target whether it has positions, normals, tangents
  108539. }
  108540. };
  108541. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108542. if (!primitive.targets) {
  108543. return Promise.resolve();
  108544. }
  108545. var promises = new Array();
  108546. var morphTargetManager = babylonMesh.morphTargetManager;
  108547. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108548. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108549. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108550. }
  108551. return Promise.all(promises).then(function () { });
  108552. };
  108553. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108554. var _this = this;
  108555. var promises = new Array();
  108556. var loadAttribute = function (attribute, setData) {
  108557. if (attributes[attribute] == undefined) {
  108558. return;
  108559. }
  108560. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108561. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108562. setData(data);
  108563. }));
  108564. };
  108565. loadAttribute("POSITION", function (data) {
  108566. if (babylonVertexData.positions) {
  108567. for (var i = 0; i < data.length; i++) {
  108568. data[i] += babylonVertexData.positions[i];
  108569. }
  108570. babylonMorphTarget.setPositions(data);
  108571. }
  108572. });
  108573. loadAttribute("NORMAL", function (data) {
  108574. if (babylonVertexData.normals) {
  108575. for (var i = 0; i < data.length; i++) {
  108576. data[i] += babylonVertexData.normals[i];
  108577. }
  108578. babylonMorphTarget.setNormals(data);
  108579. }
  108580. });
  108581. loadAttribute("TANGENT", function (data) {
  108582. if (babylonVertexData.tangents) {
  108583. // Tangent data for morph targets is stored as xyz delta.
  108584. // The vertexData.tangent is stored as xyzw.
  108585. // So we need to skip every fourth vertexData.tangent.
  108586. for (var i = 0, j = 0; i < data.length; i++) {
  108587. data[i] += babylonVertexData.tangents[j++];
  108588. if ((i + 1) % 3 == 0) {
  108589. j++;
  108590. }
  108591. }
  108592. babylonMorphTarget.setTangents(data);
  108593. }
  108594. });
  108595. return Promise.all(promises).then(function () { });
  108596. };
  108597. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108598. if (accessor.componentType == 5126 /* FLOAT */) {
  108599. return data;
  108600. }
  108601. var factor = 1;
  108602. if (accessor.normalized) {
  108603. switch (accessor.componentType) {
  108604. case 5121 /* UNSIGNED_BYTE */: {
  108605. factor = 1 / 255;
  108606. break;
  108607. }
  108608. case 5123 /* UNSIGNED_SHORT */: {
  108609. factor = 1 / 65535;
  108610. break;
  108611. }
  108612. default: {
  108613. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  108614. }
  108615. }
  108616. }
  108617. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108618. for (var i = 0; i < result.length; i++) {
  108619. result[i] = data[i] * factor;
  108620. }
  108621. return result;
  108622. };
  108623. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108624. var result = new Float32Array(data.length / 3 * 4);
  108625. var offset = 0;
  108626. for (var i = 0; i < result.length; i++) {
  108627. if ((i + 1) % 4 === 0) {
  108628. result[i] = 1;
  108629. }
  108630. else {
  108631. result[i] = data[offset++];
  108632. }
  108633. }
  108634. return result;
  108635. };
  108636. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108637. var position = BABYLON.Vector3.Zero();
  108638. var rotation = BABYLON.Quaternion.Identity();
  108639. var scaling = BABYLON.Vector3.One();
  108640. if (node.matrix) {
  108641. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108642. matrix.decompose(scaling, rotation, position);
  108643. }
  108644. else {
  108645. if (node.translation)
  108646. position = BABYLON.Vector3.FromArray(node.translation);
  108647. if (node.rotation)
  108648. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108649. if (node.scale)
  108650. scaling = BABYLON.Vector3.FromArray(node.scale);
  108651. }
  108652. babylonNode.position = position;
  108653. babylonNode.rotationQuaternion = rotation;
  108654. babylonNode.scaling = scaling;
  108655. };
  108656. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108657. var _this = this;
  108658. var assignSkeleton = function () {
  108659. _this._forEachNodeMesh(node, function (babylonMesh) {
  108660. babylonMesh.skeleton = skin._babylonSkeleton;
  108661. });
  108662. node._babylonMesh.parent = _this._rootBabylonMesh;
  108663. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108664. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108665. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108666. };
  108667. if (skin._loaded) {
  108668. return skin._loaded.then(function () {
  108669. assignSkeleton();
  108670. });
  108671. }
  108672. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108673. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108674. var skeletonId = "skeleton" + skin._index;
  108675. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108676. skin._babylonSkeleton = babylonSkeleton;
  108677. _this._loadBones(context, skin, inverseBindMatricesData);
  108678. assignSkeleton();
  108679. }));
  108680. };
  108681. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108682. if (skin.inverseBindMatrices == undefined) {
  108683. return Promise.resolve(null);
  108684. }
  108685. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108686. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108687. return data;
  108688. });
  108689. };
  108690. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108691. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108692. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108693. node._babylonAnimationTargets.push(babylonBone);
  108694. return babylonBone;
  108695. };
  108696. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108697. var babylonBones = {};
  108698. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108699. var index = _a[_i];
  108700. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108701. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108702. }
  108703. };
  108704. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108705. var babylonBone = babylonBones[node._index];
  108706. if (babylonBone) {
  108707. return babylonBone;
  108708. }
  108709. var boneIndex = skin.joints.indexOf(node._index);
  108710. var baseMatrix = BABYLON.Matrix.Identity();
  108711. if (inverseBindMatricesData && boneIndex !== -1) {
  108712. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108713. baseMatrix.invertToRef(baseMatrix);
  108714. }
  108715. var babylonParentBone = null;
  108716. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108717. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108718. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108719. }
  108720. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108721. babylonBones[node._index] = babylonBone;
  108722. return babylonBone;
  108723. };
  108724. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108725. return node.matrix ?
  108726. BABYLON.Matrix.FromArray(node.matrix) :
  108727. 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());
  108728. };
  108729. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108730. var animations = this._gltf.animations;
  108731. if (!animations) {
  108732. return Promise.resolve();
  108733. }
  108734. var promises = new Array();
  108735. for (var index = 0; index < animations.length; index++) {
  108736. var animation = animations[index];
  108737. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108738. }
  108739. return Promise.all(promises).then(function () { });
  108740. };
  108741. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108742. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108743. animation._babylonAnimationGroup = babylonAnimationGroup;
  108744. var promises = new Array();
  108745. GLTF2.ArrayItem.Assign(animation.channels);
  108746. GLTF2.ArrayItem.Assign(animation.samplers);
  108747. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108748. var channel = _a[_i];
  108749. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108750. }
  108751. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  108752. return Promise.all(promises).then(function () {
  108753. babylonAnimationGroup.normalize();
  108754. });
  108755. };
  108756. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108757. var _this = this;
  108758. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108759. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  108760. return Promise.resolve();
  108761. }
  108762. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108763. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108764. var targetPath;
  108765. var animationType;
  108766. switch (channel.target.path) {
  108767. case "translation" /* TRANSLATION */: {
  108768. targetPath = "position";
  108769. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108770. break;
  108771. }
  108772. case "rotation" /* ROTATION */: {
  108773. targetPath = "rotationQuaternion";
  108774. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108775. break;
  108776. }
  108777. case "scale" /* SCALE */: {
  108778. targetPath = "scaling";
  108779. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108780. break;
  108781. }
  108782. case "weights" /* WEIGHTS */: {
  108783. targetPath = "influence";
  108784. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108785. break;
  108786. }
  108787. default: {
  108788. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  108789. }
  108790. }
  108791. var outputBufferOffset = 0;
  108792. var getNextOutputValue;
  108793. switch (targetPath) {
  108794. case "position": {
  108795. getNextOutputValue = function () {
  108796. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108797. outputBufferOffset += 3;
  108798. return value;
  108799. };
  108800. break;
  108801. }
  108802. case "rotationQuaternion": {
  108803. getNextOutputValue = function () {
  108804. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108805. outputBufferOffset += 4;
  108806. return value;
  108807. };
  108808. break;
  108809. }
  108810. case "scaling": {
  108811. getNextOutputValue = function () {
  108812. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108813. outputBufferOffset += 3;
  108814. return value;
  108815. };
  108816. break;
  108817. }
  108818. case "influence": {
  108819. getNextOutputValue = function () {
  108820. var value = new Array(targetNode._numMorphTargets);
  108821. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108822. value[i] = data.output[outputBufferOffset++];
  108823. }
  108824. return value;
  108825. };
  108826. break;
  108827. }
  108828. }
  108829. var getNextKey;
  108830. switch (data.interpolation) {
  108831. case "STEP" /* STEP */: {
  108832. getNextKey = function (frameIndex) { return ({
  108833. frame: data.input[frameIndex],
  108834. value: getNextOutputValue(),
  108835. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  108836. }); };
  108837. break;
  108838. }
  108839. case "LINEAR" /* LINEAR */: {
  108840. getNextKey = function (frameIndex) { return ({
  108841. frame: data.input[frameIndex],
  108842. value: getNextOutputValue()
  108843. }); };
  108844. break;
  108845. }
  108846. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108847. getNextKey = function (frameIndex) { return ({
  108848. frame: data.input[frameIndex],
  108849. inTangent: getNextOutputValue(),
  108850. value: getNextOutputValue(),
  108851. outTangent: getNextOutputValue()
  108852. }); };
  108853. break;
  108854. }
  108855. }
  108856. var keys;
  108857. if (data.input.length === 1) {
  108858. var key = getNextKey(0);
  108859. keys = [
  108860. { frame: key.frame, value: key.value },
  108861. { frame: key.frame + 1, value: key.value }
  108862. ];
  108863. }
  108864. else {
  108865. keys = new Array(data.input.length);
  108866. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  108867. keys[frameIndex] = getNextKey(frameIndex);
  108868. }
  108869. }
  108870. if (targetPath === "influence") {
  108871. var _loop_1 = function (targetIndex) {
  108872. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108873. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108874. babylonAnimation.setKeys(keys.map(function (key) { return ({
  108875. frame: key.frame,
  108876. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  108877. value: key.value[targetIndex],
  108878. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  108879. }); }));
  108880. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  108881. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  108882. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  108883. });
  108884. };
  108885. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  108886. _loop_1(targetIndex);
  108887. }
  108888. }
  108889. else {
  108890. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108891. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108892. babylonAnimation.setKeys(keys);
  108893. if (targetNode._babylonAnimationTargets) {
  108894. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  108895. var target = _a[_i];
  108896. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  108897. }
  108898. }
  108899. }
  108900. });
  108901. };
  108902. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  108903. if (sampler._data) {
  108904. return sampler._data;
  108905. }
  108906. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  108907. switch (interpolation) {
  108908. case "STEP" /* STEP */:
  108909. case "LINEAR" /* LINEAR */:
  108910. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108911. break;
  108912. }
  108913. default: {
  108914. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  108915. }
  108916. }
  108917. var inputData;
  108918. var outputData;
  108919. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  108920. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  108921. sampler._data = Promise.all([
  108922. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  108923. inputData = data;
  108924. }),
  108925. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  108926. outputData = data;
  108927. })
  108928. ]).then(function () {
  108929. return {
  108930. input: inputData,
  108931. interpolation: interpolation,
  108932. output: outputData,
  108933. };
  108934. });
  108935. return sampler._data;
  108936. };
  108937. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  108938. if (buffer._data) {
  108939. return buffer._data;
  108940. }
  108941. if (!buffer.uri) {
  108942. throw new Error(context + ": Uri is missing");
  108943. }
  108944. buffer._data = this._loadUriAsync(context, buffer.uri);
  108945. return buffer._data;
  108946. };
  108947. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  108948. if (bufferView._data) {
  108949. return bufferView._data;
  108950. }
  108951. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  108952. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  108953. try {
  108954. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  108955. }
  108956. catch (e) {
  108957. throw new Error(context + ": " + e.message);
  108958. }
  108959. });
  108960. return bufferView._data;
  108961. };
  108962. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  108963. var _this = this;
  108964. if (accessor.sparse) {
  108965. throw new Error(context + ": Sparse accessors are not currently supported");
  108966. }
  108967. if (accessor._data) {
  108968. return accessor._data;
  108969. }
  108970. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108971. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  108972. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  108973. var byteOffset = accessor.byteOffset || 0;
  108974. var byteStride = bufferView.byteStride;
  108975. if (byteStride === 0) {
  108976. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  108977. }
  108978. try {
  108979. switch (accessor.componentType) {
  108980. case 5120 /* BYTE */: {
  108981. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108982. }
  108983. case 5121 /* UNSIGNED_BYTE */: {
  108984. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108985. }
  108986. case 5122 /* SHORT */: {
  108987. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108988. }
  108989. case 5123 /* UNSIGNED_SHORT */: {
  108990. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108991. }
  108992. case 5125 /* UNSIGNED_INT */: {
  108993. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108994. }
  108995. case 5126 /* FLOAT */: {
  108996. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108997. }
  108998. default: {
  108999. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109000. }
  109001. }
  109002. }
  109003. catch (e) {
  109004. throw new Error(context + ": " + e.messsage);
  109005. }
  109006. });
  109007. return accessor._data;
  109008. };
  109009. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109010. byteOffset += data.byteOffset;
  109011. var targetLength = count * numComponents;
  109012. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109013. return new typedArray(data.buffer, byteOffset, targetLength);
  109014. }
  109015. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109016. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109017. var targetBuffer = new typedArray(targetLength);
  109018. var sourceIndex = 0;
  109019. var targetIndex = 0;
  109020. while (targetIndex < targetLength) {
  109021. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109022. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109023. targetIndex++;
  109024. }
  109025. sourceIndex += elementStride;
  109026. }
  109027. return targetBuffer;
  109028. };
  109029. GLTFLoader.prototype._getDefaultMaterial = function () {
  109030. var id = "__gltf_default";
  109031. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109032. if (!babylonMaterial) {
  109033. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109034. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109035. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109036. babylonMaterial.metallic = 1;
  109037. babylonMaterial.roughness = 1;
  109038. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109039. }
  109040. return babylonMaterial;
  109041. };
  109042. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109043. var promises = new Array();
  109044. var babylonMaterial = material._babylonMaterial;
  109045. // Ensure metallic workflow
  109046. babylonMaterial.metallic = 1;
  109047. babylonMaterial.roughness = 1;
  109048. var properties = material.pbrMetallicRoughness;
  109049. if (properties) {
  109050. if (properties.baseColorFactor) {
  109051. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109052. babylonMaterial.alpha = properties.baseColorFactor[3];
  109053. }
  109054. else {
  109055. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109056. }
  109057. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109058. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109059. if (properties.baseColorTexture) {
  109060. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109061. babylonMaterial.albedoTexture = texture;
  109062. }));
  109063. }
  109064. if (properties.metallicRoughnessTexture) {
  109065. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109066. babylonMaterial.metallicTexture = texture;
  109067. }));
  109068. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109069. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109070. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109071. }
  109072. }
  109073. this._loadMaterialAlphaProperties(context, material);
  109074. return Promise.all(promises).then(function () { });
  109075. };
  109076. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109077. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109078. if (promise) {
  109079. return promise;
  109080. }
  109081. material._babylonMeshes = material._babylonMeshes || [];
  109082. material._babylonMeshes.push(babylonMesh);
  109083. if (!material._loaded) {
  109084. var promises = new Array();
  109085. var babylonMaterial = this._createMaterial(material);
  109086. material._babylonMaterial = babylonMaterial;
  109087. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109088. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109089. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109090. material._loaded = Promise.all(promises).then(function () { });
  109091. }
  109092. assign(material._babylonMaterial);
  109093. return material._loaded;
  109094. };
  109095. GLTFLoader.prototype._createMaterial = function (material) {
  109096. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109097. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109098. return babylonMaterial;
  109099. };
  109100. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109101. var promises = new Array();
  109102. var babylonMaterial = material._babylonMaterial;
  109103. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109104. if (material.doubleSided) {
  109105. babylonMaterial.backFaceCulling = false;
  109106. babylonMaterial.twoSidedLighting = true;
  109107. }
  109108. if (material.normalTexture) {
  109109. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109110. babylonMaterial.bumpTexture = texture;
  109111. }));
  109112. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109113. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109114. if (material.normalTexture.scale != undefined) {
  109115. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109116. }
  109117. }
  109118. if (material.occlusionTexture) {
  109119. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109120. babylonMaterial.ambientTexture = texture;
  109121. }));
  109122. babylonMaterial.useAmbientInGrayScale = true;
  109123. if (material.occlusionTexture.strength != undefined) {
  109124. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109125. }
  109126. }
  109127. if (material.emissiveTexture) {
  109128. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109129. babylonMaterial.emissiveTexture = texture;
  109130. }));
  109131. }
  109132. return Promise.all(promises).then(function () { });
  109133. };
  109134. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109135. var babylonMaterial = material._babylonMaterial;
  109136. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109137. switch (alphaMode) {
  109138. case "OPAQUE" /* OPAQUE */: {
  109139. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109140. break;
  109141. }
  109142. case "MASK" /* MASK */: {
  109143. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109144. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109145. if (babylonMaterial.alpha) {
  109146. if (babylonMaterial.alpha === 0) {
  109147. babylonMaterial.alphaCutOff = 1;
  109148. }
  109149. else {
  109150. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109151. }
  109152. babylonMaterial.alpha = 1;
  109153. }
  109154. if (babylonMaterial.albedoTexture) {
  109155. babylonMaterial.albedoTexture.hasAlpha = true;
  109156. }
  109157. break;
  109158. }
  109159. case "BLEND" /* BLEND */: {
  109160. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109161. if (babylonMaterial.albedoTexture) {
  109162. babylonMaterial.albedoTexture.hasAlpha = true;
  109163. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109164. }
  109165. break;
  109166. }
  109167. default: {
  109168. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109169. }
  109170. }
  109171. };
  109172. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109173. var _this = this;
  109174. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109175. context = "#/textures/" + textureInfo.index;
  109176. var promises = new Array();
  109177. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109178. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109179. var deferred = new BABYLON.Deferred();
  109180. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109181. if (!_this._disposed) {
  109182. deferred.resolve();
  109183. }
  109184. }, function (message, exception) {
  109185. if (!_this._disposed) {
  109186. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109187. }
  109188. });
  109189. promises.push(deferred.promise);
  109190. babylonTexture.name = texture.name || "texture" + texture._index;
  109191. babylonTexture.wrapU = samplerData.wrapU;
  109192. babylonTexture.wrapV = samplerData.wrapV;
  109193. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109194. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109195. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109196. babylonTexture.updateURL(objectURL);
  109197. }));
  109198. assign(babylonTexture);
  109199. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109200. return Promise.all(promises).then(function () { });
  109201. };
  109202. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109203. if (!sampler._data) {
  109204. sampler._data = {
  109205. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109206. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109207. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109208. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109209. };
  109210. }
  109211. ;
  109212. return sampler._data;
  109213. };
  109214. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109215. if (image._objectURL) {
  109216. return image._objectURL;
  109217. }
  109218. var promise;
  109219. if (image.uri) {
  109220. promise = this._loadUriAsync(context, image.uri);
  109221. }
  109222. else {
  109223. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109224. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109225. }
  109226. image._objectURL = promise.then(function (data) {
  109227. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109228. });
  109229. return image._objectURL;
  109230. };
  109231. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109232. var _this = this;
  109233. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109234. if (promise) {
  109235. return promise;
  109236. }
  109237. if (!GLTFLoader._ValidateUri(uri)) {
  109238. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109239. }
  109240. if (BABYLON.Tools.IsBase64(uri)) {
  109241. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109242. }
  109243. return new Promise(function (resolve, reject) {
  109244. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109245. if (!_this._disposed) {
  109246. resolve(new Uint8Array(data));
  109247. }
  109248. }, function (event) {
  109249. if (!_this._disposed) {
  109250. try {
  109251. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109252. request._lengthComputable = event.lengthComputable;
  109253. request._loaded = event.loaded;
  109254. request._total = event.total;
  109255. _this._onProgress();
  109256. }
  109257. }
  109258. catch (e) {
  109259. reject(e);
  109260. }
  109261. }
  109262. }, _this._babylonScene.database, true, function (request, exception) {
  109263. if (!_this._disposed) {
  109264. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109265. }
  109266. });
  109267. _this._requests.push(request);
  109268. });
  109269. };
  109270. GLTFLoader.prototype._onProgress = function () {
  109271. if (!this._progressCallback) {
  109272. return;
  109273. }
  109274. var lengthComputable = true;
  109275. var loaded = 0;
  109276. var total = 0;
  109277. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109278. var request = _a[_i];
  109279. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109280. return;
  109281. }
  109282. lengthComputable = lengthComputable && request._lengthComputable;
  109283. loaded += request._loaded;
  109284. total += request._total;
  109285. }
  109286. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109287. };
  109288. GLTFLoader._GetProperty = function (context, array, index) {
  109289. if (!array || index == undefined || !array[index]) {
  109290. throw new Error(context + ": Failed to find index (" + index + ")");
  109291. }
  109292. return array[index];
  109293. };
  109294. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109295. // Set defaults if undefined
  109296. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109297. switch (mode) {
  109298. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109299. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109300. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109301. default:
  109302. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109303. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109304. }
  109305. };
  109306. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109307. // Set defaults if undefined
  109308. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109309. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109310. if (magFilter === 9729 /* LINEAR */) {
  109311. switch (minFilter) {
  109312. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109313. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109314. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109315. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109316. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109317. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109318. default:
  109319. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109320. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109321. }
  109322. }
  109323. else {
  109324. if (magFilter !== 9728 /* NEAREST */) {
  109325. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109326. }
  109327. switch (minFilter) {
  109328. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109329. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109330. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109331. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109332. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109333. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109334. default:
  109335. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109336. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109337. }
  109338. }
  109339. };
  109340. GLTFLoader._GetNumComponents = function (context, type) {
  109341. switch (type) {
  109342. case "SCALAR": return 1;
  109343. case "VEC2": return 2;
  109344. case "VEC3": return 3;
  109345. case "VEC4": return 4;
  109346. case "MAT2": return 4;
  109347. case "MAT3": return 9;
  109348. case "MAT4": return 16;
  109349. }
  109350. throw new Error(context + ": Invalid type (" + type + ")");
  109351. };
  109352. GLTFLoader._ValidateUri = function (uri) {
  109353. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109354. };
  109355. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109356. var promises = new Array();
  109357. if (this._gltf.materials) {
  109358. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109359. var material = _a[_i];
  109360. var babylonMaterial = material._babylonMaterial;
  109361. var babylonMeshes = material._babylonMeshes;
  109362. if (babylonMaterial && babylonMeshes) {
  109363. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109364. var babylonMesh = babylonMeshes_1[_b];
  109365. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109366. if (this.useClipPlane) {
  109367. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109368. }
  109369. }
  109370. }
  109371. }
  109372. }
  109373. return Promise.all(promises).then(function () { });
  109374. };
  109375. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109376. var promises = new Array();
  109377. var lights = this._babylonScene.lights;
  109378. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109379. var light = lights_1[_i];
  109380. var generator = light.getShadowGenerator();
  109381. if (generator) {
  109382. promises.push(generator.forceCompilationAsync());
  109383. }
  109384. }
  109385. return Promise.all(promises).then(function () { });
  109386. };
  109387. GLTFLoader.prototype._clear = function () {
  109388. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109389. var request = _a[_i];
  109390. request.abort();
  109391. }
  109392. this._requests.length = 0;
  109393. if (this._gltf && this._gltf.images) {
  109394. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109395. var image = _c[_b];
  109396. if (image._objectURL) {
  109397. image._objectURL.then(function (value) {
  109398. URL.revokeObjectURL(value);
  109399. });
  109400. image._objectURL = undefined;
  109401. }
  109402. }
  109403. }
  109404. delete this._gltf;
  109405. delete this._babylonScene;
  109406. this._completePromises.length = 0;
  109407. for (var name_3 in this._extensions) {
  109408. this._extensions[name_3].dispose();
  109409. }
  109410. this._extensions = {};
  109411. delete this._rootBabylonMesh;
  109412. delete this._progressCallback;
  109413. this.onMeshLoadedObservable.clear();
  109414. this.onTextureLoadedObservable.clear();
  109415. this.onMaterialLoadedObservable.clear();
  109416. };
  109417. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109418. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109419. var name_4 = _a[_i];
  109420. var extension = this._extensions[name_4];
  109421. if (extension.enabled) {
  109422. var promise = actionAsync(extension);
  109423. if (promise) {
  109424. return promise;
  109425. }
  109426. }
  109427. }
  109428. return null;
  109429. };
  109430. GLTFLoader._Names = new Array();
  109431. GLTFLoader._Factories = {};
  109432. return GLTFLoader;
  109433. }());
  109434. GLTF2.GLTFLoader = GLTFLoader;
  109435. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  109436. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109437. })(BABYLON || (BABYLON = {}));
  109438. //# sourceMappingURL=babylon.glTFLoader.js.map
  109439. var BABYLON;
  109440. (function (BABYLON) {
  109441. var GLTF2;
  109442. (function (GLTF2) {
  109443. var GLTFLoaderExtension = /** @class */ (function () {
  109444. function GLTFLoaderExtension(loader) {
  109445. this.enabled = true;
  109446. this._loader = loader;
  109447. }
  109448. GLTFLoaderExtension.prototype.dispose = function () {
  109449. delete this._loader;
  109450. };
  109451. // #region Overridable Methods
  109452. /** Override this method to modify the default behavior for loading scenes. */
  109453. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109454. /** Override this method to modify the default behavior for loading nodes. */
  109455. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109456. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  109457. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109458. /** Override this method to modify the default behavior for loading materials. */
  109459. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  109460. /** Override this method to modify the default behavior for loading uris. */
  109461. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109462. // #endregion
  109463. /** Helper method called by a loader extension to load an glTF extension. */
  109464. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109465. if (!property.extensions) {
  109466. return null;
  109467. }
  109468. var extensions = property.extensions;
  109469. var extension = extensions[this.name];
  109470. if (!extension) {
  109471. return null;
  109472. }
  109473. // Clear out the extension before executing the action to avoid recursing into the same property.
  109474. delete extensions[this.name];
  109475. try {
  109476. return actionAsync(context + "/extensions/" + this.name, extension);
  109477. }
  109478. finally {
  109479. // Restore the extension after executing the action.
  109480. extensions[this.name] = extension;
  109481. }
  109482. };
  109483. /** Helper method called by the loader to allow extensions to override loading scenes. */
  109484. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109485. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109486. };
  109487. /** Helper method called by the loader to allow extensions to override loading nodes. */
  109488. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109489. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109490. };
  109491. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  109492. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109493. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109494. };
  109495. /** Helper method called by the loader to allow extensions to override loading materials. */
  109496. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  109497. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  109498. };
  109499. /** Helper method called by the loader to allow extensions to override loading uris. */
  109500. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109501. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109502. };
  109503. return GLTFLoaderExtension;
  109504. }());
  109505. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109506. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109507. })(BABYLON || (BABYLON = {}));
  109508. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109509. var BABYLON;
  109510. (function (BABYLON) {
  109511. var GLTF2;
  109512. (function (GLTF2) {
  109513. var Extensions;
  109514. (function (Extensions) {
  109515. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  109516. var NAME = "MSFT_lod";
  109517. var MSFT_lod = /** @class */ (function (_super) {
  109518. __extends(MSFT_lod, _super);
  109519. function MSFT_lod() {
  109520. var _this = _super !== null && _super.apply(this, arguments) || this;
  109521. _this.name = NAME;
  109522. /**
  109523. * Maximum number of LODs to load, starting from the lowest LOD.
  109524. */
  109525. _this.maxLODsToLoad = Number.MAX_VALUE;
  109526. _this._loadingNodeLOD = null;
  109527. _this._loadNodeSignals = {};
  109528. _this._loadingMaterialLOD = null;
  109529. _this._loadMaterialSignals = {};
  109530. return _this;
  109531. }
  109532. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109533. var _this = this;
  109534. return this._loadExtensionAsync(context, node, function (context, extension) {
  109535. var firstPromise;
  109536. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  109537. var _loop_1 = function (indexLOD) {
  109538. var nodeLOD = nodeLODs[indexLOD];
  109539. if (indexLOD !== 0) {
  109540. _this._loadingNodeLOD = nodeLOD;
  109541. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109542. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109543. }
  109544. }
  109545. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109546. if (indexLOD !== 0) {
  109547. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109548. if (previousNodeLOD._babylonMesh) {
  109549. previousNodeLOD._babylonMesh.dispose();
  109550. delete previousNodeLOD._babylonMesh;
  109551. }
  109552. }
  109553. if (indexLOD !== nodeLODs.length - 1) {
  109554. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109555. if (_this._loadNodeSignals[nodeIndex]) {
  109556. _this._loadNodeSignals[nodeIndex].resolve();
  109557. delete _this._loadNodeSignals[nodeIndex];
  109558. }
  109559. }
  109560. });
  109561. if (indexLOD === 0) {
  109562. firstPromise = promise;
  109563. }
  109564. else {
  109565. _this._loader._completePromises.push(promise);
  109566. _this._loadingNodeLOD = null;
  109567. }
  109568. };
  109569. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109570. _loop_1(indexLOD);
  109571. }
  109572. return firstPromise;
  109573. });
  109574. };
  109575. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109576. var _this = this;
  109577. // Don't load material LODs if already loading a node LOD.
  109578. if (this._loadingNodeLOD) {
  109579. return null;
  109580. }
  109581. return this._loadExtensionAsync(context, material, function (context, extension) {
  109582. var firstPromise;
  109583. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109584. var _loop_2 = function (indexLOD) {
  109585. var materialLOD = materialLODs[indexLOD];
  109586. if (indexLOD !== 0) {
  109587. _this._loadingMaterialLOD = materialLOD;
  109588. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109589. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109590. }
  109591. }
  109592. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  109593. if (indexLOD !== 0) {
  109594. assign(materialLOD._babylonMaterial);
  109595. var previousMaterialLOD = materialLODs[indexLOD - 1];
  109596. if (previousMaterialLOD._babylonMaterial) {
  109597. previousMaterialLOD._babylonMaterial.dispose();
  109598. delete previousMaterialLOD._babylonMaterial;
  109599. }
  109600. }
  109601. if (indexLOD !== materialLODs.length - 1) {
  109602. var materialIndex = materialLODs[indexLOD + 1]._index;
  109603. if (_this._loadMaterialSignals[materialIndex]) {
  109604. _this._loadMaterialSignals[materialIndex].resolve();
  109605. delete _this._loadMaterialSignals[materialIndex];
  109606. }
  109607. }
  109608. });
  109609. if (indexLOD === 0) {
  109610. firstPromise = promise;
  109611. }
  109612. else {
  109613. _this._loader._completePromises.push(promise);
  109614. _this._loadingMaterialLOD = null;
  109615. }
  109616. };
  109617. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109618. _loop_2(indexLOD);
  109619. }
  109620. return firstPromise;
  109621. });
  109622. };
  109623. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109624. var _this = this;
  109625. // Defer the loading of uris if loading a material or node LOD.
  109626. if (this._loadingMaterialLOD) {
  109627. var index = this._loadingMaterialLOD._index;
  109628. return this._loadMaterialSignals[index].promise.then(function () {
  109629. return _this._loader._loadUriAsync(context, uri);
  109630. });
  109631. }
  109632. else if (this._loadingNodeLOD) {
  109633. var index = this._loadingNodeLOD._index;
  109634. return this._loadNodeSignals[index].promise.then(function () {
  109635. return _this._loader._loadUriAsync(context, uri);
  109636. });
  109637. }
  109638. return null;
  109639. };
  109640. /**
  109641. * Gets an array of LOD properties from lowest to highest.
  109642. */
  109643. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109644. if (this.maxLODsToLoad <= 0) {
  109645. throw new Error("maxLODsToLoad must be greater than zero");
  109646. }
  109647. var properties = new Array();
  109648. for (var i = ids.length - 1; i >= 0; i--) {
  109649. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109650. if (properties.length === this.maxLODsToLoad) {
  109651. return properties;
  109652. }
  109653. }
  109654. properties.push(property);
  109655. return properties;
  109656. };
  109657. return MSFT_lod;
  109658. }(GLTF2.GLTFLoaderExtension));
  109659. Extensions.MSFT_lod = MSFT_lod;
  109660. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109661. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109662. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109663. })(BABYLON || (BABYLON = {}));
  109664. //# sourceMappingURL=MSFT_lod.js.map
  109665. var BABYLON;
  109666. (function (BABYLON) {
  109667. var GLTF2;
  109668. (function (GLTF2) {
  109669. var Extensions;
  109670. (function (Extensions) {
  109671. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109672. var NAME = "KHR_draco_mesh_compression";
  109673. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109674. __extends(KHR_draco_mesh_compression, _super);
  109675. function KHR_draco_mesh_compression(loader) {
  109676. var _this = _super.call(this, loader) || this;
  109677. _this.name = NAME;
  109678. _this._dracoCompression = null;
  109679. // Disable extension if decoder is not available.
  109680. if (!BABYLON.DracoCompression.DecoderUrl) {
  109681. _this.enabled = false;
  109682. }
  109683. return _this;
  109684. }
  109685. KHR_draco_mesh_compression.prototype.dispose = function () {
  109686. if (this._dracoCompression) {
  109687. this._dracoCompression.dispose();
  109688. }
  109689. _super.prototype.dispose.call(this);
  109690. };
  109691. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109692. var _this = this;
  109693. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109694. if (primitive.mode != undefined) {
  109695. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109696. primitive.mode !== 4 /* TRIANGLES */) {
  109697. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109698. }
  109699. // TODO: handle triangle strips
  109700. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109701. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109702. }
  109703. }
  109704. var attributes = {};
  109705. var loadAttribute = function (name, kind) {
  109706. var uniqueId = extension.attributes[name];
  109707. if (uniqueId == undefined) {
  109708. return;
  109709. }
  109710. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109711. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109712. babylonMesh._delayInfo.push(kind);
  109713. }
  109714. attributes[kind] = uniqueId;
  109715. };
  109716. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109717. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109718. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109719. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109720. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109721. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109722. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109723. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109724. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109725. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109726. try {
  109727. if (!_this._dracoCompression) {
  109728. _this._dracoCompression = new BABYLON.DracoCompression();
  109729. }
  109730. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  109731. }
  109732. catch (e) {
  109733. throw new Error(context + ": " + e.message);
  109734. }
  109735. });
  109736. });
  109737. };
  109738. return KHR_draco_mesh_compression;
  109739. }(GLTF2.GLTFLoaderExtension));
  109740. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109741. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109742. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109743. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109744. })(BABYLON || (BABYLON = {}));
  109745. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109746. var BABYLON;
  109747. (function (BABYLON) {
  109748. var GLTF2;
  109749. (function (GLTF2) {
  109750. var Extensions;
  109751. (function (Extensions) {
  109752. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  109753. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109754. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109755. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109756. function KHR_materials_pbrSpecularGlossiness() {
  109757. var _this = _super !== null && _super.apply(this, arguments) || this;
  109758. _this.name = NAME;
  109759. return _this;
  109760. }
  109761. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109762. var _this = this;
  109763. return this._loadExtensionAsync(context, material, function (context, extension) {
  109764. material._babylonMeshes = material._babylonMeshes || [];
  109765. material._babylonMeshes.push(babylonMesh);
  109766. if (!material._loaded) {
  109767. var promises = new Array();
  109768. var babylonMaterial = _this._loader._createMaterial(material);
  109769. material._babylonMaterial = babylonMaterial;
  109770. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  109771. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  109772. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109773. material._loaded = Promise.all(promises).then(function () { });
  109774. }
  109775. assign(material._babylonMaterial);
  109776. return material._loaded;
  109777. });
  109778. };
  109779. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  109780. var promises = new Array();
  109781. var babylonMaterial = material._babylonMaterial;
  109782. if (properties.diffuseFactor) {
  109783. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109784. babylonMaterial.alpha = properties.diffuseFactor[3];
  109785. }
  109786. else {
  109787. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109788. }
  109789. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109790. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109791. if (properties.diffuseTexture) {
  109792. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109793. babylonMaterial.albedoTexture = texture;
  109794. }));
  109795. }
  109796. if (properties.specularGlossinessTexture) {
  109797. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109798. babylonMaterial.reflectivityTexture = texture;
  109799. }));
  109800. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109801. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109802. }
  109803. this._loader._loadMaterialAlphaProperties(context, material);
  109804. return Promise.all(promises).then(function () { });
  109805. };
  109806. return KHR_materials_pbrSpecularGlossiness;
  109807. }(GLTF2.GLTFLoaderExtension));
  109808. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109809. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109810. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109811. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109812. })(BABYLON || (BABYLON = {}));
  109813. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109814. var BABYLON;
  109815. (function (BABYLON) {
  109816. var GLTF2;
  109817. (function (GLTF2) {
  109818. var Extensions;
  109819. (function (Extensions) {
  109820. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  109821. var NAME = "KHR_lights";
  109822. var LightType;
  109823. (function (LightType) {
  109824. LightType["AMBIENT"] = "ambient";
  109825. LightType["DIRECTIONAL"] = "directional";
  109826. LightType["POINT"] = "point";
  109827. LightType["SPOT"] = "spot";
  109828. })(LightType || (LightType = {}));
  109829. var KHR_lights = /** @class */ (function (_super) {
  109830. __extends(KHR_lights, _super);
  109831. function KHR_lights() {
  109832. var _this = _super !== null && _super.apply(this, arguments) || this;
  109833. _this.name = NAME;
  109834. return _this;
  109835. }
  109836. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109837. var _this = this;
  109838. return this._loadExtensionAsync(context, scene, function (context, extension) {
  109839. var promise = _this._loader._loadSceneAsync(context, scene);
  109840. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109841. if (light.type !== LightType.AMBIENT) {
  109842. throw new Error(context + ": Only ambient lights are allowed on a scene");
  109843. }
  109844. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109845. return promise;
  109846. });
  109847. };
  109848. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109849. var _this = this;
  109850. return this._loadExtensionAsync(context, node, function (context, extension) {
  109851. var promise = _this._loader._loadNodeAsync(context, node);
  109852. var babylonLight;
  109853. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109854. var name = node._babylonMesh.name;
  109855. switch (light.type) {
  109856. case LightType.AMBIENT: {
  109857. throw new Error(context + ": Ambient lights are not allowed on a node");
  109858. }
  109859. case LightType.DIRECTIONAL: {
  109860. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  109861. break;
  109862. }
  109863. case LightType.POINT: {
  109864. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  109865. break;
  109866. }
  109867. case LightType.SPOT: {
  109868. var spotLight = light;
  109869. // TODO: support inner and outer cone angles
  109870. //const innerConeAngle = spotLight.innerConeAngle || 0;
  109871. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  109872. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  109873. break;
  109874. }
  109875. default: {
  109876. throw new Error(context + ": Invalid light type (" + light.type + ")");
  109877. }
  109878. }
  109879. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  109880. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  109881. babylonLight.parent = node._babylonMesh;
  109882. return promise;
  109883. });
  109884. };
  109885. Object.defineProperty(KHR_lights.prototype, "_lights", {
  109886. get: function () {
  109887. var extensions = this._loader._gltf.extensions;
  109888. if (!extensions || !extensions[this.name]) {
  109889. throw new Error("#/extensions: '" + this.name + "' not found");
  109890. }
  109891. var extension = extensions[this.name];
  109892. return extension.lights;
  109893. },
  109894. enumerable: true,
  109895. configurable: true
  109896. });
  109897. return KHR_lights;
  109898. }(GLTF2.GLTFLoaderExtension));
  109899. Extensions.KHR_lights = KHR_lights;
  109900. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  109901. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109902. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109903. })(BABYLON || (BABYLON = {}));
  109904. //# sourceMappingURL=KHR_lights.js.map
  109905. return BABYLON;
  109906. });
  109907. /***/ }),
  109908. /* 33 */
  109909. /***/ (function(module, exports, __webpack_require__) {
  109910. /*!
  109911. * PEP v0.4.3 | https://github.com/jquery/PEP
  109912. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  109913. */
  109914. !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);
  109915. // define inherited MouseEvent properties
  109916. // skip bubbles and cancelable since they're set above in initEvent()
  109917. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  109918. // Spec requires that pointers without pressure specified use 0.5 for down
  109919. // state and 0 for up state.
  109920. var f=0;
  109921. // add x/y properties aliased to clientX/Y
  109922. // define the properties of the PointerEvent interface
  109923. 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(){
  109924. // only activate if this platform does not have pointer events
  109925. 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}})}/**
  109926. * This is the constructor for new PointerEvents.
  109927. *
  109928. * New Pointer Events must be given a type, and an optional dictionary of
  109929. * initialization properties.
  109930. *
  109931. * Due to certain platform requirements, events returned from the constructor
  109932. * identify as MouseEvents.
  109933. *
  109934. * @constructor
  109935. * @param {String} inType The type of the event to create.
  109936. * @param {Object} [inDict] An optional dictionary of initial event properties.
  109937. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  109938. */
  109939. 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},
  109940. // return value, key, map
  109941. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  109942. // MouseEvent
  109943. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  109944. // DOM Level 3
  109945. "buttons",
  109946. // PointerEvent
  109947. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  109948. // event instance
  109949. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  109950. // MouseEvent
  109951. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  109952. // DOM Level 3
  109953. 0,
  109954. // PointerEvent
  109955. 0,0,0,0,0,0,"",0,!1,
  109956. // event instance
  109957. "",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),
  109958. // Scope objects for native events.
  109959. // This exists for ease of testing.
  109960. eventSources:Object.create(null),eventSourceList:[],/**
  109961. * Add a new event source that will generate pointer events.
  109962. *
  109963. * `inSource` must contain an array of event names named `events`, and
  109964. * functions with the names specified in the `events` array.
  109965. * @param {string} name A name for the event source
  109966. * @param {Object} source A new source of platform events.
  109967. */
  109968. 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++)
  109969. // call eventsource register
  109970. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  109971. // call eventsource register
  109972. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  109973. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  109974. return!1}},
  109975. // EVENTS
  109976. 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)},
  109977. // LISTENER LOGIC
  109978. eventHandler:function(a){
  109979. // This is used to prevent multiple dispatch of pointerevents from
  109980. // platform events. This can happen when two elements in different scopes
  109981. // are set up to create pointer events, which is relevant to Shadow DOM.
  109982. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  109983. // set up event listeners
  109984. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  109985. // remove event listeners
  109986. 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)},
  109987. // EVENT CREATION AND TRACKING
  109988. /**
  109989. * Creates a new Event of type `inType`, based on the information in
  109990. * `inEvent`.
  109991. *
  109992. * @param {string} inType A string representing the type of event to create
  109993. * @param {Event} inEvent A platform event with a target
  109994. * @return {Event} A PointerEvent of type `inType`
  109995. */
  109996. makeEvent:function(b,c){
  109997. // relatedTarget must be null if pointer is captured
  109998. 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},
  109999. // make and dispatch an event in one call
  110000. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110001. * Returns a snapshot of inEvent, with writable properties.
  110002. *
  110003. * @param {Event} inEvent An event that contains properties to copy.
  110004. * @return {Object} An object containing shallow copies of `inEvent`'s
  110005. * properties.
  110006. */
  110007. 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],
  110008. // Work around SVGInstanceElement shadow tree
  110009. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110010. // This is the behavior implemented by Firefox.
  110011. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110012. // keep the semantics of preventDefault
  110013. 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){
  110014. // Order of conditions due to document.contains() missing in IE.
  110015. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110016. // Touch: Do not propagate if node is detached.
  110017. 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)}},/**
  110018. * Dispatches the event to its target.
  110019. *
  110020. * @param {Event} inEvent The event to be dispatched.
  110021. * @return {Boolean} True if an event handler returns true, false otherwise.
  110022. */
  110023. 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(
  110024. // is element a shadow host?
  110025. e=this.targetingShadow(f);e;){if(
  110026. // find the the element inside the shadow root
  110027. d=e.elementFromPoint(b,c)){
  110028. // shadowed element may contain a shadow root
  110029. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110030. // check for older shadows
  110031. e=this.olderShadow(e)}
  110032. // light dom element is the target
  110033. return f}},owner:function(a){
  110034. // walk up until you hit the shadow root or document
  110035. for(var b=a;b.parentNode;)b=b.parentNode;
  110036. // the owner element is expected to be a Document or ShadowRoot
  110037. 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);
  110038. // if x, y is not in this root, fall back to document search
  110039. 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){
  110040. // Only watch scopes that can target find, as these are top-level.
  110041. // Otherwise we can see duplicate additions and removals that add noise.
  110042. //
  110043. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110044. // a removal without an insertion when a node is redistributed among
  110045. // shadows. Since it all ends up correct in the document, watching only
  110046. // the document will yield the correct mutations to watch.
  110047. 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))},
  110048. // register all touch-action = none nodes on document load
  110049. 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){
  110050. // find children with touch-action
  110051. var b=x(a,this.findElements,this);
  110052. // flatten the list
  110053. // make sure the added nodes are accounted for
  110054. 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){}
  110055. // handler block for native mouse events
  110056. 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:[],
  110057. // collide with the global mouse listener
  110058. 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++){
  110059. // simulated mouse events will be swallowed near a primary touchend
  110060. 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);
  110061. // Update buttons state after possible out-of-document mouseup.
  110062. 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];
  110063. // Produces wrong state of buttons in Browsers without `buttons` support
  110064. // when a mouse button that was pressed outside the document is released
  110065. // inside and other buttons are still pressed down.
  110066. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110067. // Support: Firefox <=44 only
  110068. // FF Ubuntu includes the lifted button in the `buttons` property on
  110069. // mouseup.
  110070. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110071. 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),
  110072. // set touch-action on shadows as well
  110073. 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),
  110074. // remove touch-action from shadow
  110075. 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);
  110076. // simply update scrollType if listeners are already established
  110077. 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){
  110078. // set primary touch if there no pointers, or the only pointer is the mouse
  110079. (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,
  110080. // forward modifier keys
  110081. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110082. // forward touch preventDefaults
  110083. 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))},
  110084. // For single axis scrollers, determines whether the element should emit
  110085. // pointer events or behave as a scroller
  110086. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110087. // this element is a touch-action: none, should never scroll
  110088. b=!1;else if("XY"===c)
  110089. // this element should always scroll
  110090. 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]);
  110091. // if delta in the scroll axis > delta other axis, scroll instead of
  110092. // making events
  110093. 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},
  110094. // In some instances, a touchstart can happen without a touchend. This
  110095. // leaves the pointermap in a broken state.
  110096. // Therefore, on every touchstart, we remove the touches that did not fire a
  110097. // touchend event.
  110098. // To keep state globally consistent, we fire a
  110099. // pointercancel for this "abandoned" touch
  110100. vacuumTouches:function(a){var b=a.touches;
  110101. // pointermap.size should be < tl.length here, as the touchstart has not
  110102. // been processed yet.
  110103. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110104. // Never remove pointerId == 1, which is mouse.
  110105. // Touch identifiers are 2 smaller than their pointerId, which is the
  110106. // index in pointermap.
  110107. 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);
  110108. // a finger drifted off the screen, ignore it
  110109. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110110. // recover from retargeting by shadow
  110111. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110112. // clean up case when finger leaves the screen
  110113. 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)},
  110114. // prevent synth mouse events from creating pointer events
  110115. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110116. // only the primary finger will synth mouse events
  110117. if(this.isPrimaryTouch(c)){
  110118. // remember x/y of last touch
  110119. 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});
  110120. /***/ }),
  110121. /* 34 */
  110122. /***/ (function(module, exports, __webpack_require__) {
  110123. "use strict";
  110124. Object.defineProperty(exports, "__esModule", { value: true });
  110125. var defaultViewer_1 = __webpack_require__(4);
  110126. var mappers_1 = __webpack_require__(1);
  110127. function InitTags(selector) {
  110128. if (selector === void 0) { selector = 'babylon'; }
  110129. var elements = document.querySelectorAll(selector);
  110130. for (var i = 0; i < elements.length; ++i) {
  110131. var element = elements.item(i);
  110132. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110133. var config = configMapper.map(element);
  110134. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110135. }
  110136. }
  110137. exports.InitTags = InitTags;
  110138. /***/ })
  110139. /******/ ]);
  110140. return BabylonViewer;
  110141. });